[openssl-commits] [openssl] master update

Matt Caswell matt at openssl.org
Fri Nov 4 12:12:29 UTC 2016


The branch master has been updated
       via  c42a78cb57cd335f3e2b224d4d8c8d7c2ecfaa44 (commit)
       via  ff04799d904ec2bfcfc3a3ca656549db2dec9068 (commit)
       via  ed9fa2c74bbb9da312aa82865aeb3f9b75a8167b (commit)
       via  54105ddd230c0d77fab91dd3f423b58b2a976de7 (commit)
       via  740bfebaf6d879f051da625d3c583f7cbba8944f (commit)
       via  02ba18a63e1f4ae1d0c0a185f9b7701fcddc1835 (commit)
       via  8d2b1819ef66206d19c1b0ecbf3ca882fed04721 (commit)
       via  be2ef0e2e3842114054d26c3429016dc894a1359 (commit)
       via  2b7363ecf168f94e5d982cd49182aa923b92d3e4 (commit)
       via  3cdc2f8fb528a4d47436dd863f6b8d5c30619847 (commit)
       via  6782e5fdd885cbd09ecbc063f3c1116c2962ecae (commit)
       via  d0ee717c938cda00bcb13cac2f7e2b162616254b (commit)
       via  f0ca8f89f866fd2214241758b8485a462d3f6f01 (commit)
       via  d02ef3d0be3b2cb1e6b3905ad26fc03ec261b317 (commit)
       via  7714dc5ea1174ca50cd12e5013683284f66c2dd3 (commit)
       via  699ae85915f83f91bf5d5af45dd4888217005461 (commit)
       via  2688e7a0beb0f5e76a98749f25b978ddfb40ac7f (commit)
       via  708e06c55d9fee5d59e4a4f409d115423ea1fa56 (commit)
       via  56a26ce3600cc9f96da0e64b345a25276d9abfc0 (commit)
       via  348240c676a1b2beaebb865e8be0b62f88c10b7d (commit)
       via  a14aa99be8fe169bba7afc6355b6b6d750b2ba1d (commit)
       via  c08d12ca40e031e652e84cd235e8394cf883fd1f (commit)
       via  153703dfde6bf3f1cf72576a19d0f2fabe61a826 (commit)
       via  8051ab2b6f8e1fb9e957771afcc3555560f9694f (commit)
       via  8b0e934afbdf8ca61866263c507d4b653135952d (commit)
       via  e3c9727fece7bd73469e14796f579c4dc5209cdb (commit)
       via  d736bc1a7d45744300b2c81f7296b0d1e550ae0d (commit)
       via  6db6bc5a8f0663e679a99ea91a6f490db0f183ba (commit)
       via  cb150cbcaca651a5b32fc1f1fc94ca61285c3515 (commit)
       via  12472b456180cbc582d6152e174135524081c3ba (commit)
       via  ec60ccc1c1b9562359753e8fcbeeab0a6b4b669c (commit)
       via  8c1a534305054c58d783fdfe7adbed24f5893a2e (commit)
       via  b43d1cbb9abb331bbaa29658b4af434c7b870c56 (commit)
       via  d0e7c31db04349882855add5a5a21977b4467e3d (commit)
       via  72716e79bf1207625d58f4fe3874303ac47d0f98 (commit)
       via  5607b2759a3148be6f38a9205d225bc8c802eaf1 (commit)
       via  7ee8627f6eb7cf63b34d2701d76bb66f6db811e5 (commit)
       via  eda757514ea3018c8510b4738b5e37479aeadc5e (commit)
       via  8e6d03cac4c34dc089751f36120b69c512f77756 (commit)
      from  a1ca39c02c5507536ee586e787f12f9ea3ea908b (commit)


- Log -----------------------------------------------------------------
commit c42a78cb57cd335f3e2b224d4d8c8d7c2ecfaa44
Author: Matt Caswell <matt at openssl.org>
Date:   Fri Nov 4 10:26:57 2016 +0000

    Fix a missed size_t variable declaration
    
    pqueue_size() now returns a size_t, but the variable that gets returned
    was still declared as an int.
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit ff04799d904ec2bfcfc3a3ca656549db2dec9068
Author: Matt Caswell <matt at openssl.org>
Date:   Fri Nov 4 10:25:03 2016 +0000

    Fix some style issues from libssl size_tify review
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit ed9fa2c74bbb9da312aa82865aeb3f9b75a8167b
Author: Matt Caswell <matt at openssl.org>
Date:   Wed Oct 26 20:59:49 2016 +0100

    Tweak the SSL_read()/SSL_write() text based on feedback received.
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 54105ddd230c0d77fab91dd3f423b58b2a976de7
Author: Matt Caswell <matt at openssl.org>
Date:   Wed Oct 26 10:43:34 2016 +0100

    Rename all "read" variables with "readbytes"
    
    Travis is reporting one file at a time shadowed variable warnings where
    "read" has been used. This attempts to go through all of libssl and replace
    "read" with "readbytes" to fix all the problems in one go.
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 740bfebaf6d879f051da625d3c583f7cbba8944f
Author: Matt Caswell <matt at openssl.org>
Date:   Tue Oct 25 23:46:27 2016 +0100

    Clarify the return values for SSL_read_ex()/SSL_write_ex()
    
    Give more detail on what constitutes success/failure.
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 02ba18a63e1f4ae1d0c0a185f9b7701fcddc1835
Author: Matt Caswell <matt at openssl.org>
Date:   Tue Oct 25 23:27:16 2016 +0100

    Fix a shadowed variable declaration warning picked up by Travis
    
    Rename "read" to "readbytes"
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 8d2b1819ef66206d19c1b0ecbf3ca882fed04721
Author: Matt Caswell <matt at openssl.org>
Date:   Tue Oct 25 17:10:44 2016 +0100

    Document the HMAC_size() function
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit be2ef0e2e3842114054d26c3429016dc894a1359
Author: Matt Caswell <matt at openssl.org>
Date:   Tue Oct 25 15:29:35 2016 +0100

    Test the size_t constant time functions
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 2b7363ecf168f94e5d982cd49182aa923b92d3e4
Author: Matt Caswell <matt at openssl.org>
Date:   Tue Oct 25 15:29:17 2016 +0100

    Ensure SSL_DEBUG works following size_t changes
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 3cdc2f8fb528a4d47436dd863f6b8d5c30619847
Author: Matt Caswell <matt at openssl.org>
Date:   Tue Oct 25 15:27:55 2016 +0100

    Clarify the return values for the peek functions
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 6782e5fdd885cbd09ecbc063f3c1116c2962ecae
Author: Matt Caswell <matt at openssl.org>
Date:   Fri Oct 21 16:16:20 2016 +0100

    Updates various man pages based on review feedback received.
    
    Improvements to style, grammar etc.
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit d0ee717c938cda00bcb13cac2f7e2b162616254b
Author: Matt Caswell <matt at openssl.org>
Date:   Fri Oct 21 15:41:04 2016 +0100

    Fix style issues in HMAC_size()
    
    Based on review feedback.
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit f0ca8f89f866fd2214241758b8485a462d3f6f01
Author: Matt Caswell <matt at openssl.org>
Date:   Thu Oct 20 23:49:41 2016 +0100

    Fix some bogus warnings about uninitialised variables
    
    Travis was failing in some builds due to a bogus complaint
    about uninit variables.
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit d02ef3d0be3b2cb1e6b3905ad26fc03ec261b317
Author: Matt Caswell <matt at openssl.org>
Date:   Thu Oct 20 17:27:59 2016 +0100

    Fix some clashing symbol numbers due to merge conflict
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 7714dc5ea1174ca50cd12e5013683284f66c2dd3
Author: Matt Caswell <matt at openssl.org>
Date:   Thu Oct 20 15:04:21 2016 +0100

    Document the newly added SSL functions
    
    Also document SSL_peek() which was missing from the docs.
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 699ae85915f83f91bf5d5af45dd4888217005461
Author: Matt Caswell <matt at openssl.org>
Date:   Wed Oct 19 17:37:22 2016 +0100

    Remove a stray TODO that has already been fixed
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 2688e7a0beb0f5e76a98749f25b978ddfb40ac7f
Author: Matt Caswell <matt at openssl.org>
Date:   Wed Oct 19 17:13:13 2016 +0100

    Provide some constant time functions for dealing with size_t values
    
    Also implement the using of them
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 708e06c55d9fee5d59e4a4f409d115423ea1fa56
Author: Matt Caswell <matt at openssl.org>
Date:   Wed Oct 19 16:29:01 2016 +0100

    Ensure HMAC_size() handles errors correctly
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 56a26ce3600cc9f96da0e64b345a25276d9abfc0
Author: Matt Caswell <matt at openssl.org>
Date:   Wed Oct 19 16:28:12 2016 +0100

    Now that we can use size_t in PACKET lets use it
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 348240c676a1b2beaebb865e8be0b62f88c10b7d
Author: Matt Caswell <matt at openssl.org>
Date:   Wed Oct 19 15:11:24 2016 +0100

    Fix misc size_t issues causing Windows warnings in 64 bit
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit a14aa99be8fe169bba7afc6355b6b6d750b2ba1d
Author: Matt Caswell <matt at openssl.org>
Date:   Wed Oct 19 14:44:28 2016 +0100

    Convert the mac functions to just return 1 for success and 0 for failure
    
    Previously they return -1 for failure or the size of the mac. But the size
    was never used anywhere.
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit c08d12ca40e031e652e84cd235e8394cf883fd1f
Author: Matt Caswell <matt at openssl.org>
Date:   Wed Oct 19 14:39:55 2016 +0100

    Fix some ssl3_record code witch converstion to/from size_t
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 153703dfde6bf3f1cf72576a19d0f2fabe61a826
Author: Matt Caswell <matt at openssl.org>
Date:   Wed Oct 19 14:39:39 2016 +0100

    Add some PACKET functions for size_t
    
    And use them in the DTLS code
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 8051ab2b6f8e1fb9e957771afcc3555560f9694f
Author: Matt Caswell <matt at openssl.org>
Date:   Wed Oct 19 14:09:02 2016 +0100

    Convert SSL BIO to use SSL_write_ex().
    
    We also modify the SSL_get_error() function to handle the fact that with
    SSL_write_ex() the error return is 0 not -1, and fix some bugs in the
    SSL BIO reading.
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 8b0e934afbdf8ca61866263c507d4b653135952d
Author: Matt Caswell <matt at openssl.org>
Date:   Thu Oct 6 19:17:54 2016 +0100

    Fix some missed size_t updates
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit e3c9727fece7bd73469e14796f579c4dc5209cdb
Author: Matt Caswell <matt at openssl.org>
Date:   Tue Oct 4 21:42:28 2016 +0100

    Resolve some outstanding size_t related TODOs
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit d736bc1a7d45744300b2c81f7296b0d1e550ae0d
Author: Matt Caswell <matt at openssl.org>
Date:   Tue Oct 4 21:22:19 2016 +0100

    Update misc function params in libssl for size_t
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 6db6bc5a8f0663e679a99ea91a6f490db0f183ba
Author: Matt Caswell <matt at openssl.org>
Date:   Tue Oct 4 21:14:24 2016 +0100

    Convert some libssl local functions to size_t
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit cb150cbcaca651a5b32fc1f1fc94ca61285c3515
Author: Matt Caswell <matt at openssl.org>
Date:   Tue Oct 4 21:04:03 2016 +0100

    Update cookie_len for size_t
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 12472b456180cbc582d6152e174135524081c3ba
Author: Matt Caswell <matt at openssl.org>
Date:   Tue Oct 4 20:56:11 2016 +0100

    Update numerous misc libssl fields to be size_t
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit ec60ccc1c1b9562359753e8fcbeeab0a6b4b669c
Author: Matt Caswell <matt at openssl.org>
Date:   Tue Oct 4 20:31:19 2016 +0100

    Convert session_id_length and sid_ctx_len to size_t
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 8c1a534305054c58d783fdfe7adbed24f5893a2e
Author: Matt Caswell <matt at openssl.org>
Date:   Mon Oct 3 23:22:07 2016 +0100

    Convert master_secret_size code to size_t
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit b43d1cbb9abb331bbaa29658b4af434c7b870c56
Author: Matt Caswell <matt at openssl.org>
Date:   Mon Oct 3 22:34:07 2016 +0100

    Convert various mac_secret_size usage to size_t
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit d0e7c31db04349882855add5a5a21977b4467e3d
Author: Matt Caswell <matt at openssl.org>
Date:   Mon Oct 3 22:26:59 2016 +0100

    Convert ssl3_cbc_digest_record for size_t
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 72716e79bf1207625d58f4fe3874303ac47d0f98
Author: Matt Caswell <matt at openssl.org>
Date:   Mon Oct 3 22:15:10 2016 +0100

    Convert some misc record layer functions for size_t
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 5607b2759a3148be6f38a9205d225bc8c802eaf1
Author: Matt Caswell <matt at openssl.org>
Date:   Mon Oct 3 21:12:23 2016 +0100

    Convert SSL3_RECORD_clear() and SSL3_RECORD_release() to size_t
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 7ee8627f6eb7cf63b34d2701d76bb66f6db811e5
Author: Matt Caswell <matt at openssl.org>
Date:   Wed Sep 7 11:34:39 2016 +0100

    Convert libssl writing for size_t
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit eda757514ea3018c8510b4738b5e37479aeadc5e
Author: Matt Caswell <matt at openssl.org>
Date:   Tue Sep 6 12:05:25 2016 +0100

    Further libssl size_t-ify of reading
    
    Writing still to be done
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

commit 8e6d03cac4c34dc089751f36120b69c512f77756
Author: Matt Caswell <matt at openssl.org>
Date:   Tue Sep 6 09:24:19 2016 +0100

    Convert record layer to use size_t
    
    Reviewed-by: Rich Salz <rsalz at openssl.org>

-----------------------------------------------------------------------

Summary of changes:
 crypto/hmac/hmac.c                           |   4 +-
 doc/man3/HMAC.pod                            |  10 +-
 doc/man3/SSL_CTX_set_mode.pod                |  26 ++-
 doc/man3/SSL_CTX_set_split_send_fragment.pod |  10 +-
 doc/man3/SSL_get_error.pod                   |  15 +-
 doc/man3/SSL_pending.pod                     |  17 +-
 doc/man3/SSL_read.pod                        | 110 +++++----
 doc/man3/SSL_set_connect_state.pod           |   8 +-
 doc/man3/SSL_write.pod                       |  82 ++++---
 doc/man7/ssl.pod                             |   6 +-
 include/internal/constant_time_locl.h        |  49 ++++
 include/openssl/ssl.h                        |   6 +
 ssl/bio_ssl.c                                |  25 +--
 ssl/d1_lib.c                                 |  56 +++--
 ssl/d1_msg.c                                 |  11 +-
 ssl/d1_srtp.c                                |   5 +-
 ssl/packet_locl.h                            |  48 ++++
 ssl/pqueue.c                                 |   4 +-
 ssl/record/rec_layer_d1.c                    | 120 +++++-----
 ssl/record/rec_layer_s3.c                    | 247 ++++++++++----------
 ssl/record/record.h                          |  71 +++---
 ssl/record/record_locl.h                     |  19 +-
 ssl/record/ssl3_buffer.c                     |   8 +-
 ssl/record/ssl3_record.c                     | 267 ++++++++++++----------
 ssl/s3_cbc.c                                 |  24 +-
 ssl/s3_enc.c                                 |  40 ++--
 ssl/s3_lib.c                                 |  67 +++---
 ssl/s3_msg.c                                 |  20 +-
 ssl/ssl_asn1.c                               |  10 +-
 ssl/ssl_ciph.c                               |  11 +-
 ssl/ssl_err.c                                |   3 +
 ssl/ssl_lib.c                                | 322 +++++++++++++++++----------
 ssl/ssl_locl.h                               | 151 ++++++-------
 ssl/ssl_mcnf.c                               |   4 +-
 ssl/ssl_sess.c                               |  10 +-
 ssl/ssl_txt.c                                |  11 +-
 ssl/statem/statem.c                          |   4 +-
 ssl/statem/statem_clnt.c                     |  80 ++++---
 ssl/statem/statem_dtls.c                     | 198 ++++++++--------
 ssl/statem/statem_lib.c                      | 103 +++++----
 ssl/statem/statem_locl.h                     |   8 +-
 ssl/statem/statem_srvr.c                     |  61 ++---
 ssl/t1_enc.c                                 |  79 +++----
 ssl/t1_lib.c                                 |  65 +++---
 ssl/t1_reneg.c                               |   6 +-
 test/constant_time_test.c                    | 115 +++++++++-
 util/libssl.num                              |   3 +
 47 files changed, 1537 insertions(+), 1082 deletions(-)

diff --git a/crypto/hmac/hmac.c b/crypto/hmac/hmac.c
index 3374105..ffca891 100644
--- a/crypto/hmac/hmac.c
+++ b/crypto/hmac/hmac.c
@@ -118,7 +118,9 @@ int HMAC_Final(HMAC_CTX *ctx, unsigned char *md, unsigned int *len)
 
 size_t HMAC_size(const HMAC_CTX *ctx)
 {
-    return EVP_MD_size((ctx)->md);
+    int size = EVP_MD_size((ctx)->md);
+
+    return (size < 0) ? 0 : size;
 }
 
 HMAC_CTX *HMAC_CTX_new(void)
diff --git a/doc/man3/HMAC.pod b/doc/man3/HMAC.pod
index 87f7e33..595d67d 100644
--- a/doc/man3/HMAC.pod
+++ b/doc/man3/HMAC.pod
@@ -12,7 +12,8 @@ HMAC_Update,
 HMAC_Final,
 HMAC_CTX_copy,
 HMAC_CTX_set_flags,
-HMAC_CTX_get_md
+HMAC_CTX_get_md,
+HMAC_size
 - HMAC message authentication code
 
 =head1 SYNOPSIS
@@ -37,6 +38,8 @@ HMAC_CTX_get_md
  void HMAC_CTX_set_flags(HMAC_CTX *ctx, unsigned long flags);
  const EVP_MD *HMAC_CTX_get_md(const HMAC_CTX *ctx);
 
+ size_t HMAC_size(const HMAC_CTX *e);
+
 Deprecated:
 
  #if OPENSSL_API_COMPAT < 0x10100000L
@@ -105,6 +108,8 @@ These flags have the same meaning as for L<EVP_MD_CTX_set_flags(3)>.
 HMAC_CTX_get_md() returns the EVP_MD that has previously been set for the
 supplied HMAC_CTX.
 
+HMAC_size() returns the length in bytes of the underlying hash function output.
+
 =head1 RETURN VALUES
 
 HMAC() returns a pointer to the message authentication code or NULL if
@@ -119,6 +124,9 @@ HMAC_CTX_copy() return 1 for success or 0 if an error occurred.
 HMAC_CTX_get_md() return the EVP_MD previously set for the supplied HMAC_CTX or
 NULL if no EVP_MD has been set.
 
+HMAC_size() returns the length in bytes of the underlying hash function output
+or zero on error.
+
 =head1 CONFORMING TO
 
 RFC 2104
diff --git a/doc/man3/SSL_CTX_set_mode.pod b/doc/man3/SSL_CTX_set_mode.pod
index 1b3e783..6b8fad6 100644
--- a/doc/man3/SSL_CTX_set_mode.pod
+++ b/doc/man3/SSL_CTX_set_mode.pod
@@ -34,26 +34,27 @@ The following mode changes are available:
 
 =item SSL_MODE_ENABLE_PARTIAL_WRITE
 
-Allow SSL_write(..., n) to return r with 0 < r < n (i.e. report success
-when just a single record has been written). When not set (the default),
-SSL_write() will only report success once the complete chunk was written.
-Once SSL_write() returns with r, r bytes have been successfully written
-and the next call to SSL_write() must only send the n-r bytes left,
-imitating the behaviour of write().
+Allow SSL_write_ex(..., n, &r) to return with 0 < r < n (i.e. report success
+when just a single record has been written). This works in a similar way for
+SSL_write(). When not set (the default), SSL_write_ex() or SSL_write() will only
+report success once the complete chunk was written. Once SSL_write_ex() or
+SSL_write() returns successful, B<r> bytes have been written and the next call
+to SSL_write_ex() or SSL_write() must only send the n-r bytes left, imitating
+the behaviour of write().
 
 =item SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
 
-Make it possible to retry SSL_write() with changed buffer location
-(the buffer contents must stay the same). This is not the default to avoid
-the misconception that non-blocking SSL_write() behaves like
+Make it possible to retry SSL_write_ex() or SSL_write() with changed buffer
+location (the buffer contents must stay the same). This is not the default to
+avoid the misconception that non-blocking SSL_write() behaves like
 non-blocking write().
 
 =item SSL_MODE_AUTO_RETRY
 
 Never bother the application with retries if the transport is blocking.
 If a renegotiation take place during normal operation, a
-L<SSL_read(3)> or L<SSL_write(3)> would return
-with -1 and indicate the need to retry with SSL_ERROR_WANT_READ.
+L<SSL_read_ex(3)>, L<SSL_read(3)>, L<SSL_write_ex(3)> or L<SSL_write(3)> would
+return with a failure and indicate the need to retry with SSL_ERROR_WANT_READ.
 In a non-blocking environment applications must be prepared to handle
 incomplete read/write operations.
 In a blocking environment, applications are not always prepared to
@@ -96,7 +97,8 @@ SSL_CTX_get_mode() and SSL_get_mode() return the current bitmask.
 
 =head1 SEE ALSO
 
-L<ssl(3)>, L<SSL_read(3)>, L<SSL_write(3)>, L<SSL_get_error(3)>
+L<ssl(3)>, L<SSL_read_ex(3)>, L<SSL_read(3)>, L<SSL_write_ex(3)> or
+L<SSL_write(3)>, L<SSL_get_error(3)>
 
 =head1 HISTORY
 
diff --git a/doc/man3/SSL_CTX_set_split_send_fragment.pod b/doc/man3/SSL_CTX_set_split_send_fragment.pod
index accf5af..4c3e9e6 100644
--- a/doc/man3/SSL_CTX_set_split_send_fragment.pod
+++ b/doc/man3/SSL_CTX_set_split_send_fragment.pod
@@ -58,19 +58,19 @@ Pipelining operates slightly differently for reading encrypted data compared to
 writing encrypted data. SSL_CTX_set_split_send_fragment() and
 SSL_set_split_send_fragment() define how data is split up into pipelines when
 writing encrypted data. The number of pipelines used will be determined by the
-amount of data provided to the SSL_write() call divided by
+amount of data provided to the SSL_write_ex() or SSL_write() call divided by
 B<split_send_fragment>.
 
 For example if B<split_send_fragment> is set to 2000 and B<max_pipelines> is 4
 then:
 
-SSL_write called with 0-2000 bytes == 1 pipeline used
+SSL_write/SSL_write_ex called with 0-2000 bytes == 1 pipeline used
 
-SSL_write called with 2001-4000 bytes == 2 pipelines used
+SSL_write/SSL_write_ex called with 2001-4000 bytes == 2 pipelines used
 
-SSL_write called with 4001-6000 bytes == 3 pipelines used
+SSL_write/SSL_write_ex called with 4001-6000 bytes == 3 pipelines used
 
-SSL_write called with 6001+ bytes == 4 pipelines used
+SSL_write/SSL_write_ex called with 6001+ bytes == 4 pipelines used
 
 B<split_send_fragment> must always be less than or equal to
 B<max_send_fragment>. By default it is set to be equal to B<max_send_fragment>.
diff --git a/doc/man3/SSL_get_error.pod b/doc/man3/SSL_get_error.pod
index ddd72f7..424f6f0 100644
--- a/doc/man3/SSL_get_error.pod
+++ b/doc/man3/SSL_get_error.pod
@@ -14,9 +14,9 @@ SSL_get_error - obtain result code for TLS/SSL I/O operation
 
 SSL_get_error() returns a result code (suitable for the C "switch"
 statement) for a preceding call to SSL_connect(), SSL_accept(), SSL_do_handshake(),
-SSL_read(), SSL_peek(), or SSL_write() on B<ssl>.  The value returned by
-that TLS/SSL I/O function must be passed to SSL_get_error() in parameter
-B<ret>.
+SSL_read_ex(), SSL_read(), SSL_peek_ex(), SSL_peek(), SSL_write_ex() or
+SSL_write() on B<ssl>.  The value returned by that TLS/SSL I/O function must be
+passed to SSL_get_error() in parameter B<ret>.
 
 In addition to B<ssl> and B<ret>, SSL_get_error() inspects the
 current thread's OpenSSL error queue.  Thus, SSL_get_error() must be
@@ -64,10 +64,11 @@ TLS/SSL I/O function should be retried.
 
 Caveat: Any TLS/SSL I/O function can lead to either of
 B<SSL_ERROR_WANT_READ> and B<SSL_ERROR_WANT_WRITE>.  In particular,
-SSL_read() or SSL_peek() may want to write data and SSL_write() may want
-to read data.  This is mainly because TLS/SSL handshakes may occur at any
-time during the protocol (initiated by either the client or the server);
-SSL_read(), SSL_peek(), and SSL_write() will handle any pending handshakes.
+SSL_read_ex(), SSL_read(), SSL_peek_ex(), or SSL_peek() may want to write data
+and SSL_write() or SSL_write_ex() may want to read data.  This is mainly because
+TLS/SSL handshakes may occur at any time during the protocol (initiated by
+either the client or the server); SSL_read_ex(), SSL_read(), SSL_peek_ex(),
+SSL_peek(), SSL_write_ex(), and SSL_write() will handle any pending handshakes.
 
 =item SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT
 
diff --git a/doc/man3/SSL_pending.pod b/doc/man3/SSL_pending.pod
index f6ed565..642cd4b 100644
--- a/doc/man3/SSL_pending.pod
+++ b/doc/man3/SSL_pending.pod
@@ -16,7 +16,7 @@ SSL object
 
 Data is received in whole blocks known as records from the peer. A whole record
 is processed (e.g. decrypted) in one go and is buffered by OpenSSL until it is
-read by the application via a call to L<SSL_read(3)>.
+read by the application via a call to L<SSL_read_ex(3)> or L<SSL_read(3)>.
 
 SSL_pending() returns the number of bytes which have been processed, buffered
 and are available inside B<ssl> for immediate read.
@@ -34,12 +34,13 @@ the data is in unprocessed buffered records).
 
 SSL_has_pending() returns 1 if B<s> has buffered data (whether processed or
 unprocessed) and 0 otherwise. Note that it is possible for SSL_has_pending() to
-return 1, and then a subsequent call to SSL_read() to return no data because the
-unprocessed buffered data when processed yielded no application data (for
-example this can happen during renegotiation). It is also possible in this
-scenario for SSL_has_pending() to continue to return 1 even after an SSL_read()
-call because the buffered and unprocessed data is not yet processable (e.g.
-because OpenSSL has only received a partial record so far).
+return 1, and then a subsequent call to SSL_read_ex() or SSL_read() to return no
+data because the unprocessed buffered data when processed yielded no application
+data (for example this can happen during renegotiation). It is also possible in
+this scenario for SSL_has_pending() to continue to return 1 even after an
+SSL_read_ex() or SSL_read() call because the buffered and unprocessed data is
+not yet processable (e.g. because OpenSSL has only received a partial record so
+far).
 
 =head1 RETURN VALUES
 
@@ -49,7 +50,7 @@ returns 1 if there is buffered record data in the SSL object and 0 otherwise.
 
 =head1 SEE ALSO
 
-L<SSL_read(3)>, L<SSL_CTX_set_read_ahead(3)>,
+L<SSL_read_ex(3)>, L<SSL_read(3)>, L<SSL_CTX_set_read_ahead(3)>,
 L<SSL_CTX_set_split_send_fragment(3)>, L<ssl(3)>
 
 =head1 HISTORY
diff --git a/doc/man3/SSL_read.pod b/doc/man3/SSL_read.pod
index 8dff244..7c175bf 100644
--- a/doc/man3/SSL_read.pod
+++ b/doc/man3/SSL_read.pod
@@ -2,82 +2,100 @@
 
 =head1 NAME
 
-SSL_read - read bytes from a TLS/SSL connection
+SSL_read_ex, SSL_read - read bytes from a TLS/SSL connection
 
 =head1 SYNOPSIS
 
  #include <openssl/ssl.h>
 
+ int SSL_read_ex(SSL *ssl, void *buf, size_t num, size_t *read);
  int SSL_read(SSL *ssl, void *buf, int num);
 
+ int SSL_peek_ex(SSL *ssl, void *buf, size_t num, size_t *read);
+ int SSL_peek(SSL *ssl, void *buf, int num);
+
 =head1 DESCRIPTION
 
-SSL_read() tries to read B<num> bytes from the specified B<ssl> into the
-buffer B<buf>.
+SSL_read_ex() and SSL_read() try to read B<num> bytes from the specified B<ssl>
+into the buffer B<buf>. On success SSL_read_ex() will store the number of bytes
+actually read in B<*read>.
+
+SSL_peek_ex() and SSL_peek() are identical to SSL_read_ex() and SSL_read()
+respectively except no bytes are actually removed from the underlying BIO during
+the read, so that a subsequent call to SSL_read_ex() or SSL_read() will yield
+at least the same bytes.
 
 =head1 NOTES
 
-If necessary, SSL_read() will negotiate a TLS/SSL session, if
-not already explicitly performed by L<SSL_connect(3)> or
-L<SSL_accept(3)>. If the
+In the paragraphs below a "read function" is defined as one of SSL_read_ex(),
+SSL_read(), SSL_peek_ex() or SSL_peek().
+
+If necessary, a read function will negotiate a TLS/SSL session, if not already
+explicitly performed by L<SSL_connect(3)> or L<SSL_accept(3)>. If the
 peer requests a re-negotiation, it will be performed transparently during
-the SSL_read() operation. The behaviour of SSL_read() depends on the
+the read function operation. The behaviour of the read functions depends on the
 underlying BIO.
 
 For the transparent negotiation to succeed, the B<ssl> must have been
 initialized to client or server mode. This is being done by calling
-L<SSL_set_connect_state(3)> or SSL_set_accept_state()
-before the first call to an SSL_read() or L<SSL_write(3)>
-function.
-
-SSL_read() works based on the SSL/TLS records. The data are received in
-records (with a maximum record size of 16kB for SSLv3/TLSv1). Only when a
-record has been completely received, it can be processed (decryption and
-check of integrity). Therefore data that was not retrieved at the last
-call of SSL_read() can still be buffered inside the SSL layer and will be
-retrieved on the next call to SSL_read(). If B<num> is higher than the
-number of bytes buffered, SSL_read() will return with the bytes buffered.
-If no more bytes are in the buffer, SSL_read() will trigger the processing
-of the next record. Only when the record has been received and processed
-completely, SSL_read() will return reporting success. At most the contents
-of the record will be returned. As the size of an SSL/TLS record may exceed
-the maximum packet size of the underlying transport (e.g. TCP), it may
-be necessary to read several packets from the transport layer before the
-record is complete and SSL_read() can succeed.
-
-If the underlying BIO is B<blocking>, SSL_read() will only return, once the
+L<SSL_set_connect_state(3)> or SSL_set_accept_state() before the first
+invocation of a read function.
+
+The read functions work based on the SSL/TLS records. The data are received in
+records (with a maximum record size of 16kB). Only when a record has been
+completely received, can it be processed (decryption and check of integrity).
+Therefore data that was not retrieved at the last read call can still be
+buffered inside the SSL layer and will be retrieved on the next read
+call. If B<num> is higher than the number of bytes buffered then the read
+functions will return with the bytes buffered. If no more bytes are in the
+buffer, the read functions will trigger the processing of the next record.
+Only when the record has been received and processed completely will the read
+functions return reporting success. At most the contents of the record will
+be returned. As the size of an SSL/TLS record may exceed the maximum packet size
+of the underlying transport (e.g. TCP), it may be necessary to read several
+packets from the transport layer before the record is complete and the read call
+can succeed.
+
+If the underlying BIO is B<blocking>, a read function will only return once the
 read operation has been finished or an error occurred, except when a
-renegotiation take place, in which case a SSL_ERROR_WANT_READ may occur.
-This behaviour can be controlled with the SSL_MODE_AUTO_RETRY flag of the
+renegotiation takes place, in which case a SSL_ERROR_WANT_READ may occur. This
+behaviour can be controlled with the SSL_MODE_AUTO_RETRY flag of the
 L<SSL_CTX_set_mode(3)> call.
 
-If the underlying BIO is B<non-blocking>, SSL_read() will also return
-when the underlying BIO could not satisfy the needs of SSL_read()
-to continue the operation. In this case a call to
-L<SSL_get_error(3)> with the
-return value of SSL_read() will yield B<SSL_ERROR_WANT_READ> or
+If the underlying BIO is B<non-blocking>, a read function will also return when
+the underlying BIO could not satisfy the needs of the function to continue the
+operation. In this case a call to L<SSL_get_error(3)> with the
+return value of the read function will yield B<SSL_ERROR_WANT_READ> or
 B<SSL_ERROR_WANT_WRITE>. As at any time a re-negotiation is possible, a
-call to SSL_read() can also cause write operations! The calling process
-then must repeat the call after taking appropriate action to satisfy the
-needs of SSL_read(). The action depends on the underlying BIO. When using a
-non-blocking socket, nothing is to be done, but select() can be used to check
-for the required condition. When using a buffering BIO, like a BIO pair, data
-must be written into or retrieved out of the BIO before being able to continue.
+a read function can also cause write operations! The calling process then must
+repeat the call after taking appropriate action to satisfy the needs of the read
+function. The action depends on the underlying BIO. When using a non-blocking
+socket, nothing is to be done, but select() can be used to check for the
+required condition. When using a buffering BIO, like a BIO pair, data must be
+written into or retrieved out of the BIO before being able to continue.
 
 L<SSL_pending(3)> can be used to find out whether there
 are buffered bytes available for immediate retrieval. In this case
-SSL_read() can be called without blocking or actually receiving new
-data from the underlying socket.
+the read function can be called without blocking or actually receiving
+new data from the underlying socket.
 
 =head1 WARNING
 
-When an SSL_read() operation has to be repeated because of
-B<SSL_ERROR_WANT_READ> or B<SSL_ERROR_WANT_WRITE>, it must be repeated
+When a read function operation has to be repeated because L<SSL_get_error(3)>
+returned B<SSL_ERROR_WANT_READ> or B<SSL_ERROR_WANT_WRITE>, it must be repeated
 with the same arguments.
 
 =head1 RETURN VALUES
 
-The following return values can occur:
+SSL_read_ex() and SSL_peek_ex() will return 1 for success or 0 for failure.
+Success means that 1 or more application data bytes have been read from the SSL
+connection. Failure means that no bytes could be read from the SSL connection.
+Failures can be retryable (e.g. we are waiting for more bytes to
+be delivered by the network) or non-retryable (e.g. a fatal network error). In
+the event of a failure call L<SSL_get_error(3)> to find out the reason which
+indicates whether the call is retryable or not.
+
+For SSL_read() and SSL_peek() the following return values can occur:
 
 =over 4
 
@@ -108,7 +126,7 @@ return value B<ret> to find out the reason.
 
 =head1 SEE ALSO
 
-L<SSL_get_error(3)>, L<SSL_write(3)>,
+L<SSL_get_error(3)>, L<SSL_write_ex(3)>,
 L<SSL_CTX_set_mode(3)>, L<SSL_CTX_new(3)>,
 L<SSL_connect(3)>, L<SSL_accept(3)>
 L<SSL_set_connect_state(3)>,
diff --git a/doc/man3/SSL_set_connect_state.pod b/doc/man3/SSL_set_connect_state.pod
index 60c18a4..1f44f59 100644
--- a/doc/man3/SSL_set_connect_state.pod
+++ b/doc/man3/SSL_set_connect_state.pod
@@ -35,8 +35,8 @@ requested, the handshake routines must be explicitly set.
 When using the L<SSL_connect(3)> or
 L<SSL_accept(3)> routines, the correct handshake
 routines are automatically set. When performing a transparent negotiation
-using L<SSL_write(3)> or L<SSL_read(3)>, the
-handshake routines must be explicitly set in advance using either
+using L<SSL_write_ex(3)>, L<SSL_write(3)>, L<SSL_read_ex(3)>, or L<SSL_read(3)>,
+the handshake routines must be explicitly set in advance using either
 SSL_set_connect_state() or SSL_set_accept_state().
 
 =head1 RETURN VALUES
@@ -47,8 +47,8 @@ information.
 =head1 SEE ALSO
 
 L<ssl(3)>, L<SSL_new(3)>, L<SSL_CTX_new(3)>,
-LL<SSL_connect(3)>, L<SSL_accept(3)>,
-L<SSL_write(3)>, L<SSL_read(3)>,
+L<SSL_connect(3)>, L<SSL_accept(3)>,
+L<SSL_write_ex(3)>, L<SSL_write(3)>, L<SSL_read_ex(3)>, L<SSL_read(3)>,
 L<SSL_do_handshake(3)>,
 L<SSL_CTX_set_ssl_version(3)>
 
diff --git a/doc/man3/SSL_write.pod b/doc/man3/SSL_write.pod
index 5ab0790..c860ed7 100644
--- a/doc/man3/SSL_write.pod
+++ b/doc/man3/SSL_write.pod
@@ -2,75 +2,87 @@
 
 =head1 NAME
 
-SSL_write - write bytes to a TLS/SSL connection
+SSL_write_ex, SSL_write - write bytes to a TLS/SSL connection
 
 =head1 SYNOPSIS
 
  #include <openssl/ssl.h>
 
+ int SSL_write_ex(SSL *s, const void *buf, size_t num, size_t *written);
  int SSL_write(SSL *ssl, const void *buf, int num);
 
 =head1 DESCRIPTION
 
-SSL_write() writes B<num> bytes from the buffer B<buf> into the specified
-B<ssl> connection.
+SSL_write_ex() and SSL_write() write B<num> bytes from the buffer B<buf> into
+the specified B<ssl> connection. On success SSL_write_ex() will store the number
+of bytes written in B<*written>.
 
 =head1 NOTES
 
-If necessary, SSL_write() will negotiate a TLS/SSL session, if
-not already explicitly performed by L<SSL_connect(3)> or
-L<SSL_accept(3)>. If the
-peer requests a re-negotiation, it will be performed transparently during
-the SSL_write() operation. The behaviour of SSL_write() depends on the
+In the paragraphs below a "write function" is defined as one of either
+SSL_write_ex(), or SSL_write().
+
+If necessary, a write function will negotiate a TLS/SSL session, if not already
+explicitly performed by L<SSL_connect(3)> or L<SSL_accept(3)>. If the peer
+requests a re-negotiation, it will be performed transparently during
+the write functio operation. The behaviour of the write functions depends on the
 underlying BIO.
 
 For the transparent negotiation to succeed, the B<ssl> must have been
 initialized to client or server mode. This is being done by calling
 L<SSL_set_connect_state(3)> or SSL_set_accept_state()
-before the first call to an L<SSL_read(3)> or SSL_write() function.
+before the first call to a write function.
 
-If the underlying BIO is B<blocking>, SSL_write() will only return, once the
-write operation has been finished or an error occurred, except when a
+If the underlying BIO is B<blocking>, the write functions will only return, once
+the write operation has been finished or an error occurred, except when a
 renegotiation take place, in which case a SSL_ERROR_WANT_READ may occur.
 This behaviour can be controlled with the SSL_MODE_AUTO_RETRY flag of the
 L<SSL_CTX_set_mode(3)> call.
 
-If the underlying BIO is B<non-blocking>, SSL_write() will also return,
-when the underlying BIO could not satisfy the needs of SSL_write()
-to continue the operation. In this case a call to
-L<SSL_get_error(3)> with the
-return value of SSL_write() will yield B<SSL_ERROR_WANT_READ> or
-B<SSL_ERROR_WANT_WRITE>. As at any time a re-negotiation is possible, a
-call to SSL_write() can also cause read operations! The calling process
-then must repeat the call after taking appropriate action to satisfy the
-needs of SSL_write(). The action depends on the underlying BIO. When using a
+If the underlying BIO is B<non-blocking> the write functions will also return
+when the underlying BIO could not satisfy the needs of the function to continue
+the operation. In this case a call to L<SSL_get_error(3)> with the
+return value of the write function will yield B<SSL_ERROR_WANT_READ>
+or B<SSL_ERROR_WANT_WRITE>. As at any time a re-negotiation is possible, a
+call to a write function can also cause read operations! The calling process
+then must repeat the call after taking appropriate action to satisfy the needs
+of the write function. The action depends on the underlying BIO. When using a
 non-blocking socket, nothing is to be done, but select() can be used to check
 for the required condition. When using a buffering BIO, like a BIO pair, data
 must be written into or retrieved out of the BIO before being able to continue.
 
-SSL_write() will only return with success, when the complete contents
-of B<buf> of length B<num> has been written. This default behaviour
-can be changed with the SSL_MODE_ENABLE_PARTIAL_WRITE option of
-L<SSL_CTX_set_mode(3)>. When this flag is set,
-SSL_write() will also return with success, when a partial write has been
-successfully completed. In this case the SSL_write() operation is considered
-completed. The bytes are sent and a new SSL_write() operation with a new
-buffer (with the already sent bytes removed) must be started.
-A partial write is performed with the size of a message block, which is
-16kB for SSLv3/TLSv1.
+The write functions will only return with success when the complete contents of
+B<buf> of length B<num> has been written. This default behaviour can be changed
+with the SSL_MODE_ENABLE_PARTIAL_WRITE option of L<SSL_CTX_set_mode(3)>. When
+this flag is set the write functions will also return with success when a
+partial write has been successfully completed. In this case the write function
+operation is considered completed. The bytes are sent and a new write call with
+a new buffer (with the already sent bytes removed) must be started. A partial
+write is performed with the size of a message block, which is 16kB.
 
 =head1 WARNING
 
-When an SSL_write() operation has to be repeated because of
-B<SSL_ERROR_WANT_READ> or B<SSL_ERROR_WANT_WRITE>, it must be repeated
+When a write function call has to be repeated because L<SSL_get_error(3)>
+returned B<SSL_ERROR_WANT_READ> or B<SSL_ERROR_WANT_WRITE>, it must be repeated
 with the same arguments.
 
-When calling SSL_write() with num=0 bytes to be sent the behaviour is
+When calling the write functions with num=0 bytes to be sent the behaviour is
 undefined.
 
 =head1 RETURN VALUES
 
-The following return values can occur:
+SSL_write_ex() will return 1 for success or 0 for failure. Success means that
+all requested application data bytes have been written to the SSL connection or,
+if SSL_MODE_ENABLE_PARTIAL_WRITE is in use, at least 1 application data byte has
+been written to the SSL connection. Failure means that not all the requested
+bytes have been written yet (if SSL_MODE_ENABLE_PARTIAL_WRITE is not in use) or
+no bytes could be written to the SSL connection (if
+SSL_MODE_ENABLE_PARTIAL_WRITE is in use). Failures can be retryable (e.g. the
+network write buffer has temporarily filled up) or non-retryable (e.g. a fatal
+network error). In the event of a failure call L<SSL_get_error(3)> to find out
+the reason which indicates whether the call is retryable or not.
+
+For SSL_write() the following return values can occur:
 
 =over 4
 
@@ -96,7 +108,7 @@ return value B<ret> to find out the reason.
 
 =head1 SEE ALSO
 
-L<SSL_get_error(3)>, L<SSL_read(3)>,
+L<SSL_get_error(3)>, L<SSL_read_ex(3)>, L<SSL_read(3)>
 L<SSL_CTX_set_mode(3)>, L<SSL_CTX_new(3)>,
 L<SSL_connect(3)>, L<SSL_accept(3)>
 L<SSL_set_connect_state(3)>,
diff --git a/doc/man7/ssl.pod b/doc/man7/ssl.pod
index ce163f4..7b5b39e 100644
--- a/doc/man7/ssl.pod
+++ b/doc/man7/ssl.pod
@@ -28,8 +28,8 @@ connection with the object.
 Then the TLS/SSL handshake is performed using
 L<SSL_accept(3)> or L<SSL_connect(3)>
 respectively.
-L<SSL_read(3)> and L<SSL_write(3)> are used
-to read and write data on the TLS/SSL connection.
+L<SSL_read_ex(3)>, L<SSL_read(3)>, L<SSL_write_ex(3)> and L<SSL_write(3)> are
+used to read and write data on the TLS/SSL connection.
 L<SSL_shutdown(3)> can be used to shut down the
 TLS/SSL connection.
 
@@ -792,6 +792,7 @@ L<SSL_get_version(3)>,
 L<SSL_load_client_CA_file(3)>,
 L<SSL_new(3)>,
 L<SSL_pending(3)>,
+L<SSL_read_ex(3)>,
 L<SSL_read(3)>,
 L<SSL_rstate_string(3)>,
 L<SSL_session_reused(3)>,
@@ -803,6 +804,7 @@ L<SSL_set_shutdown(3)>,
 L<SSL_shutdown(3)>,
 L<SSL_state_string(3)>,
 L<SSL_want(3)>,
+L<SSL_write_ex(3)>,
 L<SSL_write(3)>,
 L<SSL_SESSION_free(3)>,
 L<SSL_SESSION_get_time(3)>,
diff --git a/include/internal/constant_time_locl.h b/include/internal/constant_time_locl.h
index d27fb14..be2730e 100644
--- a/include/internal/constant_time_locl.h
+++ b/include/internal/constant_time_locl.h
@@ -10,6 +10,7 @@
 #ifndef HEADER_CONSTANT_TIME_LOCL_H
 # define HEADER_CONSTANT_TIME_LOCL_H
 
+# include <stdlib.h>
 # include <openssl/e_os2.h>              /* For 'ossl_inline' */
 
 #ifdef __cplusplus
@@ -102,12 +103,22 @@ static ossl_inline unsigned int constant_time_msb(unsigned int a)
     return 0 - (a >> (sizeof(a) * 8 - 1));
 }
 
+static ossl_inline size_t constant_time_msb_s(size_t a)
+{
+    return 0 - (a >> (sizeof(a) * 8 - 1));
+}
+
 static ossl_inline unsigned int constant_time_lt(unsigned int a,
                                                  unsigned int b)
 {
     return constant_time_msb(a ^ ((a ^ b) | ((a - b) ^ b)));
 }
 
+static ossl_inline size_t constant_time_lt_s(size_t a, size_t b)
+{
+    return constant_time_msb_s(a ^ ((a ^ b) | ((a - b) ^ b)));
+}
+
 static ossl_inline unsigned char constant_time_lt_8(unsigned int a,
                                                     unsigned int b)
 {
@@ -120,17 +131,32 @@ static ossl_inline unsigned int constant_time_ge(unsigned int a,
     return ~constant_time_lt(a, b);
 }
 
+static ossl_inline size_t constant_time_ge_s(size_t a, size_t b)
+{
+    return ~constant_time_lt_s(a, b);
+}
+
 static ossl_inline unsigned char constant_time_ge_8(unsigned int a,
                                                     unsigned int b)
 {
     return (unsigned char)(constant_time_ge(a, b));
 }
 
+static ossl_inline unsigned char constant_time_ge_8_s(size_t a, size_t b)
+{
+    return (unsigned char)(constant_time_ge_s(a, b));
+}
+
 static ossl_inline unsigned int constant_time_is_zero(unsigned int a)
 {
     return constant_time_msb(~a & (a - 1));
 }
 
+static ossl_inline size_t constant_time_is_zero_s(size_t a)
+{
+    return constant_time_msb_s(~a & (a - 1));
+}
+
 static ossl_inline unsigned char constant_time_is_zero_8(unsigned int a)
 {
     return (unsigned char)(constant_time_is_zero(a));
@@ -142,12 +168,22 @@ static ossl_inline unsigned int constant_time_eq(unsigned int a,
     return constant_time_is_zero(a ^ b);
 }
 
+static ossl_inline size_t constant_time_eq_s(size_t a, size_t b)
+{
+    return constant_time_is_zero_s(a ^ b);
+}
+
 static ossl_inline unsigned char constant_time_eq_8(unsigned int a,
                                                     unsigned int b)
 {
     return (unsigned char)(constant_time_eq(a, b));
 }
 
+static ossl_inline unsigned char constant_time_eq_8_s(size_t a, size_t b)
+{
+    return (unsigned char)(constant_time_eq_s(a, b));
+}
+
 static ossl_inline unsigned int constant_time_eq_int(int a, int b)
 {
     return constant_time_eq((unsigned)(a), (unsigned)(b));
@@ -165,6 +201,13 @@ static ossl_inline unsigned int constant_time_select(unsigned int mask,
     return (mask & a) | (~mask & b);
 }
 
+static ossl_inline size_t constant_time_select_s(size_t mask,
+                                                 size_t a,
+                                                 size_t b)
+{
+    return (mask & a) | (~mask & b);
+}
+
 static ossl_inline unsigned char constant_time_select_8(unsigned char mask,
                                                         unsigned char a,
                                                         unsigned char b)
@@ -178,6 +221,12 @@ static ossl_inline int constant_time_select_int(unsigned int mask, int a,
     return (int)(constant_time_select(mask, (unsigned)(a), (unsigned)(b)));
 }
 
+static ossl_inline int constant_time_select_int_s(size_t mask, int a, int b)
+{
+    return (int)(constant_time_select((unsigned)mask, (unsigned)(a),
+                                      (unsigned)(b)));
+}
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/include/openssl/ssl.h b/include/openssl/ssl.h
index 7b40b37..c781323 100644
--- a/include/openssl/ssl.h
+++ b/include/openssl/ssl.h
@@ -1568,8 +1568,11 @@ __owur int SSL_get_changed_async_fds(SSL *s, OSSL_ASYNC_FD *addfd,
 __owur int SSL_accept(SSL *ssl);
 __owur int SSL_connect(SSL *ssl);
 __owur int SSL_read(SSL *ssl, void *buf, int num);
+__owur int SSL_read_ex(SSL *ssl, void *buf, size_t num, size_t *read);
 __owur int SSL_peek(SSL *ssl, void *buf, int num);
+__owur int SSL_peek_ex(SSL *ssl, void *buf, size_t num, size_t *read);
 __owur int SSL_write(SSL *ssl, const void *buf, int num);
+__owur int SSL_write_ex(SSL *s, const void *buf, size_t num, size_t *written);
 long SSL_ctrl(SSL *ssl, int cmd, long larg, void *parg);
 long SSL_callback_ctrl(SSL *, int, void (*)(void));
 long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg);
@@ -2179,7 +2182,9 @@ int ERR_load_SSL_strings(void);
 # define SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT               303
 # define SSL_F_SSL_PARSE_SERVERHELLO_USE_SRTP_EXT         311
 # define SSL_F_SSL_PEEK                                   270
+# define SSL_F_SSL_PEEK_EX                                432
 # define SSL_F_SSL_READ                                   223
+# define SSL_F_SSL_READ_EX                                434
 # define SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT                320
 # define SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT                321
 # define SSL_F_SSL_SESSION_DUP                            348
@@ -2216,6 +2221,7 @@ int ERR_load_SSL_strings(void);
 # define SSL_F_SSL_VALIDATE_CT                            400
 # define SSL_F_SSL_VERIFY_CERT_CHAIN                      207
 # define SSL_F_SSL_WRITE                                  208
+# define SSL_F_SSL_WRITE_EX                               433
 # define SSL_F_STATE_MACHINE                              353
 # define SSL_F_TLS12_CHECK_PEER_SIGALG                    333
 # define SSL_F_TLS1_CHANGE_CIPHER_STATE                   209
diff --git a/ssl/bio_ssl.c b/ssl/bio_ssl.c
index d64451c..e48b90f 100644
--- a/ssl/bio_ssl.c
+++ b/ssl/bio_ssl.c
@@ -28,7 +28,7 @@ typedef struct bio_ssl_st {
     /* re-negotiate every time the total number of bytes is this size */
     int num_renegotiates;
     unsigned long renegotiate_count;
-    unsigned long byte_count;
+    size_t byte_count;
     unsigned long renegotiate_timeout;
     unsigned long last_time;
 } BIO_SSL;
@@ -103,17 +103,10 @@ static int ssl_read(BIO *b, char *buf, size_t size, size_t *readbytes)
 
     BIO_clear_retry_flags(b);
 
-    if (size > INT_MAX)
-        size = INT_MAX;
-
-    ret = SSL_read(ssl, buf, size);
-    if (ret > 0)
-        *readbytes = ret;
+    ret = SSL_read_ex(ssl, buf, size, readbytes);
 
     switch (SSL_get_error(ssl, ret)) {
     case SSL_ERROR_NONE:
-        if (ret <= 0)
-            break;
         if (sb->renegotiate_count > 0) {
             sb->byte_count += *readbytes;
             if (sb->byte_count > sb->renegotiate_count) {
@@ -179,17 +172,12 @@ static int ssl_write(BIO *b, const char *buf, size_t size, size_t *written)
 
     BIO_clear_retry_flags(b);
 
-    if (size > INT_MAX)
-        size = INT_MAX;
-
-    ret = SSL_write(ssl, buf, size);
+    ret = SSL_write_ex(ssl, buf, size, written);
 
     switch (SSL_get_error(ssl, ret)) {
     case SSL_ERROR_NONE:
-        if (ret <= 0)
-            break;
         if (bs->renegotiate_count > 0) {
-            bs->byte_count += ret;
+            bs->byte_count += *written;
             if (bs->byte_count > bs->renegotiate_count) {
                 bs->byte_count = 0;
                 bs->num_renegotiates++;
@@ -229,11 +217,6 @@ static int ssl_write(BIO *b, const char *buf, size_t size, size_t *written)
 
     BIO_set_retry_reason(b, retry_reason);
 
-    if (ret > 0) {
-        *written = ret;
-        ret = 1;
-    }
-
     return ret;
 }
 
diff --git a/ssl/d1_lib.c b/ssl/d1_lib.c
index e7a6650..ffc6322 100644
--- a/ssl/d1_lib.c
+++ b/ssl/d1_lib.c
@@ -23,10 +23,10 @@
 
 static void get_current_time(struct timeval *t);
 static int dtls1_handshake_write(SSL *s);
-static unsigned int dtls1_link_min_mtu(void);
+static size_t dtls1_link_min_mtu(void);
 
 /* XDTLS:  figure out the right values */
-static const unsigned int g_probable_mtu[] = { 1500, 512, 256 };
+static const size_t g_probable_mtu[] = { 1500, 512, 256 };
 
 const SSL3_ENC_METHOD DTLSv1_enc_data = {
     tls1_enc,
@@ -35,13 +35,11 @@ const SSL3_ENC_METHOD DTLSv1_enc_data = {
     tls1_generate_master_secret,
     tls1_change_cipher_state,
     tls1_final_finish_mac,
-    TLS1_FINISH_MAC_LENGTH,
     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
     tls1_alert_code,
     tls1_export_keying_material,
     SSL_ENC_FLAG_DTLS | SSL_ENC_FLAG_EXPLICIT_IV,
-    DTLS1_HM_HEADER_LENGTH,
     dtls1_set_handshake_header,
     dtls1_close_construct_packet,
     dtls1_handshake_write
@@ -54,14 +52,12 @@ const SSL3_ENC_METHOD DTLSv1_2_enc_data = {
     tls1_generate_master_secret,
     tls1_change_cipher_state,
     tls1_final_finish_mac,
-    TLS1_FINISH_MAC_LENGTH,
     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
     tls1_alert_code,
     tls1_export_keying_material,
     SSL_ENC_FLAG_DTLS | SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS
         | SSL_ENC_FLAG_SHA256_PRF | SSL_ENC_FLAG_TLS1_2_CIPHERS,
-    DTLS1_HM_HEADER_LENGTH,
     dtls1_set_handshake_header,
     dtls1_close_construct_packet,
     dtls1_handshake_write
@@ -164,8 +160,8 @@ void dtls1_clear(SSL *s)
 {
     pqueue *buffered_messages;
     pqueue *sent_messages;
-    unsigned int mtu;
-    unsigned int link_mtu;
+    size_t mtu;
+    size_t link_mtu;
 
     DTLS_RECORD_LAYER_clear(&s->rlayer);
 
@@ -344,7 +340,7 @@ void dtls1_stop_timer(SSL *s)
 
 int dtls1_check_timeout_num(SSL *s)
 {
-    unsigned int mtu;
+    size_t mtu;
 
     s->d1->timeout.num_alerts++;
 
@@ -435,7 +431,7 @@ int DTLSv1_listen(SSL *s, BIO_ADDR *client)
     unsigned char seq[SEQ_NUM_SIZE];
     const unsigned char *data;
     unsigned char *buf;
-    unsigned long fragoff, fraglen, msglen;
+    size_t fragoff, fraglen, msglen;
     unsigned int rectype, versmajor, msgseq, msgtype, clientvers, cookielen;
     BIO *rbio, *wbio;
     BUF_MEM *bufm;
@@ -583,10 +579,10 @@ int DTLSv1_listen(SSL *s, BIO_ADDR *client)
 
         /* Finished processing the record header, now process the message */
         if (!PACKET_get_1(&msgpkt, &msgtype)
-            || !PACKET_get_net_3(&msgpkt, &msglen)
+            || !PACKET_get_net_3_len(&msgpkt, &msglen)
             || !PACKET_get_net_2(&msgpkt, &msgseq)
-            || !PACKET_get_net_3(&msgpkt, &fragoff)
-            || !PACKET_get_net_3(&msgpkt, &fraglen)
+            || !PACKET_get_net_3_len(&msgpkt, &fragoff)
+            || !PACKET_get_net_3_len(&msgpkt, &fraglen)
             || !PACKET_get_sub_packet(&msgpkt, &msgpayload, fraglen)
             || PACKET_remaining(&msgpkt) != 0) {
             SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
@@ -663,8 +659,7 @@ int DTLSv1_listen(SSL *s, BIO_ADDR *client)
                 return -1;
             }
             if (s->ctx->app_verify_cookie_cb(s, PACKET_data(&cookiepkt),
-                                             PACKET_remaining(&cookiepkt)) ==
-                0) {
+                    (unsigned int)PACKET_remaining(&cookiepkt)) == 0) {
                 /*
                  * We treat invalid cookies in the same was as no cookie as
                  * per RFC6347
@@ -795,6 +790,7 @@ int DTLSv1_listen(SSL *s, BIO_ADDR *client)
             BIO_ADDR_free(tmpclient);
             tmpclient = NULL;
 
+            /* TODO(size_t): convert this call */
             if (BIO_write(wbio, buf, wreclen) < (int)wreclen) {
                 if (BIO_should_retry(wbio)) {
                     /*
@@ -872,12 +868,13 @@ static int dtls1_handshake_write(SSL *s)
 
 # define HEARTBEAT_SIZE_STD(payload) HEARTBEAT_SIZE(payload, 16)
 
-int dtls1_process_heartbeat(SSL *s, unsigned char *p, unsigned int length)
+int dtls1_process_heartbeat(SSL *s, unsigned char *p, size_t length)
 {
     unsigned char *pl;
     unsigned short hbtype;
     unsigned int payload;
     unsigned int padding = 16;  /* Use minimum padding */
+    size_t written;
 
     if (s->msg_callback)
         s->msg_callback(0, s->version, DTLS1_RT_HEARTBEAT,
@@ -897,7 +894,7 @@ int dtls1_process_heartbeat(SSL *s, unsigned char *p, unsigned int length)
 
     if (hbtype == TLS1_HB_REQUEST) {
         unsigned char *buffer, *bp;
-        unsigned int write_length = HEARTBEAT_SIZE(payload, padding);
+        size_t write_length = HEARTBEAT_SIZE(payload, padding);
         int r;
 
         if (write_length > SSL3_RT_MAX_PLAIN_LENGTH)
@@ -920,16 +917,17 @@ int dtls1_process_heartbeat(SSL *s, unsigned char *p, unsigned int length)
             return -1;
         }
 
-        r = dtls1_write_bytes(s, DTLS1_RT_HEARTBEAT, buffer, write_length);
+        r = dtls1_write_bytes(s, DTLS1_RT_HEARTBEAT, buffer, write_length,
+                              &written);
 
-        if (r >= 0 && s->msg_callback)
+        if (r > 0 && s->msg_callback)
             s->msg_callback(1, s->version, DTLS1_RT_HEARTBEAT,
                             buffer, write_length, s, s->msg_callback_arg);
 
         OPENSSL_free(buffer);
 
-        if (r < 0)
-            return r;
+        if (r <= 0)
+            return -1;
     } else if (hbtype == TLS1_HB_RESPONSE) {
         unsigned int seq;
 
@@ -953,9 +951,9 @@ int dtls1_heartbeat(SSL *s)
 {
     unsigned char *buf, *p;
     int ret = -1;
-    unsigned int payload = 18;  /* Sequence number + random bytes */
-    unsigned int padding = 16;  /* Use minimum padding */
-    unsigned int size;
+    size_t payload = 18;  /* Sequence number + random bytes */
+    size_t padding = 16;  /* Use minimum padding */
+    size_t size, written;
 
     /* Only send if peer supports and accepts HB requests... */
     if (!(s->tlsext_heartbeat & SSL_DTLSEXT_HB_ENABLED) ||
@@ -1006,8 +1004,8 @@ int dtls1_heartbeat(SSL *s)
         goto err;
     }
 
-    ret = dtls1_write_bytes(s, DTLS1_RT_HEARTBEAT, buf, size);
-    if (ret >= 0) {
+    ret = dtls1_write_bytes(s, DTLS1_RT_HEARTBEAT, buf, size, &written);
+    if (ret > 0) {
         if (s->msg_callback)
             s->msg_callback(1, s->version, DTLS1_RT_HEARTBEAT,
                             buf, size, s, s->msg_callback_arg);
@@ -1070,7 +1068,7 @@ int dtls1_query_mtu(SSL *s)
                 /* Set to min mtu */
                 s->d1->mtu = dtls1_min_mtu(s);
                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
-                         s->d1->mtu, NULL);
+                         (long)s->d1->mtu, NULL);
             }
         } else
             return 0;
@@ -1078,13 +1076,13 @@ int dtls1_query_mtu(SSL *s)
     return 1;
 }
 
-static unsigned int dtls1_link_min_mtu(void)
+static size_t dtls1_link_min_mtu(void)
 {
     return (g_probable_mtu[(sizeof(g_probable_mtu) /
                             sizeof(g_probable_mtu[0])) - 1]);
 }
 
-unsigned int dtls1_min_mtu(SSL *s)
+size_t dtls1_min_mtu(SSL *s)
 {
     return dtls1_link_min_mtu() - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
 }
diff --git a/ssl/d1_msg.c b/ssl/d1_msg.c
index ae7aff6..ac6d284 100644
--- a/ssl/d1_msg.c
+++ b/ssl/d1_msg.c
@@ -10,7 +10,8 @@
 #define USE_SOCKETS
 #include "ssl_locl.h"
 
-int dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
+int dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, size_t len,
+                               size_t *written)
 {
     int i;
 
@@ -41,8 +42,7 @@ int dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
         return -1;
     }
 
-    i = dtls1_write_bytes(s, type, buf_, len);
-    return i;
+    return dtls1_write_bytes(s, type, buf_, len, written);
 }
 
 int dtls1_dispatch_alert(SSL *s)
@@ -51,6 +51,7 @@ int dtls1_dispatch_alert(SSL *s)
     void (*cb) (const SSL *ssl, int type, int val) = NULL;
     unsigned char buf[DTLS1_AL_HEADER_LENGTH];
     unsigned char *ptr = &buf[0];
+    size_t written;
 
     s->s3->alert_dispatch = 0;
 
@@ -65,7 +66,7 @@ int dtls1_dispatch_alert(SSL *s)
     }
 #endif
 
-    i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), 0);
+    i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), 0, &written);
     if (i <= 0) {
         s->s3->alert_dispatch = 1;
         /* fprintf( stderr, "not done with alert\n" ); */
@@ -91,5 +92,5 @@ int dtls1_dispatch_alert(SSL *s)
             cb(s, SSL_CB_WRITE_ALERT, j);
         }
     }
-    return (i);
+    return i;
 }
diff --git a/ssl/d1_srtp.c b/ssl/d1_srtp.c
index bcefb9e..718f417 100644
--- a/ssl/d1_srtp.c
+++ b/ssl/d1_srtp.c
@@ -40,7 +40,7 @@ static SRTP_PROTECTION_PROFILE srtp_known_profiles[] = {
 };
 
 static int find_profile_by_name(char *profile_name,
-                                SRTP_PROTECTION_PROFILE **pptr, unsigned len)
+                                SRTP_PROTECTION_PROFILE **pptr, size_t len)
 {
     SRTP_PROTECTION_PROFILE *p;
 
@@ -76,7 +76,8 @@ static int ssl_ctx_make_profiles(const char *profiles_string,
     do {
         col = strchr(ptr, ':');
 
-        if (!find_profile_by_name(ptr, &p, col ? col - ptr : (int)strlen(ptr))) {
+        if (!find_profile_by_name(ptr, &p, col ? (size_t)(col - ptr)
+                                               : strlen(ptr))) {
             if (sk_SRTP_PROTECTION_PROFILE_find(profiles, p) >= 0) {
                 SSLerr(SSL_F_SSL_CTX_MAKE_PROFILES,
                        SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
diff --git a/ssl/packet_locl.h b/ssl/packet_locl.h
index cee1400..94933c1 100644
--- a/ssl/packet_locl.h
+++ b/ssl/packet_locl.h
@@ -160,6 +160,18 @@ __owur static ossl_inline int PACKET_get_net_2(PACKET *pkt, unsigned int *data)
     return 1;
 }
 
+/* Same as PACKET_get_net_2() but for a size_t */
+__owur static ossl_inline int PACKET_get_net_2_len(PACKET *pkt, size_t *data)
+{
+    unsigned int i;
+    int ret = PACKET_get_net_2(pkt, &i);
+
+    if (ret)
+        *data = (size_t)i;
+
+    return ret;
+}
+
 /*
  * Peek ahead at 3 bytes in network order from |pkt| and store the value in
  * |*data|
@@ -189,6 +201,18 @@ __owur static ossl_inline int PACKET_get_net_3(PACKET *pkt, unsigned long *data)
     return 1;
 }
 
+/* Same as PACKET_get_net_3() but for a size_t */
+__owur static ossl_inline int PACKET_get_net_3_len(PACKET *pkt, size_t *data)
+{
+    unsigned long i;
+    int ret = PACKET_get_net_3(pkt, &i);
+
+    if (ret)
+        *data = (size_t)i;
+
+    return ret;
+}
+
 /*
  * Peek ahead at 4 bytes in network order from |pkt| and store the value in
  * |*data|
@@ -219,6 +243,18 @@ __owur static ossl_inline int PACKET_get_net_4(PACKET *pkt, unsigned long *data)
     return 1;
 }
 
+/* Same as PACKET_get_net_4() but for a size_t */
+__owur static ossl_inline int PACKET_get_net_4_len(PACKET *pkt, size_t *data)
+{
+    unsigned long i;
+    int ret = PACKET_get_net_4(pkt, &i);
+
+    if (ret)
+        *data = (size_t)i;
+
+    return ret;
+}
+
 /* Peek ahead at 1 byte from |pkt| and store the value in |*data| */
 __owur static ossl_inline int PACKET_peek_1(const PACKET *pkt,
                                             unsigned int *data)
@@ -242,6 +278,18 @@ __owur static ossl_inline int PACKET_get_1(PACKET *pkt, unsigned int *data)
     return 1;
 }
 
+/* Same as PACKET_get_1() but for a size_t */
+__owur static ossl_inline int PACKET_get_1_len(PACKET *pkt, size_t *data)
+{
+    unsigned int i;
+    int ret = PACKET_get_1(pkt, &i);
+
+    if (ret)
+        *data = (size_t)i;
+
+    return ret;
+}
+
 /*
  * Peek ahead at 4 bytes in reverse network order from |pkt| and store the value
  * in |*data|
diff --git a/ssl/pqueue.c b/ssl/pqueue.c
index b447e1d..7e0ced9 100644
--- a/ssl/pqueue.c
+++ b/ssl/pqueue.c
@@ -141,10 +141,10 @@ pitem *pqueue_next(pitem **item)
     return ret;
 }
 
-int pqueue_size(pqueue *pq)
+size_t pqueue_size(pqueue *pq)
 {
     pitem *item = pq->items;
-    int count = 0;
+    size_t count = 0;
 
     while (item != NULL) {
         count++;
diff --git a/ssl/record/rec_layer_d1.c b/ssl/record/rec_layer_d1.c
index c9fd066..d2bb678 100644
--- a/ssl/record/rec_layer_d1.c
+++ b/ssl/record/rec_layer_d1.c
@@ -118,8 +118,8 @@ void DTLS_RECORD_LAYER_set_write_sequence(RECORD_LAYER *rl, unsigned char *seq)
     memcpy(rl->write_sequence, seq, SEQ_NUM_SIZE);
 }
 
-static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
-                                   int len);
+static size_t have_handshake_fragment(SSL *s, int type, unsigned char *buf,
+                                      size_t len);
 
 /* copy buffered record into SSL structure */
 static int dtls1_copy_record(SSL *s, pitem *item)
@@ -336,10 +336,10 @@ int dtls1_process_buffered_records(SSL *s)
  *             none of our business
  */
 int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
-                     int len, int peek)
+                     size_t len, int peek, size_t *readbytes)
 {
-    int al, i, j, ret;
-    unsigned int n;
+    int al, i, j, iret;
+    size_t ret, n;
     SSL3_RECORD *rr;
     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
 
@@ -359,9 +359,11 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
     /*
      * check whether there's a handshake message (client hello?) waiting
      */
-    if ((ret = have_handshake_fragment(s, type, buf, len))) {
+    ret = have_handshake_fragment(s, type, buf, len);
+    if (ret > 0) {
         *recvd_type = SSL3_RT_HANDSHAKE;
-        return ret;
+        *readbytes = ret;
+        return 1;
     }
 
     /*
@@ -385,10 +387,10 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
         /* type == SSL3_RT_APPLICATION_DATA */
         i = s->handshake_func(s);
         if (i < 0)
-            return (i);
+            return i;
         if (i == 0) {
             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
-            return (-1);
+            return -1;
         }
     }
 
@@ -434,12 +436,12 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
     /* get new packet if necessary */
     if ((SSL3_RECORD_get_length(rr) == 0)
         || (s->rlayer.rstate == SSL_ST_READ_BODY)) {
-        ret = dtls1_get_record(s);
-        if (ret <= 0) {
-            ret = dtls1_read_failed(s, ret);
+        iret = dtls1_get_record(s);
+        if (iret <= 0) {
+            iret = dtls1_read_failed(s, iret);
             /* anything other than a timeout is an error */
-            if (ret <= 0)
-                return (ret);
+            if (iret <= 0)
+                return iret;
             else
                 goto start;
         }
@@ -479,7 +481,7 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
         SSL3_RECORD_set_length(rr, 0);
         s->rwstate = SSL_NOTHING;
-        return (0);
+        return 0;
     }
 
     if (type == SSL3_RECORD_get_type(rr)
@@ -504,13 +506,13 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
         if (recvd_type != NULL)
             *recvd_type = SSL3_RECORD_get_type(rr);
 
-        if (len <= 0)
-            return (len);
+        if (len == 0)
+            return 0;
 
-        if ((unsigned int)len > SSL3_RECORD_get_length(rr))
+        if (len > SSL3_RECORD_get_length(rr))
             n = SSL3_RECORD_get_length(rr);
         else
-            n = (unsigned int)len;
+            n = len;
 
         memcpy(buf, &(SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)]), n);
         if (!peek) {
@@ -543,10 +545,11 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
             s->d1->shutdown_received
             && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
-            return (0);
+            return 0;
         }
 #endif
-        return (n);
+        *readbytes = n;
+        return 1;
     }
 
     /*
@@ -559,9 +562,9 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
      * that so that we can process the data at a fixed place.
      */
     {
-        unsigned int k, dest_maxlen = 0;
+        size_t k, dest_maxlen = 0;
         unsigned char *dest = NULL;
-        unsigned int *dest_len = NULL;
+        size_t *dest_len = NULL;
 
         if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
             dest_maxlen = sizeof s->rlayer.d->handshake_fragment;
@@ -584,7 +587,7 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
             s->rwstate = SSL_READING;
             BIO_clear_retry_flags(SSL_get_rbio(s));
             BIO_set_retry_read(SSL_get_rbio(s));
-            return (-1);
+            return -1;
         }
 #endif
         /* else it's a CCS message, or application data or wrong */
@@ -600,7 +603,7 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
                 s->rwstate = SSL_READING;
                 BIO_clear_retry_flags(bio);
                 BIO_set_retry_read(bio);
-                return (-1);
+                return -1;
             }
 
             /* Not certain if this is the right error handling */
@@ -677,10 +680,10 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
             if (ssl3_renegotiate_check(s)) {
                 i = s->handshake_func(s);
                 if (i < 0)
-                    return (i);
+                    return i;
                 if (i == 0) {
                     SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
-                    return (-1);
+                    return -1;
                 }
 
                 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
@@ -697,7 +700,7 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
                         bio = SSL_get_rbio(s);
                         BIO_clear_retry_flags(bio);
                         BIO_set_retry_read(bio);
-                        return (-1);
+                        return -1;
                     }
                 }
             }
@@ -757,7 +760,7 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
                 }
 #endif
                 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
-                return (0);
+                return 0;
             }
 #if 0
             /* XXX: this is a possible improvement in the future */
@@ -797,7 +800,7 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
             ERR_add_error_data(2, "SSL alert number ", tmp);
             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
             SSL_CTX_remove_session(s->session_ctx, s->session);
-            return (0);
+            return 0;
         } else {
             al = SSL_AD_ILLEGAL_PARAMETER;
             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
@@ -811,7 +814,7 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
                                             * shutdown */
         s->rwstate = SSL_NOTHING;
         SSL3_RECORD_set_length(rr, 0);
-        return (0);
+        return 0;
     }
 
     if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
@@ -858,10 +861,10 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
         }
         i = s->handshake_func(s);
         if (i < 0)
-            return (i);
+            return i;
         if (i == 0) {
             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
-            return (-1);
+            return -1;
         }
 
         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
@@ -878,7 +881,7 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
                 bio = SSL_get_rbio(s);
                 BIO_clear_retry_flags(bio);
                 BIO_set_retry_read(bio);
-                return (-1);
+                return -1;
             }
         }
         goto start;
@@ -917,7 +920,7 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
             (s->s3->total_renegotiations != 0) &&
             ossl_statem_app_data_allowed(s)) {
             s->s3->in_read_app_data = 2;
-            return (-1);
+            return -1;
         } else {
             al = SSL_AD_UNEXPECTED_MESSAGE;
             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
@@ -928,15 +931,15 @@ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
 
  f_err:
     ssl3_send_alert(s, SSL3_AL_FATAL, al);
-    return (-1);
+    return -1;
 }
 
-        /*
-         * this only happens when a client hello is received and a handshake
-         * is started.
-         */
-static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
-                                   int len)
+/*
+ * this only happens when a client hello is received and a handshake
+ * is started.
+ */
+static size_t have_handshake_fragment(SSL *s, int type, unsigned char *buf,
+                                      size_t len)
 {
 
     if ((type == SSL3_RT_HANDSHAKE)
@@ -945,7 +948,7 @@ static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
     {
         unsigned char *src = s->rlayer.d->handshake_fragment;
         unsigned char *dst = buf;
-        unsigned int k, n;
+        size_t k, n;
 
         /* peek == 0 */
         n = 0;
@@ -968,22 +971,23 @@ static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
  * Call this to write data in records of type 'type' It will return <= 0 if
  * not all data has been sent or non-blocking IO.
  */
-int dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
+int dtls1_write_bytes(SSL *s, int type, const void *buf, size_t len,
+                      size_t *written)
 {
     int i;
 
     OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
     s->rwstate = SSL_NOTHING;
-    i = do_dtls1_write(s, type, buf, len, 0);
+    i = do_dtls1_write(s, type, buf, len, 0, written);
     return i;
 }
 
 int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
-                   unsigned int len, int create_empty_fragment)
+                   size_t len, int create_empty_fragment, size_t *written)
 {
     unsigned char *p, *pseq;
     int i, mac_size, clear = 0;
-    int prefix_len = 0;
+    size_t prefix_len = 0;
     int eivlen;
     SSL3_RECORD wr;
     SSL3_BUFFER *wb;
@@ -997,14 +1001,14 @@ int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
      */
     if (SSL3_BUFFER_get_left(wb) != 0) {
         OPENSSL_assert(0);      /* XDTLS: want to see if we ever get here */
-        return (ssl3_write_pending(s, type, buf, len));
+        return ssl3_write_pending(s, type, buf, len, written);
     }
 
     /* If we have an alert to send, lets send it */
     if (s->s3->alert_dispatch) {
         i = s->method->ssl_dispatch_alert(s);
         if (i <= 0)
-            return (i);
+            return i;
         /* if it went, fall through and send more stuff */
     }
 
@@ -1069,7 +1073,7 @@ int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
 
     /* lets setup the record stuff. */
     SSL3_RECORD_set_data(&wr, p + eivlen); /* make room for IV in case of CBC */
-    SSL3_RECORD_set_length(&wr, (int)len);
+    SSL3_RECORD_set_length(&wr, len);
     SSL3_RECORD_set_input(&wr, (unsigned char *)buf);
 
     /*
@@ -1095,9 +1099,9 @@ int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
      */
 
     if (!SSL_USE_ETM(s) && mac_size != 0) {
-        if (s->method->ssl3_enc->mac(s, &wr,
-                                     &(p[SSL3_RECORD_get_length(&wr) + eivlen]),
-                                     1) < 0)
+        if (!s->method->ssl3_enc->mac(s, &wr,
+                                      &(p[SSL3_RECORD_get_length(&wr) + eivlen]),
+                                      1))
             goto err;
         SSL3_RECORD_add_length(&wr, mac_size);
     }
@@ -1113,9 +1117,8 @@ int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
         goto err;
 
     if (SSL_USE_ETM(s) && mac_size != 0) {
-        if (s->method->ssl3_enc->mac(s, &wr,
-                                     &(p[SSL3_RECORD_get_length(&wr)]),
-                                     1) < 0)
+        if (!s->method->ssl3_enc->mac(s, &wr,
+                                      &(p[SSL3_RECORD_get_length(&wr)]), 1))
             goto err;
         SSL3_RECORD_add_length(&wr, mac_size);
     }
@@ -1157,7 +1160,8 @@ int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
          * we are in a recursive call; just return the length, don't write
          * out anything here
          */
-        return wr.length;
+        *written = wr.length;
+        return 1;
     }
 
     /* now let's set up wb */
@@ -1174,7 +1178,7 @@ int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
     s->rlayer.wpend_ret = len;
 
     /* we now just need to write the buffer */
-    return ssl3_write_pending(s, type, buf, len);
+    return ssl3_write_pending(s, type, buf, len, written);
  err:
     return -1;
 }
diff --git a/ssl/record/rec_layer_s3.c b/ssl/record/rec_layer_s3.c
index 28de7c3..779a29f 100644
--- a/ssl/record/rec_layer_s3.c
+++ b/ssl/record/rec_layer_s3.c
@@ -95,7 +95,8 @@ int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
         && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
 }
 
-int RECORD_LAYER_set_data(RECORD_LAYER *rl, const unsigned char *buf, int len)
+int RECORD_LAYER_set_data(RECORD_LAYER *rl, const unsigned char *buf,
+                          size_t len)
 {
     rl->packet_length = len;
     if (len != 0) {
@@ -121,10 +122,9 @@ void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
     memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
 }
 
-int ssl3_pending(const SSL *s)
+size_t ssl3_pending(const SSL *s)
 {
-    unsigned int i;
-    int num = 0;
+    size_t i, num = 0;
 
     if (s->rlayer.rstate == SSL_ST_READ_BODY)
         return 0;
@@ -179,11 +179,12 @@ const char *SSL_rstate_string(const SSL *s)
 
 /*
  * Return values are as per SSL_read(), i.e.
- * >0 The number of read bytes
+ *  1 Success
  *  0 Failure (not retryable)
  * <0 Failure (may be retryable)
  */
-int ssl3_read_n(SSL *s, int n, int max, int extend, int clearold)
+int ssl3_read_n(SSL *s, size_t n, size_t max, int extend, int clearold,
+                size_t *readbytes)
 {
     /*
      * If extend == 0, obtain new n-byte packet; if extend == 1, increase
@@ -194,13 +195,12 @@ int ssl3_read_n(SSL *s, int n, int max, int extend, int clearold)
      * if clearold == 1, move the packet to the start of the buffer; if
      * clearold == 0 then leave any old packets where they were
      */
-    int i, len, left;
-    size_t align = 0;
+    size_t len, left, align = 0;
     unsigned char *pkt;
     SSL3_BUFFER *rb;
 
-    if (n <= 0)
-        return n;
+    if (n == 0)
+        return 0;
 
     rb = &s->rlayer.rbuf;
     if (rb->buf == NULL)
@@ -270,12 +270,13 @@ int ssl3_read_n(SSL *s, int n, int max, int extend, int clearold)
         s->rlayer.packet_length += n;
         rb->left = left - n;
         rb->offset += n;
-        return (n);
+        *readbytes = n;
+        return 1;
     }
 
     /* else we need to read more data */
 
-    if (n > (int)(rb->len - rb->offset)) { /* does not happen */
+    if (n > rb->len - rb->offset) { /* does not happen */
         SSLerr(SSL_F_SSL3_READ_N, ERR_R_INTERNAL_ERROR);
         return -1;
     }
@@ -287,11 +288,14 @@ int ssl3_read_n(SSL *s, int n, int max, int extend, int clearold)
     else {
         if (max < n)
             max = n;
-        if (max > (int)(rb->len - rb->offset))
+        if (max > rb->len - rb->offset)
             max = rb->len - rb->offset;
     }
 
     while (left < n) {
+        size_t bioread = 0;
+        int ret;
+
         /*
          * Now we have len+left bytes at the front of s->s3->rbuf.buf and
          * need to read in more until we have len+n (up to len+max if
@@ -301,20 +305,23 @@ int ssl3_read_n(SSL *s, int n, int max, int extend, int clearold)
         clear_sys_error();
         if (s->rbio != NULL) {
             s->rwstate = SSL_READING;
-            i = BIO_read(s->rbio, pkt + len + left, max - left);
+            /* TODO(size_t): Convert this function */
+            ret = BIO_read(s->rbio, pkt + len + left, max - left);
+            if (ret >= 0)
+                bioread = ret;
         } else {
             SSLerr(SSL_F_SSL3_READ_N, SSL_R_READ_BIO_NOT_SET);
-            i = -1;
+            ret = -1;
         }
 
-        if (i <= 0) {
+        if (ret <= 0) {
             rb->left = left;
             if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
                 if (len + left == 0)
                     ssl3_release_read_buffer(s);
             return -1;
         }
-        left += i;
+        left += bioread;
         /*
          * reads should *never* span multiple packets for DTLS because the
          * underlying transport protocol is message oriented as opposed to
@@ -331,29 +338,26 @@ int ssl3_read_n(SSL *s, int n, int max, int extend, int clearold)
     rb->left = left - n;
     s->rlayer.packet_length += n;
     s->rwstate = SSL_NOTHING;
-    return (n);
+    *readbytes = n;
+    return 1;
 }
 
 /*
  * Call this to write data in records of type 'type' It will return <= 0 if
  * not all data has been sent or non-blocking IO.
  */
-int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
+int ssl3_write_bytes(SSL *s, int type, const void *buf_, size_t len,
+                     size_t *written)
 {
     const unsigned char *buf = buf_;
-    int tot;
-    unsigned int n, split_send_fragment, maxpipes;
+    size_t tot;
+    size_t n, split_send_fragment, maxpipes;
 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
-    unsigned int max_send_fragment, nw;
-    unsigned int u_len = (unsigned int)len;
+    size_t max_send_fragment, nw;
 #endif
     SSL3_BUFFER *wb = &s->rlayer.wbuf[0];
     int i;
-
-    if (len < 0) {
-        SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_NEGATIVE_LENGTH);
-        return -1;
-    }
+    size_t tmpwrit;
 
     s->rwstate = SSL_NOTHING;
     tot = s->rlayer.wnum;
@@ -366,7 +370,7 @@ int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
      * promptly send beyond the end of the users buffer ... so we trap and
      * report the error in a way the user will notice
      */
-    if ((unsigned int)len < s->rlayer.wnum) {
+    if (len < s->rlayer.wnum) {
         SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH);
         return -1;
     }
@@ -376,7 +380,7 @@ int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
     if (SSL_in_init(s) && !ossl_statem_get_in_handshake(s)) {
         i = s->handshake_func(s);
         if (i < 0)
-            return (i);
+            return i;
         if (i == 0) {
             SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
             return -1;
@@ -388,13 +392,14 @@ int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
      * will happen with non blocking IO
      */
     if (wb->left != 0) {
-        i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot);
+        i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot,
+                               &tmpwrit);
         if (i <= 0) {
             /* XXX should we ssl3_release_write_buffer if i<0? */
             s->rlayer.wnum = tot;
             return i;
         }
-        tot += i;               /* this might be last fragment */
+        tot += tmpwrit;               /* this might be last fragment */
     }
 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
     /*
@@ -404,14 +409,15 @@ int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
      * compromise is considered worthy.
      */
     if (type == SSL3_RT_APPLICATION_DATA &&
-        u_len >= 4 * (max_send_fragment = s->max_send_fragment) &&
+        len >= 4 * (max_send_fragment = s->max_send_fragment) &&
         s->compress == NULL && s->msg_callback == NULL &&
         !SSL_USE_ETM(s) && SSL_USE_EXPLICIT_IV(s) &&
         EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx)) &
         EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) {
         unsigned char aad[13];
         EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
-        int packlen;
+        size_t packlen;
+        int packleni;
 
         /* minimize address aliasing conflicts */
         if ((max_send_fragment & 0xfff) == 0)
@@ -422,9 +428,9 @@ int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
 
             packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
                                           EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
-                                          max_send_fragment, NULL);
+                                          (int)max_send_fragment, NULL);
 
-            if (u_len >= 8 * max_send_fragment)
+            if (len >= 8 * max_send_fragment)
                 packlen *= 8;
             else
                 packlen *= 4;
@@ -436,7 +442,8 @@ int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
         } else if (tot == len) { /* done? */
             /* free jumbo buffer */
             ssl3_release_write_buffer(s);
-            return tot;
+            *written = tot;
+            return 1;
         }
 
         n = (len - tot);
@@ -470,11 +477,11 @@ int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
             mb_param.inp = aad;
             mb_param.len = nw;
 
-            packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
+            packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
                                           EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
                                           sizeof(mb_param), &mb_param);
-
-            if (packlen <= 0 || packlen > (int)wb->len) { /* never happens */
+            packlen = (size_t)packleni;
+            if (packleni <= 0 || packlen > wb->len) { /* never happens */
                 /* free jumbo buffer */
                 ssl3_release_write_buffer(s);
                 break;
@@ -503,7 +510,7 @@ int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
             s->rlayer.wpend_type = type;
             s->rlayer.wpend_ret = nw;
 
-            i = ssl3_write_pending(s, type, &buf[tot], nw);
+            i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
             if (i <= 0) {
                 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
                     /* free jumbo buffer */
@@ -512,13 +519,14 @@ int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
                 s->rlayer.wnum = tot;
                 return i;
             }
-            if (i == (int)n) {
+            if (tmpwrit == n) {
                 /* free jumbo buffer */
                 ssl3_release_write_buffer(s);
-                return tot + i;
+                *written = tot + tmpwrit;
+                return 1;
             }
-            n -= i;
-            tot += i;
+            n -= tmpwrit;
+            tot += tmpwrit;
         }
     } else
 #endif
@@ -526,7 +534,8 @@ int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
         if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
             ssl3_release_write_buffer(s);
 
-        return tot;
+        *written = tot;
+        return 1;
     }
 
     n = (len - tot);
@@ -564,8 +573,8 @@ int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
     }
 
     for (;;) {
-        unsigned int pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
-        unsigned int numpipes, j;
+        size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
+        size_t numpipes, j;
 
         if (n == 0)
             numpipes = 1;
@@ -593,14 +602,15 @@ int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
             }
         }
 
-        i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0);
+        i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0,
+                          &tmpwrit);
         if (i <= 0) {
             /* XXX should we ssl3_release_write_buffer if i<0? */
             s->rlayer.wnum = tot;
             return i;
         }
 
-        if ((i == (int)n) ||
+        if (tmpwrit == n ||
             (type == SSL3_RT_APPLICATION_DATA &&
              (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
             /*
@@ -613,28 +623,29 @@ int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
                 !SSL_IS_DTLS(s))
                 ssl3_release_write_buffer(s);
 
-            return tot + i;
+            *written = tot + tmpwrit;
+            return 1;
         }
 
-        n -= i;
-        tot += i;
+        n -= tmpwrit;
+        tot += tmpwrit;
     }
 }
 
 int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
-                  unsigned int *pipelens, unsigned int numpipes,
-                  int create_empty_fragment)
+                  size_t *pipelens, size_t numpipes,
+                  int create_empty_fragment, size_t *written)
 {
     unsigned char *outbuf[SSL_MAX_PIPELINES], *plen[SSL_MAX_PIPELINES];
     SSL3_RECORD wr[SSL_MAX_PIPELINES];
     int i, mac_size, clear = 0;
-    int prefix_len = 0;
+    size_t prefix_len = 0;
     int eivlen;
     size_t align = 0;
     SSL3_BUFFER *wb;
     SSL_SESSION *sess;
-    unsigned int totlen = 0;
-    unsigned int j;
+    size_t totlen = 0;
+    size_t j;
 
     for (j = 0; j < numpipes; j++)
         totlen += pipelens[j];
@@ -643,7 +654,7 @@ int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
      * will happen with non blocking IO
      */
     if (RECORD_LAYER_write_pending(&s->rlayer))
-        return (ssl3_write_pending(s, type, buf, totlen));
+        return ssl3_write_pending(s, type, buf, totlen, written);
 
     /* If we have an alert to send, lets send it */
     if (s->s3->alert_dispatch) {
@@ -667,6 +678,7 @@ int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
         clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
         mac_size = 0;
     } else {
+        /* TODO(siz_t): Convert me */
         mac_size = EVP_MD_CTX_size(s->write_hash);
         if (mac_size < 0)
             goto err;
@@ -688,10 +700,11 @@ int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
              * 'prefix_len' bytes are sent out later together with the actual
              * payload)
              */
-            unsigned int tmppipelen = 0;
+            size_t tmppipelen = 0;
+            int ret;
 
-            prefix_len = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1);
-            if (prefix_len <= 0)
+            ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len);
+            if (ret <= 0)
                 goto err;
 
             if (prefix_len >
@@ -738,6 +751,7 @@ int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
     if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)) {
         int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
         if (mode == EVP_CIPH_CBC_MODE) {
+            /* TODO(size_t): Convert me */
             eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
             if (eivlen <= 1)
                 eivlen = 0;
@@ -777,7 +791,7 @@ int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
 
         /* lets setup the record stuff. */
         SSL3_RECORD_set_data(&wr[j], outbuf[j] + eivlen);
-        SSL3_RECORD_set_length(&wr[j], (int)pipelens[j]);
+        SSL3_RECORD_set_length(&wr[j], pipelens[j]);
         SSL3_RECORD_set_input(&wr[j], (unsigned char *)&buf[totlen]);
         totlen += pipelens[j];
 
@@ -803,9 +817,9 @@ int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
          */
 
         if (!SSL_USE_ETM(s) && mac_size != 0) {
-            if (s->method->ssl3_enc->mac(s, &wr[j],
-                                         &(outbuf[j][wr[j].length + eivlen]),
-                                         1) < 0)
+            if (!s->method->ssl3_enc->mac(s, &wr[j],
+                                          &(outbuf[j][wr[j].length + eivlen]),
+                                          1))
                 goto err;
             SSL3_RECORD_add_length(&wr[j], mac_size);
         }
@@ -826,8 +840,8 @@ int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
 
     for (j = 0; j < numpipes; j++) {
         if (SSL_USE_ETM(s) && mac_size != 0) {
-            if (s->method->ssl3_enc->mac(s, &wr[j],
-                                         outbuf[j] + wr[j].length, 1) < 0)
+            if (!s->method->ssl3_enc->mac(s, &wr[j],
+                                          outbuf[j] + wr[j].length, 1))
                 goto err;
             SSL3_RECORD_add_length(&wr[j], mac_size);
         }
@@ -857,7 +871,8 @@ int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
                 SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
                 goto err;
             }
-            return SSL3_RECORD_get_length(wr);
+            *written = SSL3_RECORD_get_length(wr);
+            return 1;
         }
 
         /* now let's set up wb */
@@ -875,7 +890,7 @@ int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
     s->rlayer.wpend_ret = totlen;
 
     /* we now just need to write the buffer */
-    return ssl3_write_pending(s, type, buf, totlen);
+    return ssl3_write_pending(s, type, buf, totlen, written);
  err:
     return -1;
 }
@@ -883,24 +898,24 @@ int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
 /* if s->s3->wbuf.left != 0, we need to call this
  *
  * Return values are as per SSL_read(), i.e.
- * >0 The number of read bytes
+ *  1 Success
  *  0 Failure (not retryable)
  * <0 Failure (may be retryable)
  */
-int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
-                       unsigned int len)
+int ssl3_write_pending(SSL *s, int type, const unsigned char *buf, size_t len,
+                       size_t *written)
 {
     int i;
     SSL3_BUFFER *wb = s->rlayer.wbuf;
-    unsigned int currbuf = 0;
+    size_t currbuf = 0;
+    size_t tmpwrit = 0;
 
-/* XXXX */
-    if ((s->rlayer.wpend_tot > (int)len)
+    if ((s->rlayer.wpend_tot > len)
         || ((s->rlayer.wpend_buf != buf) &&
             !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
         || (s->rlayer.wpend_type != type)) {
         SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BAD_WRITE_RETRY);
-        return (-1);
+        return -1;
     }
 
     for (;;) {
@@ -913,21 +928,25 @@ int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
         clear_sys_error();
         if (s->wbio != NULL) {
             s->rwstate = SSL_WRITING;
+            /* TODO(size_t): Convert this call */
             i = BIO_write(s->wbio, (char *)
                           &(SSL3_BUFFER_get_buf(&wb[currbuf])
                             [SSL3_BUFFER_get_offset(&wb[currbuf])]),
                           (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
+            if (i >= 0)
+                tmpwrit = i;
         } else {
             SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BIO_NOT_SET);
             i = -1;
         }
-        if (i == SSL3_BUFFER_get_left(&wb[currbuf])) {
+        if (i > 0 && tmpwrit == SSL3_BUFFER_get_left(&wb[currbuf])) {
             SSL3_BUFFER_set_left(&wb[currbuf], 0);
-            SSL3_BUFFER_add_offset(&wb[currbuf], i);
+            SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
             if (currbuf + 1 < s->rlayer.numwpipes)
                 continue;
             s->rwstate = SSL_NOTHING;
-            return (s->rlayer.wpend_ret);
+            *written = s->rlayer.wpend_ret;
+            return 1;
         } else if (i <= 0) {
             if (SSL_IS_DTLS(s)) {
                 /*
@@ -938,8 +957,8 @@ int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
             }
             return -1;
         }
-        SSL3_BUFFER_add_offset(&wb[currbuf], i);
-        SSL3_BUFFER_add_left(&wb[currbuf], -i);
+        SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
+        SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit);
     }
 }
 
@@ -973,10 +992,10 @@ int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
  *             none of our business
  */
 int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
-                    int len, int peek)
+                    size_t len, int peek, size_t *readbytes)
 {
     int al, i, j, ret;
-    unsigned int n, curr_rec, num_recs, read_bytes;
+    size_t n, curr_rec, num_recs, totalbytes;
     SSL3_RECORD *rr;
     SSL3_BUFFER *rbuf;
     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
@@ -986,7 +1005,7 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
     if (!SSL3_BUFFER_is_initialised(rbuf)) {
         /* Not initialized yet */
         if (!ssl3_setup_read_buffer(s))
-            return (-1);
+            return -1;
     }
 
     if ((type && (type != SSL3_RT_APPLICATION_DATA)
@@ -1019,7 +1038,8 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
         if (recvd_type != NULL)
             *recvd_type = SSL3_RT_HANDSHAKE;
 
-        return n;
+        *readbytes = n;
+        return 1;
     }
 
     /*
@@ -1030,10 +1050,10 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
         /* type == SSL3_RT_APPLICATION_DATA */
         i = s->handshake_func(s);
         if (i < 0)
-            return (i);
+            return i;
         if (i == 0) {
             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
-            return (-1);
+            return -1;
         }
     }
  start:
@@ -1054,7 +1074,7 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
         if (num_recs == 0) {
             ret = ssl3_get_record(s);
             if (ret <= 0)
-                return (ret);
+                return ret;
             num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
             if (num_recs == 0) {
                 /* Shouldn't happen */
@@ -1100,7 +1120,7 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
         SSL3_RECORD_set_length(rr, 0);
         s->rwstate = SSL_NOTHING;
-        return (0);
+        return 0;
     }
 
     if (type == SSL3_RECORD_get_type(rr)
@@ -1133,15 +1153,15 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
         if (recvd_type != NULL)
             *recvd_type = SSL3_RECORD_get_type(rr);
 
-        if (len <= 0)
-            return (len);
+        if (len == 0)
+            return 0;
 
-        read_bytes = 0;
+        totalbytes = 0;
         do {
-            if ((unsigned int)len - read_bytes > SSL3_RECORD_get_length(rr))
+            if (len - totalbytes > SSL3_RECORD_get_length(rr))
                 n = SSL3_RECORD_get_length(rr);
             else
-                n = (unsigned int)len - read_bytes;
+                n = len - totalbytes;
 
             memcpy(buf, &(rr->data[rr->off]), n);
             buf += n;
@@ -1163,10 +1183,10 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
                 curr_rec++;
                 rr++;
             }
-            read_bytes += n;
+            totalbytes += n;
         } while (type == SSL3_RT_APPLICATION_DATA && curr_rec < num_recs
-                 && read_bytes < (unsigned int)len);
-        if (read_bytes == 0) {
+                 && totalbytes < len);
+        if (totalbytes == 0) {
             /* We must have read empty records. Get more data */
             goto start;
         }
@@ -1174,7 +1194,8 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
             && (s->mode & SSL_MODE_RELEASE_BUFFERS)
             && SSL3_BUFFER_get_left(rbuf) == 0)
             ssl3_release_read_buffer(s);
-        return read_bytes;
+        *readbytes = totalbytes;
+        return 1;
     }
 
     /*
@@ -1217,9 +1238,9 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
      * that so that we can process the data at a fixed place.
      */
     {
-        unsigned int dest_maxlen = 0;
+        size_t dest_maxlen = 0;
         unsigned char *dest = NULL;
-        unsigned int *dest_len = NULL;
+        size_t *dest_len = NULL;
 
         if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
             dest_maxlen = sizeof s->rlayer.handshake_fragment;
@@ -1284,10 +1305,10 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
             if (ssl3_renegotiate_check(s)) {
                 i = s->handshake_func(s);
                 if (i < 0)
-                    return (i);
+                    return i;
                 if (i == 0) {
                     SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
-                    return (-1);
+                    return -1;
                 }
 
                 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
@@ -1304,7 +1325,7 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
                         bio = SSL_get_rbio(s);
                         BIO_clear_retry_flags(bio);
                         BIO_set_retry_read(bio);
-                        return (-1);
+                        return -1;
                     }
                 }
             }
@@ -1367,7 +1388,7 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
 
             if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
                 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
-                return (0);
+                return 0;
             }
             /*
              * This is a warning but we receive it if we requested
@@ -1397,7 +1418,7 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
             SSL3_RECORD_set_read(rr);
             SSL_CTX_remove_session(s->session_ctx, s->session);
-            return (0);
+            return 0;
         } else {
             al = SSL_AD_ILLEGAL_PARAMETER;
             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
@@ -1412,7 +1433,7 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
         s->rwstate = SSL_NOTHING;
         SSL3_RECORD_set_length(rr, 0);
         SSL3_RECORD_set_read(rr);
-        return (0);
+        return 0;
     }
 
     if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
@@ -1434,10 +1455,10 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
         }
         i = s->handshake_func(s);
         if (i < 0)
-            return (i);
+            return i;
         if (i == 0) {
             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
-            return (-1);
+            return -1;
         }
 
         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
@@ -1454,7 +1475,7 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
                 bio = SSL_get_rbio(s);
                 BIO_clear_retry_flags(bio);
                 BIO_set_retry_read(bio);
-                return (-1);
+                return -1;
             }
         }
         goto start;
@@ -1493,7 +1514,7 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
          */
         if (ossl_statem_app_data_allowed(s)) {
             s->s3->in_read_app_data = 2;
-            return (-1);
+            return -1;
         } else {
             al = SSL_AD_UNEXPECTED_MESSAGE;
             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
@@ -1504,7 +1525,7 @@ int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
 
  f_err:
     ssl3_send_alert(s, SSL3_AL_FATAL, al);
-    return (-1);
+    return -1;
 }
 
 void ssl3_record_sequence_update(unsigned char *seq)
@@ -1530,7 +1551,7 @@ int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
 /*
  * Returns the length in bytes of the current rrec
  */
-unsigned int RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
+size_t RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
 {
     return SSL3_RECORD_get_length(&rl->rrec[0]);
 }
diff --git a/ssl/record/record.h b/ssl/record/record.h
index 3e1530f..e30010d 100644
--- a/ssl/record/record.h
+++ b/ssl/record/record.h
@@ -22,9 +22,9 @@ typedef struct ssl3_buffer_st {
     /* buffer size */
     size_t len;
     /* where to 'copy from' */
-    int offset;
+    size_t offset;
     /* how many bytes left */
-    int left;
+    size_t left;
 } SSL3_BUFFER;
 
 #define SEQ_NUM_SIZE                            8
@@ -38,16 +38,16 @@ typedef struct ssl3_record_st {
     int type;
     /* How many bytes available */
     /* rw */
-    unsigned int length;
+    size_t length;
     /*
      * How many bytes were available before padding was removed? This is used
      * to implement the MAC check in constant time for CBC records.
      */
     /* rw */
-    unsigned int orig_len;
+    size_t orig_len;
     /* read/write offset into 'buf' */
     /* r */
-    unsigned int off;
+    size_t off;
     /* pointer to the record data */
     /* rw */
     unsigned char *data;
@@ -82,7 +82,7 @@ typedef struct record_pqueue_st {
 
 typedef struct dtls1_record_data_st {
     unsigned char *packet;
-    unsigned int packet_length;
+    size_t packet_length;
     SSL3_BUFFER rbuf;
     SSL3_RECORD rrec;
 #ifndef OPENSSL_NO_SCTP
@@ -116,9 +116,9 @@ typedef struct dtls_record_layer_st {
      * processed by ssl3_read_bytes:
      */
     unsigned char alert_fragment[DTLS1_AL_HEADER_LENGTH];
-    unsigned int alert_fragment_len;
+    size_t alert_fragment_len;
     unsigned char handshake_fragment[DTLS1_HM_HEADER_LENGTH];
-    unsigned int handshake_fragment_len;
+    size_t handshake_fragment_len;
     /* save last and current sequence numbers for retransmissions */
     unsigned char last_write_sequence[8];
     unsigned char curr_write_sequence[8];
@@ -143,9 +143,9 @@ typedef struct record_layer_st {
     /* where we are when reading */
     int rstate;
     /* How many pipelines can be used to read data */
-    unsigned int numrpipes;
+    size_t numrpipes;
     /* How many pipelines can be used to write data */
-    unsigned int numwpipes;
+    size_t numwpipes;
     /* read IO goes into here */
     SSL3_BUFFER rbuf;
     /* write IO goes into here */
@@ -154,25 +154,25 @@ typedef struct record_layer_st {
     SSL3_RECORD rrec[SSL_MAX_PIPELINES];
     /* used internally to point at a raw packet */
     unsigned char *packet;
-    unsigned int packet_length;
+    size_t packet_length;
     /* number of bytes sent so far */
-    unsigned int wnum;
+    size_t wnum;
     /*
      * storage for Alert/Handshake protocol data received but not yet
      * processed by ssl3_read_bytes:
      */
     unsigned char alert_fragment[2];
-    unsigned int alert_fragment_len;
+    size_t alert_fragment_len;
     unsigned char handshake_fragment[4];
-    unsigned int handshake_fragment_len;
+    size_t handshake_fragment_len;
     /* The number of consecutive empty records we have received */
-    unsigned int empty_record_count;
+    size_t empty_record_count;
     /* partial write - check the numbers match */
     /* number bytes written */
-    int wpend_tot;
+    size_t wpend_tot;
     int wpend_type;
     /* number of bytes submitted */
-    int wpend_ret;
+    size_t wpend_ret;
     const unsigned char *wpend_buf;
     unsigned char read_sequence[SEQ_NUM_SIZE];
     unsigned char write_sequence[SEQ_NUM_SIZE];
@@ -208,24 +208,27 @@ void RECORD_LAYER_clear(RECORD_LAYER *rl);
 void RECORD_LAYER_release(RECORD_LAYER *rl);
 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl);
 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl);
-int RECORD_LAYER_set_data(RECORD_LAYER *rl, const unsigned char *buf, int len);
+int RECORD_LAYER_set_data(RECORD_LAYER *rl, const unsigned char *buf,
+                          size_t len);
 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl);
 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl);
 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl);
-unsigned int RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl);
-__owur int ssl3_pending(const SSL *s);
-__owur int ssl3_write_bytes(SSL *s, int type, const void *buf, int len);
-__owur int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
-                         unsigned int *pipelens, unsigned int numpipes,
-                         int create_empty_fragment);
+size_t RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl);
+__owur size_t ssl3_pending(const SSL *s);
+__owur int ssl3_write_bytes(SSL *s, int type, const void *buf, size_t len,
+                            size_t *written);
+int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
+                  size_t *pipelens, size_t numpipes,
+                  int create_empty_fragment, size_t *written);
 __owur int ssl3_read_bytes(SSL *s, int type, int *recvd_type,
-                           unsigned char *buf, int len, int peek);
+                           unsigned char *buf, size_t len, int peek,
+                           size_t *readbytes);
 __owur int ssl3_setup_buffers(SSL *s);
-__owur int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, unsigned int n_recs, int send);
+__owur int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, size_t n_recs, int send);
 __owur int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send);
-__owur int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
-                              unsigned int len);
-__owur int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int n_recs, int send);
+__owur int ssl3_write_pending(SSL *s, int type, const unsigned char *buf, size_t len,
+                              size_t *written);
+__owur int tls1_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int send);
 __owur int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send);
 int DTLS_RECORD_LAYER_new(RECORD_LAYER *rl);
 void DTLS_RECORD_LAYER_free(RECORD_LAYER *rl);
@@ -235,8 +238,10 @@ void DTLS_RECORD_LAYER_clear(RECORD_LAYER *rl);
 void DTLS_RECORD_LAYER_resync_write(RECORD_LAYER *rl);
 void DTLS_RECORD_LAYER_set_write_sequence(RECORD_LAYER *rl, unsigned char *seq);
 __owur int dtls1_read_bytes(SSL *s, int type, int *recvd_type,
-                            unsigned char *buf, int len, int peek);
-__owur int dtls1_write_bytes(SSL *s, int type, const void *buf, int len);
-__owur int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
-                          unsigned int len, int create_empty_fragement);
+                            unsigned char *buf, size_t len, int peek,
+                            size_t *readbytes);
+__owur int dtls1_write_bytes(SSL *s, int type, const void *buf, size_t len,
+                             size_t *written);
+int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
+                   size_t len, int create_empty_fragment, size_t *written);
 void dtls1_reset_seq_numbers(SSL *s, int rw);
diff --git a/ssl/record/record_locl.h b/ssl/record/record_locl.h
index b69afd8..6394835 100644
--- a/ssl/record/record_locl.h
+++ b/ssl/record/record_locl.h
@@ -38,7 +38,8 @@
 #define RECORD_LAYER_clear_first_record(rl)     ((rl)->is_first_record = 0)
 #define DTLS_RECORD_LAYER_get_r_epoch(rl)       ((rl)->d->r_epoch)
 
-__owur int ssl3_read_n(SSL *s, int n, int max, int extend, int clearold);
+__owur int ssl3_read_n(SSL *s, size_t n, size_t max, int extend, int clearold,
+                       size_t *readbytes);
 
 void RECORD_LAYER_set_write_sequence(RECORD_LAYER *rl, const unsigned char *ws);
 DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
@@ -61,7 +62,7 @@ void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
 #define SSL3_BUFFER_set_len(b, l)           ((b)->len = (l))
 #define SSL3_BUFFER_get_left(b)             ((b)->left)
 #define SSL3_BUFFER_set_left(b, l)          ((b)->left = (l))
-#define SSL3_BUFFER_add_left(b, l)          ((b)->left += (l))
+#define SSL3_BUFFER_sub_left(b, l)          ((b)->left -= (l))
 #define SSL3_BUFFER_get_offset(b)           ((b)->offset)
 #define SSL3_BUFFER_set_offset(b, o)        ((b)->offset = (o))
 #define SSL3_BUFFER_add_offset(b, o)        ((b)->offset += (o))
@@ -69,10 +70,10 @@ void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
 #define SSL3_BUFFER_set_default_len(b, l)   ((b)->default_len = (l))
 
 void SSL3_BUFFER_clear(SSL3_BUFFER *b);
-void SSL3_BUFFER_set_data(SSL3_BUFFER *b, const unsigned char *d, int n);
+void SSL3_BUFFER_set_data(SSL3_BUFFER *b, const unsigned char *d, size_t n);
 void SSL3_BUFFER_release(SSL3_BUFFER *b);
 __owur int ssl3_setup_read_buffer(SSL *s);
-__owur int ssl3_setup_write_buffer(SSL *s, unsigned int numwpipes, size_t len);
+__owur int ssl3_setup_write_buffer(SSL *s, size_t numwpipes, size_t len);
 int ssl3_release_read_buffer(SSL *s);
 int ssl3_release_write_buffer(SSL *s);
 
@@ -99,18 +100,18 @@ int ssl3_release_write_buffer(SSL *s);
 #define SSL3_RECORD_is_read(r)                  ((r)->read)
 #define SSL3_RECORD_set_read(r)                 ((r)->read = 1)
 
-void SSL3_RECORD_clear(SSL3_RECORD *r, unsigned int num_recs);
-void SSL3_RECORD_release(SSL3_RECORD *r, unsigned int num_recs);
+void SSL3_RECORD_clear(SSL3_RECORD *r, size_t);
+void SSL3_RECORD_release(SSL3_RECORD *r, size_t num_recs);
 void SSL3_RECORD_set_seq_num(SSL3_RECORD *r, const unsigned char *seq_num);
 int ssl3_get_record(SSL *s);
 __owur int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr);
 __owur int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr);
 void ssl3_cbc_copy_mac(unsigned char *out,
-                       const SSL3_RECORD *rec, unsigned md_size);
+                       const SSL3_RECORD *rec, size_t md_size);
 __owur int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
-                                   unsigned block_size, unsigned mac_size);
+                                   size_t block_size, size_t mac_size);
 __owur int tls1_cbc_remove_padding(const SSL *s,
                                    SSL3_RECORD *rec,
-                                   unsigned block_size, unsigned mac_size);
+                                   size_t block_size, size_t mac_size);
 int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap);
 __owur int dtls1_get_record(SSL *s);
diff --git a/ssl/record/ssl3_buffer.c b/ssl/record/ssl3_buffer.c
index 9638002..df1f900 100644
--- a/ssl/record/ssl3_buffer.c
+++ b/ssl/record/ssl3_buffer.c
@@ -10,7 +10,7 @@
 #include "../ssl_locl.h"
 #include "record_locl.h"
 
-void SSL3_BUFFER_set_data(SSL3_BUFFER *b, const unsigned char *d, int n)
+void SSL3_BUFFER_set_data(SSL3_BUFFER *b, const unsigned char *d, size_t n)
 {
     if (d != NULL)
         memcpy(b->buf, d, n);
@@ -74,12 +74,12 @@ int ssl3_setup_read_buffer(SSL *s)
     return 0;
 }
 
-int ssl3_setup_write_buffer(SSL *s, unsigned int numwpipes, size_t len)
+int ssl3_setup_write_buffer(SSL *s, size_t numwpipes, size_t len)
 {
     unsigned char *p;
     size_t align = 0, headerlen;
     SSL3_BUFFER *wb;
-    unsigned int currpipe;
+    size_t currpipe;
 
     s->rlayer.numwpipes = numwpipes;
 
@@ -134,7 +134,7 @@ int ssl3_setup_buffers(SSL *s)
 int ssl3_release_write_buffer(SSL *s)
 {
     SSL3_BUFFER *wb;
-    unsigned int pipes;
+    size_t pipes;
 
     pipes = s->rlayer.numwpipes;
     while (pipes > 0) {
diff --git a/ssl/record/ssl3_record.c b/ssl/record/ssl3_record.c
index 3236166..f160c06 100644
--- a/ssl/record/ssl3_record.c
+++ b/ssl/record/ssl3_record.c
@@ -33,10 +33,10 @@ static const unsigned char ssl3_pad_2[48] = {
 /*
  * Clear the contents of an SSL3_RECORD but retain any memory allocated
  */
-void SSL3_RECORD_clear(SSL3_RECORD *r, unsigned int num_recs)
+void SSL3_RECORD_clear(SSL3_RECORD *r, size_t num_recs)
 {
     unsigned char *comp;
-    unsigned int i;
+    size_t i;
 
     for (i = 0; i < num_recs; i++) {
         comp = r[i].comp;
@@ -46,9 +46,9 @@ void SSL3_RECORD_clear(SSL3_RECORD *r, unsigned int num_recs)
     }
 }
 
-void SSL3_RECORD_release(SSL3_RECORD *r, unsigned int num_recs)
+void SSL3_RECORD_release(SSL3_RECORD *r, size_t num_recs)
 {
-    unsigned int i;
+    size_t i;
 
     for (i = 0; i < num_recs; i++) {
         OPENSSL_free(r[i].comp);
@@ -68,7 +68,7 @@ void SSL3_RECORD_set_seq_num(SSL3_RECORD *r, const unsigned char *seq_num)
 static int ssl3_record_app_data_waiting(SSL *s)
 {
     SSL3_BUFFER *rbuf;
-    int left, len;
+    size_t left, len;
     unsigned char *p;
 
     rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
@@ -125,17 +125,18 @@ static int ssl3_record_app_data_waiting(SSL *s)
 int ssl3_get_record(SSL *s)
 {
     int ssl_major, ssl_minor, al;
-    int enc_err, n, i, ret = -1;
+    int enc_err, rret, ret = -1;
+    int i;
+    size_t more, n;
     SSL3_RECORD *rr;
     SSL3_BUFFER *rbuf;
     SSL_SESSION *sess;
     unsigned char *p;
     unsigned char md[EVP_MAX_MD_SIZE];
     short version;
-    unsigned mac_size;
-    unsigned int num_recs = 0;
-    unsigned int max_recs;
-    unsigned int j;
+    size_t mac_size;
+    int imac_size;
+    size_t num_recs = 0, max_recs, j;
 
     rr = RECORD_LAYER_get_rrec(&s->rlayer);
     rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
@@ -149,11 +150,11 @@ int ssl3_get_record(SSL *s)
         if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
             (RECORD_LAYER_get_packet_length(&s->rlayer)
              < SSL3_RT_HEADER_LENGTH)) {
-            n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
-                            SSL3_BUFFER_get_len(rbuf), 0,
-                            num_recs == 0 ? 1 : 0);
-            if (n <= 0)
-                return (n);     /* error or non-blocking */
+            rret = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
+                               SSL3_BUFFER_get_len(rbuf), 0,
+                               num_recs == 0 ? 1 : 0, &n);
+            if (rret <= 0)
+                return rret;     /* error or non-blocking */
             RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
 
             p = RECORD_LAYER_get_packet(&s->rlayer);
@@ -274,17 +275,17 @@ int ssl3_get_record(SSL *s)
          * record
          */
         if (rr[num_recs].rec_version == SSL2_VERSION) {
-            i = rr[num_recs].length + SSL2_RT_HEADER_LENGTH
+            more = rr[num_recs].length + SSL2_RT_HEADER_LENGTH
                 - SSL3_RT_HEADER_LENGTH;
         } else {
-            i = rr[num_recs].length;
+            more = rr[num_recs].length;
         }
-        if (i > 0) {
+        if (more > 0) {
             /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
 
-            n = ssl3_read_n(s, i, i, 1, 0);
-            if (n <= 0)
-                return (n);     /* error or non-blocking io */
+            rret = ssl3_read_n(s, more, more, 1, 0, &n);
+            if (rret <= 0)
+                return rret;     /* error or non-blocking io */
         }
 
         /* set state for later operations */
@@ -348,7 +349,14 @@ int ssl3_get_record(SSL *s)
      */
     if (SSL_USE_ETM(s) && s->read_hash) {
         unsigned char *mac;
-        mac_size = EVP_MD_CTX_size(s->read_hash);
+        /* TODO(size_t): convert this to do size_t properly */
+        imac_size = EVP_MD_CTX_size(s->read_hash);
+        if (imac_size < 0) {
+                al = SSL_AD_INTERNAL_ERROR;
+                SSLerr(SSL_F_SSL3_GET_RECORD, ERR_LIB_EVP);
+                goto f_err;
+        }
+        mac_size = (size_t)imac_size;
         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
         for (j = 0; j < num_recs; j++) {
             if (rr[j].length < mac_size) {
@@ -359,7 +367,7 @@ int ssl3_get_record(SSL *s)
             rr[j].length -= mac_size;
             mac = rr[j].data + rr[j].length;
             i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ );
-            if (i < 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
+            if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
                 al = SSL_AD_BAD_RECORD_MAC;
                 SSLerr(SSL_F_SSL3_GET_RECORD,
                        SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
@@ -381,9 +389,9 @@ int ssl3_get_record(SSL *s)
         goto f_err;
     }
 #ifdef SSL_DEBUG
-    printf("dec %d\n", rr->length);
+    printf("dec %"OSSLzu"\n", rr->length);
     {
-        unsigned int z;
+        size_t z;
         for (z = 0; z < rr->length; z++)
             printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
     }
@@ -438,7 +446,7 @@ int ssl3_get_record(SSL *s)
             }
 
             i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ );
-            if (i < 0 || mac == NULL
+            if (i == 0 || mac == NULL
                 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
                 enc_err = -1;
             if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
@@ -525,6 +533,7 @@ int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
     if (rr->comp == NULL)
         return 0;
 
+    /* TODO(size_t): Convert this call */
     i = COMP_expand_block(ssl->expand, rr->comp,
                           SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (int)rr->length);
     if (i < 0)
@@ -541,6 +550,7 @@ int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
 #ifndef OPENSSL_NO_COMP
     int i;
 
+    /* TODO(size_t): Convert this call */
     i = COMP_compress_block(ssl->compress, wr->data,
                             SSL3_RT_MAX_COMPRESSED_LENGTH,
                             wr->input, (int)wr->length);
@@ -564,12 +574,13 @@ int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
  *   -1: if the record's padding is invalid or, if sending, an internal error
  *       occurred.
  */
-int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, unsigned int n_recs, int send)
+int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, size_t n_recs, int send)
 {
     SSL3_RECORD *rec;
     EVP_CIPHER_CTX *ds;
-    unsigned long l;
-    int bs, i, mac_size = 0;
+    size_t l, i;
+    size_t bs, mac_size = 0;
+    int imac_size;
     const EVP_CIPHER *enc;
 
     rec = inrecs;
@@ -597,12 +608,13 @@ int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, unsigned int n_recs, int send)
         rec->input = rec->data;
     } else {
         l = rec->length;
+        /* TODO(size_t): Convert this call */
         bs = EVP_CIPHER_CTX_block_size(ds);
 
         /* COMPRESS */
 
         if ((bs != 1) && send) {
-            i = bs - ((int)l % bs);
+            i = bs - (l % bs);
 
             /* we need to add 'i-1' padding bytes */
             l += i;
@@ -612,7 +624,7 @@ int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, unsigned int n_recs, int send)
              */
             memset(&rec->input[rec->length], 0, i);
             rec->length += i;
-            rec->input[l - 1] = (i - 1);
+            rec->input[l - 1] = (unsigned char)(i - 1);
         }
 
         if (!send) {
@@ -621,17 +633,24 @@ int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, unsigned int n_recs, int send)
             /* otherwise, rec->length >= bs */
         }
 
-        if (EVP_Cipher(ds, rec->data, rec->input, l) < 1)
+        /* TODO(size_t): Convert this call */
+        if (EVP_Cipher(ds, rec->data, rec->input, (unsigned int)l) < 1)
             return -1;
 
-        if (EVP_MD_CTX_md(s->read_hash) != NULL)
-            mac_size = EVP_MD_CTX_size(s->read_hash);
+        if (EVP_MD_CTX_md(s->read_hash) != NULL) {
+            /* TODO(size_t): convert me */
+            imac_size = EVP_MD_CTX_size(s->read_hash);
+            if (imac_size < 0)
+                return -1;
+            mac_size = (size_t)imac_size;
+        }
         if ((bs != 1) && !send)
             return ssl3_cbc_remove_padding(rec, bs, mac_size);
     }
     return (1);
 }
 
+#define MAX_PADDING 256
 /*-
  * tls1_enc encrypts/decrypts |n_recs| in |recs|.
  *
@@ -642,14 +661,16 @@ int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, unsigned int n_recs, int send)
  *   -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
  *       an internal error occurred.
  */
-int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int n_recs, int send)
+int tls1_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int send)
 {
     EVP_CIPHER_CTX *ds;
     size_t reclen[SSL_MAX_PIPELINES];
     unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
-    int bs, i, j, k, pad = 0, ret, mac_size = 0;
+    int i, pad = 0, ret, tmpr;
+    size_t bs, mac_size = 0, ctr, padnum, loop;
+    unsigned char padval;
+    int imac_size;
     const EVP_CIPHER *enc;
-    unsigned int ctr;
 
     if (send) {
         if (EVP_MD_CTX_md(s->write_hash)) {
@@ -746,8 +767,8 @@ int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int n_recs, int send)
                 buf[ctr][8] = recs[ctr].type;
                 buf[ctr][9] = (unsigned char)(s->version >> 8);
                 buf[ctr][10] = (unsigned char)(s->version);
-                buf[ctr][11] = recs[ctr].length >> 8;
-                buf[ctr][12] = recs[ctr].length & 0xff;
+                buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
+                buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
                 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
                                           EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
                 if (pad <= 0)
@@ -759,16 +780,18 @@ int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int n_recs, int send)
                 }
 
             } else if ((bs != 1) && send) {
-                i = bs - ((int)reclen[ctr] % bs);
+                padnum = bs - (reclen[ctr] % bs);
 
                 /* Add weird padding of upto 256 bytes */
 
-                /* we need to add 'i' padding bytes of value j */
-                j = i - 1;
-                for (k = (int)reclen[ctr]; k < (int)(reclen[ctr] + i); k++)
-                    recs[ctr].input[k] = j;
-                reclen[ctr] += i;
-                recs[ctr].length += i;
+                if (padnum > MAX_PADDING)
+                    return -1;
+                /* we need to add 'padnum' padding bytes of value padval */
+                padval = (unsigned char)(padnum - 1);
+                for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
+                    recs[ctr].input[loop] = padval;
+                reclen[ctr] += padnum;
+                recs[ctr].length += padnum;
             }
 
             if (!send) {
@@ -784,7 +807,7 @@ int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int n_recs, int send)
                 data[ctr] = recs[ctr].data;
             }
             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
-                                    n_recs, data) <= 0) {
+                                    (int)n_recs, data) <= 0) {
                 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
             }
             /* Set the input buffers */
@@ -792,19 +815,21 @@ int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int n_recs, int send)
                 data[ctr] = recs[ctr].input;
             }
             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
-                                    n_recs, data) <= 0
+                                    (int)n_recs, data) <= 0
                 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
-                                       n_recs, reclen) <= 0) {
+                                       (int)n_recs, reclen) <= 0) {
                 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
                 return -1;
             }
         }
 
-        i = EVP_Cipher(ds, recs[0].data, recs[0].input, reclen[0]);
+        /* TODO(size_t): Convert this call */
+        tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
+                          (unsigned int)reclen[0]);
         if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
              & EVP_CIPH_FLAG_CUSTOM_CIPHER)
-            ? (i < 0)
-            : (i == 0))
+            ? (tmpr < 0)
+            : (tmpr == 0))
             return -1;          /* AEAD can fail to verify MAC */
         if (send == 0) {
             if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
@@ -823,8 +848,12 @@ int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int n_recs, int send)
         }
 
         ret = 1;
-        if (!SSL_USE_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)
-            mac_size = EVP_MD_CTX_size(s->read_hash);
+        if (!SSL_USE_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL) {
+            imac_size = EVP_MD_CTX_size(s->read_hash);
+            if (imac_size < 0)
+                return -1;
+            mac_size = (size_t)imac_size;
+        }
         if ((bs != 1) && !send) {
             int tmpret;
             for (ctr = 0; ctr < n_recs; ctr++) {
@@ -855,7 +884,7 @@ int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
     const EVP_MD_CTX *hash;
     unsigned char *p, rec_char;
     size_t md_size;
-    int npad;
+    size_t npad;
     int t;
 
     if (send) {
@@ -870,7 +899,7 @@ int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
 
     t = EVP_MD_CTX_size(hash);
     if (t < 0)
-        return -1;
+        return 0;
     md_size = t;
     npad = (48 / md_size) * md_size;
 
@@ -892,7 +921,7 @@ int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
          * total size.
          */
         unsigned char header[75];
-        unsigned j = 0;
+        size_t j = 0;
         memcpy(header + j, mac_sec, md_size);
         j += md_size;
         memcpy(header + j, ssl3_pad_1, npad);
@@ -900,8 +929,8 @@ int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
         memcpy(header + j, seq, 8);
         j += 8;
         header[j++] = rec->type;
-        header[j++] = rec->length >> 8;
-        header[j++] = rec->length & 0xff;
+        header[j++] = (unsigned char)(rec->length >> 8);
+        header[j++] = (unsigned char)(rec->length & 0xff);
 
         /* Final param == is SSLv3 */
         if (ssl3_cbc_digest_record(hash,
@@ -909,14 +938,14 @@ int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
                                    header, rec->input,
                                    rec->length + md_size, rec->orig_len,
                                    mac_sec, md_size, 1) <= 0)
-            return -1;
+            return 0;
     } else {
         unsigned int md_size_u;
         /* Chop the digest off the end :-) */
         EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
 
         if (md_ctx == NULL)
-            return -1;
+            return 0;
 
         rec_char = rec->type;
         p = md;
@@ -935,15 +964,14 @@ int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
             || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
             || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
             EVP_MD_CTX_reset(md_ctx);
-            return -1;
+            return 0;
         }
-        md_size = md_size_u;
 
         EVP_MD_CTX_free(md_ctx);
     }
 
     ssl3_record_sequence_update(seq);
-    return (md_size);
+    return 1;
 }
 
 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
@@ -976,7 +1004,7 @@ int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
     } else {
         hmac = EVP_MD_CTX_new();
         if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash))
-            return -1;
+            return 0;
         mac_ctx = hmac;
     }
 
@@ -994,8 +1022,8 @@ int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
     header[8] = rec->type;
     header[9] = (unsigned char)(ssl->version >> 8);
     header[10] = (unsigned char)(ssl->version);
-    header[11] = (rec->length) >> 8;
-    header[12] = (rec->length) & 0xff;
+    header[11] = (unsigned char)(rec->length >> 8);
+    header[12] = (unsigned char)(rec->length & 0xff);
 
     if (!send && !SSL_USE_ETM(ssl) &&
         EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
@@ -1016,18 +1044,19 @@ int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
             return -1;
         }
     } else {
+        /* TODO(size_t): Convert these calls */
         if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
             || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
             || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
             EVP_MD_CTX_free(hmac);
-            return -1;
+            return 0;
         }
         if (!send && !SSL_USE_ETM(ssl) && FIPS_mode())
             if (!tls_fips_digest_extra(ssl->enc_read_ctx,
                                        mac_ctx, rec->input,
                                        rec->length, rec->orig_len)) {
                 EVP_MD_CTX_free(hmac);
-                return -1;
+                return 0;
             }
     }
 
@@ -1043,7 +1072,7 @@ int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
     }
     fprintf(stderr, "rec=");
     {
-        unsigned int z;
+        size_t z;
         for (z = 0; z < rec->length; z++)
             fprintf(stderr, "%02X ", rec->data[z]);
         fprintf(stderr, "\n");
@@ -1065,7 +1094,7 @@ int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
         fprintf(stderr, "\n");
     }
 #endif
-    return (md_size);
+    return 1;
 }
 
 /*-
@@ -1079,10 +1108,11 @@ int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
  *  -1: otherwise.
  */
 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
-                            unsigned block_size, unsigned mac_size)
+                            size_t block_size, size_t mac_size)
 {
-    unsigned padding_length, good;
-    const unsigned overhead = 1 /* padding length byte */  + mac_size;
+    size_t padding_length;
+    size_t good;
+    const size_t overhead = 1 /* padding length byte */  + mac_size;
 
     /*
      * These lengths are all public so we can test them in non-constant time.
@@ -1091,11 +1121,11 @@ int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
         return 0;
 
     padding_length = rec->data[rec->length - 1];
-    good = constant_time_ge(rec->length, padding_length + overhead);
+    good = constant_time_ge_s(rec->length, padding_length + overhead);
     /* SSLv3 requires that the padding is minimal. */
-    good &= constant_time_ge(block_size, padding_length + 1);
+    good &= constant_time_ge_s(block_size, padding_length + 1);
     rec->length -= good & (padding_length + 1);
-    return constant_time_select_int(good, 1, -1);
+    return constant_time_select_int_s(good, 1, -1);
 }
 
 /*-
@@ -1113,10 +1143,11 @@ int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
  */
 int tls1_cbc_remove_padding(const SSL *s,
                             SSL3_RECORD *rec,
-                            unsigned block_size, unsigned mac_size)
+                            size_t block_size, size_t mac_size)
 {
-    unsigned padding_length, good, to_check, i;
-    const unsigned overhead = 1 /* padding length byte */  + mac_size;
+    size_t good;
+    size_t padding_length, to_check, i;
+    const size_t overhead = 1 /* padding length byte */  + mac_size;
     /* Check if version requires explicit IV */
     if (SSL_USE_EXPLICIT_IV(s)) {
         /*
@@ -1142,7 +1173,7 @@ int tls1_cbc_remove_padding(const SSL *s,
         return 1;
     }
 
-    good = constant_time_ge(rec->length, overhead + padding_length);
+    good = constant_time_ge_s(rec->length, overhead + padding_length);
     /*
      * The padding consists of a length byte at the end of the record and
      * then that many bytes of padding, all with the same value as the length
@@ -1157,7 +1188,7 @@ int tls1_cbc_remove_padding(const SSL *s,
         to_check = rec->length;
 
     for (i = 0; i < to_check; i++) {
-        unsigned char mask = constant_time_ge_8(padding_length, i);
+        unsigned char mask = constant_time_ge_8_s(padding_length, i);
         unsigned char b = rec->data[rec->length - 1 - i];
         /*
          * The final |padding_length+1| bytes should all have the value
@@ -1170,10 +1201,10 @@ int tls1_cbc_remove_padding(const SSL *s,
      * If any of the final |padding_length+1| bytes had the wrong value, one
      * or more of the lower eight bits of |good| will be cleared.
      */
-    good = constant_time_eq(0xff, good & 0xff);
+    good = constant_time_eq_s(0xff, good & 0xff);
     rec->length -= good & (padding_length + 1);
 
-    return constant_time_select_int(good, 1, -1);
+    return constant_time_select_int_s(good, 1, -1);
 }
 
 /*-
@@ -1197,7 +1228,7 @@ int tls1_cbc_remove_padding(const SSL *s,
 #define CBC_MAC_ROTATE_IN_PLACE
 
 void ssl3_cbc_copy_mac(unsigned char *out,
-                       const SSL3_RECORD *rec, unsigned md_size)
+                       const SSL3_RECORD *rec, size_t md_size)
 {
 #if defined(CBC_MAC_ROTATE_IN_PLACE)
     unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
@@ -1209,16 +1240,16 @@ void ssl3_cbc_copy_mac(unsigned char *out,
     /*
      * mac_end is the index of |rec->data| just after the end of the MAC.
      */
-    unsigned mac_end = rec->length;
-    unsigned mac_start = mac_end - md_size;
+    size_t mac_end = rec->length;
+    size_t mac_start = mac_end - md_size;
     /*
      * scan_start contains the number of bytes that we can ignore because the
      * MAC's position can only vary by 255 bytes.
      */
-    unsigned scan_start = 0;
-    unsigned i, j;
-    unsigned div_spoiler;
-    unsigned rotate_offset;
+    size_t scan_start = 0;
+    size_t i, j;
+    size_t div_spoiler;
+    size_t rotate_offset;
 
     OPENSSL_assert(rec->orig_len >= md_size);
     OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
@@ -1244,11 +1275,11 @@ void ssl3_cbc_copy_mac(unsigned char *out,
 
     memset(rotated_mac, 0, md_size);
     for (i = scan_start, j = 0; i < rec->orig_len; i++) {
-        unsigned char mac_started = constant_time_ge_8(i, mac_start);
-        unsigned char mac_ended = constant_time_ge_8(i, mac_end);
+        unsigned char mac_started = constant_time_ge_8_s(i, mac_start);
+        unsigned char mac_ended = constant_time_ge_8_s(i, mac_end);
         unsigned char b = rec->data[i];
         rotated_mac[j++] |= b & mac_started & ~mac_ended;
-        j &= constant_time_lt(j, md_size);
+        j &= constant_time_lt_s(j, md_size);
     }
 
     /* Now rotate the MAC */
@@ -1258,17 +1289,17 @@ void ssl3_cbc_copy_mac(unsigned char *out,
         /* in case cache-line is 32 bytes, touch second line */
         ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
         out[j++] = rotated_mac[rotate_offset++];
-        rotate_offset &= constant_time_lt(rotate_offset, md_size);
+        rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
     }
 #else
     memset(out, 0, md_size);
     rotate_offset = md_size - rotate_offset;
-    rotate_offset &= constant_time_lt(rotate_offset, md_size);
+    rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
     for (i = 0; i < md_size; i++) {
         for (j = 0; j < md_size; j++)
-            out[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset);
+            out[j] |= rotated_mac[i] & constant_time_eq_8_s(j, rotate_offset);
         rotate_offset++;
-        rotate_offset &= constant_time_lt(rotate_offset, md_size);
+        rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
     }
 #endif
 }
@@ -1279,7 +1310,8 @@ int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
     int enc_err;
     SSL_SESSION *sess;
     SSL3_RECORD *rr;
-    unsigned int mac_size;
+    int imac_size;
+    size_t mac_size;
     unsigned char md[EVP_MAX_MD_SIZE];
 
     rr = RECORD_LAYER_get_rrec(&s->rlayer);
@@ -1326,7 +1358,7 @@ int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
         rr->length -= mac_size;
         mac = rr->data + rr->length;
         i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
-        if (i < 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
+        if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
             al = SSL_AD_BAD_RECORD_MAC;
             SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
                    SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
@@ -1348,9 +1380,9 @@ int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
         goto err;
     }
 #ifdef SSL_DEBUG
-    printf("dec %d\n", rr->length);
+    printf("dec %ld\n", rr->length);
     {
-        unsigned int z;
+        size_t z;
         for (z = 0; z < rr->length; z++)
             printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
     }
@@ -1363,7 +1395,15 @@ int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
         /* s->read_hash != NULL => mac_size != -1 */
         unsigned char *mac = NULL;
         unsigned char mac_tmp[EVP_MAX_MD_SIZE];
-        mac_size = EVP_MD_CTX_size(s->read_hash);
+
+        /* TODO(size_t): Convert this to do size_t properly */
+        imac_size = EVP_MD_CTX_size(s->read_hash);
+        if (imac_size < 0) {
+            al = SSL_AD_INTERNAL_ERROR;
+            SSLerr(SSL_F_DTLS1_PROCESS_RECORD, ERR_LIB_EVP);
+            goto f_err;
+        }
+        mac_size = (size_t)imac_size;
         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
 
         /*
@@ -1402,8 +1442,8 @@ int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
         }
 
         i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
-        if (i < 0 || mac == NULL
-            || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
+        if (i == 0 || mac == NULL
+            || CRYPTO_memcmp(md, mac, mac_size) != 0)
             enc_err = -1;
         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
             enc_err = -1;
@@ -1482,7 +1522,8 @@ int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
 int dtls1_get_record(SSL *s)
 {
     int ssl_major, ssl_minor;
-    int i, n;
+    int rret;
+    size_t more, n;
     SSL3_RECORD *rr;
     unsigned char *p = NULL;
     unsigned short version;
@@ -1508,11 +1549,11 @@ int dtls1_get_record(SSL *s)
     /* check if we have the header */
     if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
         (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
-        n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
-                        SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1);
+        rret = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
+                           SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1, &n);
         /* read timeout is handled by dtls1_read_bytes */
-        if (n <= 0)
-            return (n);         /* error or non-blocking */
+        if (rret <= 0)
+            return rret;         /* error or non-blocking */
 
         /* this packet contained a partial record, dump it */
         if (RECORD_LAYER_get_packet_length(&s->rlayer) !=
@@ -1575,10 +1616,10 @@ int dtls1_get_record(SSL *s)
     if (rr->length >
         RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
         /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
-        i = rr->length;
-        n = ssl3_read_n(s, i, i, 1, 1);
+        more = rr->length;
+        rret = ssl3_read_n(s, more, more, 1, 1, &n);
         /* this packet contained a partial record, dump it */
-        if (n != i) {
+        if (rret <= 0 || n != more) {
             rr->length = 0;
             RECORD_LAYER_reset_packet_length(&s->rlayer);
             goto again;
diff --git a/ssl/s3_cbc.c b/ssl/s3_cbc.c
index 9a228f7..3a75745 100644
--- a/ssl/s3_cbc.c
+++ b/ssl/s3_cbc.c
@@ -134,7 +134,7 @@ int ssl3_cbc_digest_record(const EVP_MD_CTX *ctx,
                            size_t data_plus_mac_size,
                            size_t data_plus_mac_plus_padding_size,
                            const unsigned char *mac_secret,
-                           unsigned mac_secret_length, char is_sslv3)
+                           size_t mac_secret_length, char is_sslv3)
 {
     union {
         double align;
@@ -142,23 +142,24 @@ int ssl3_cbc_digest_record(const EVP_MD_CTX *ctx,
     } md_state;
     void (*md_final_raw) (void *ctx, unsigned char *md_out);
     void (*md_transform) (void *ctx, const unsigned char *block);
-    unsigned md_size, md_block_size = 64;
-    unsigned sslv3_pad_length = 40, header_length, variance_blocks,
+    size_t md_size, md_block_size = 64;
+    size_t sslv3_pad_length = 40, header_length, variance_blocks,
         len, max_mac_bytes, num_blocks,
         num_starting_blocks, k, mac_end_offset, c, index_a, index_b;
-    unsigned int bits;          /* at most 18 bits */
+    size_t bits;          /* at most 18 bits */
     unsigned char length_bytes[MAX_HASH_BIT_COUNT_BYTES];
     /* hmac_pad is the masked HMAC key. */
     unsigned char hmac_pad[MAX_HASH_BLOCK_SIZE];
     unsigned char first_block[MAX_HASH_BLOCK_SIZE];
     unsigned char mac_out[EVP_MAX_MD_SIZE];
-    unsigned i, j, md_out_size_u;
+    size_t i, j;
+    unsigned md_out_size_u;
     EVP_MD_CTX *md_ctx = NULL;
     /*
      * mdLengthSize is the number of bytes in the length field that
      * terminates * the hash.
      */
-    unsigned md_length_size = 8;
+    size_t md_length_size = 8;
     char length_is_big_endian = 1;
     int ret;
 
@@ -356,7 +357,7 @@ int ssl3_cbc_digest_record(const EVP_MD_CTX *ctx,
 
     if (k > 0) {
         if (is_sslv3) {
-            unsigned overhang;
+            size_t overhang;
 
             /*
              * The SSLv3 header is larger than a single block. overhang is
@@ -399,8 +400,8 @@ int ssl3_cbc_digest_record(const EVP_MD_CTX *ctx,
     for (i = num_starting_blocks; i <= num_starting_blocks + variance_blocks;
          i++) {
         unsigned char block[MAX_HASH_BLOCK_SIZE];
-        unsigned char is_block_a = constant_time_eq_8(i, index_a);
-        unsigned char is_block_b = constant_time_eq_8(i, index_b);
+        unsigned char is_block_a = constant_time_eq_8_s(i, index_a);
+        unsigned char is_block_b = constant_time_eq_8_s(i, index_b);
         for (j = 0; j < md_block_size; j++) {
             unsigned char b = 0, is_past_c, is_past_cp1;
             if (k < header_length)
@@ -409,8 +410,8 @@ int ssl3_cbc_digest_record(const EVP_MD_CTX *ctx,
                 b = data[k - header_length];
             k++;
 
-            is_past_c = is_block_a & constant_time_ge_8(j, c);
-            is_past_cp1 = is_block_a & constant_time_ge_8(j, c + 1);
+            is_past_c = is_block_a & constant_time_ge_8_s(j, c);
+            is_past_cp1 = is_block_a & constant_time_ge_8_s(j, c + 1);
             /*
              * If this is the block containing the end of the application
              * data, and we are at the offset for the 0x80 value, then
@@ -471,6 +472,7 @@ int ssl3_cbc_digest_record(const EVP_MD_CTX *ctx,
             || EVP_DigestUpdate(md_ctx, mac_out, md_size) <= 0)
             goto err;
     }
+    /* TODO(size_t): Convert me */
     ret = EVP_DigestFinal(md_ctx, md_out, &md_out_size_u);
     if (ret && md_out_size)
         *md_out_size = md_out_size_u;
diff --git a/ssl/s3_enc.c b/ssl/s3_enc.c
index 56bd34a..ba71bc1 100644
--- a/ssl/s3_enc.c
+++ b/ssl/s3_enc.c
@@ -113,7 +113,8 @@ int ssl3_change_cipher_state(SSL *s, int which)
     COMP_METHOD *comp;
 #endif
     const EVP_MD *m;
-    int n, i, j, k, cl;
+    int mdi;
+    size_t n, i, j, k, cl;
     int reuse_dd = 0;
 
     c = s->s3->tmp.new_sym_enc;
@@ -194,9 +195,10 @@ int ssl3_change_cipher_state(SSL *s, int which)
         EVP_CIPHER_CTX_reset(dd);
 
     p = s->s3->tmp.key_block;
-    i = EVP_MD_size(m);
-    if (i < 0)
+    mdi = EVP_MD_size(m);
+    if (mdi < 0)
         goto err2;
+    i = mdi;
     cl = EVP_CIPHER_key_length(c);
     j = cl;
     k = EVP_CIPHER_iv_length(c);
@@ -356,13 +358,18 @@ void ssl3_free_digest_list(SSL *s)
     s->s3->handshake_dgst = NULL;
 }
 
-int ssl3_finish_mac(SSL *s, const unsigned char *buf, int len)
+int ssl3_finish_mac(SSL *s, const unsigned char *buf, size_t len)
 {
-    if (s->s3->handshake_dgst == NULL)
+    if (s->s3->handshake_dgst == NULL) {
+        int ret;
         /* Note: this writes to a memory BIO so a failure is a fatal error */
-        return BIO_write(s->s3->handshake_buffer, (void *)buf, len) == len;
-    else
+        if (len > INT_MAX)
+            return 0;
+        ret = BIO_write(s->s3->handshake_buffer, (void *)buf, (int)len);
+        return ret > 0 && ret == (int)len;
+    } else {
         return EVP_DigestUpdate(s->s3->handshake_dgst, buf, len);
+    }
 }
 
 int ssl3_digest_cached_records(SSL *s, int keep)
@@ -400,7 +407,8 @@ int ssl3_digest_cached_records(SSL *s, int keep)
     return 1;
 }
 
-int ssl3_final_finish_mac(SSL *s, const char *sender, int len, unsigned char *p)
+size_t ssl3_final_finish_mac(SSL *s, const char *sender, size_t len,
+                             unsigned char *p)
 {
     int ret;
     EVP_MD_CTX *ctx = NULL;
@@ -431,7 +439,7 @@ int ssl3_final_finish_mac(SSL *s, const char *sender, int len, unsigned char *p)
 
     if ((sender != NULL && EVP_DigestUpdate(ctx, sender, len) <= 0)
         || EVP_MD_CTX_ctrl(ctx, EVP_CTRL_SSL3_MASTER_SECRET,
-                           s->session->master_key_length,
+                           (int)s->session->master_key_length,
                            s->session->master_key) <= 0
         || EVP_DigestFinal_ex(ctx, p, NULL) <= 0) {
         SSLerr(SSL_F_SSL3_FINAL_FINISH_MAC, ERR_R_INTERNAL_ERROR);
@@ -444,7 +452,7 @@ int ssl3_final_finish_mac(SSL *s, const char *sender, int len, unsigned char *p)
 }
 
 int ssl3_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
-                                int len)
+                                size_t len, size_t *secret_size)
 {
     static const unsigned char *salt[3] = {
 #ifndef CHARSET_EBCDIC
@@ -459,11 +467,12 @@ int ssl3_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
     };
     unsigned char buf[EVP_MAX_MD_SIZE];
     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
-    int i, ret = 0;
+    int i, ret = 1;
     unsigned int n;
 #ifdef OPENSSL_SSL_TRACE_CRYPTO
     unsigned char *tmpout = out;
 #endif
+    size_t ret_secret_size = 0;
 
     if (ctx == NULL) {
         SSLerr(SSL_F_SSL3_GENERATE_MASTER_SECRET, ERR_R_MALLOC_FAILURE);
@@ -478,6 +487,7 @@ int ssl3_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
                                 SSL3_RANDOM_SIZE) <= 0
             || EVP_DigestUpdate(ctx, &(s->s3->server_random[0]),
                                 SSL3_RANDOM_SIZE) <= 0
+               /* TODO(size_t) : convert me */
             || EVP_DigestFinal_ex(ctx, buf, &n) <= 0
             || EVP_DigestInit_ex(ctx, s->ctx->md5, NULL) <= 0
             || EVP_DigestUpdate(ctx, p, len) <= 0
@@ -488,12 +498,12 @@ int ssl3_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
             break;
         }
         out += n;
-        ret += n;
+        ret_secret_size += n;
     }
     EVP_MD_CTX_free(ctx);
 
 #ifdef OPENSSL_SSL_TRACE_CRYPTO
-    if (ret > 0 && s->msg_callback) {
+    if (ret && s->msg_callback) {
         s->msg_callback(2, s->version, TLS1_RT_CRYPTO_PREMASTER,
                         p, len, s, s->msg_callback_arg);
         s->msg_callback(2, s->version, TLS1_RT_CRYPTO_CLIENT_RANDOM,
@@ -508,7 +518,9 @@ int ssl3_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
     }
 #endif
     OPENSSL_cleanse(buf, sizeof(buf));
-    return (ret);
+    if (ret)
+        *secret_size = ret_secret_size;
+    return ret;
 }
 
 int ssl3_alert_code(int code)
diff --git a/ssl/s3_lib.c b/ssl/s3_lib.c
index ffdb454..90c1c66 100644
--- a/ssl/s3_lib.c
+++ b/ssl/s3_lib.c
@@ -2756,7 +2756,6 @@ const SSL3_ENC_METHOD SSLv3_enc_data = {
     ssl3_generate_master_secret,
     ssl3_change_cipher_state,
     ssl3_final_finish_mac,
-    MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH,
     SSL3_MD_CLIENT_FINISHED_CONST, 4,
     SSL3_MD_SERVER_FINISHED_CONST, 4,
     ssl3_alert_code,
@@ -2764,7 +2763,6 @@ const SSL3_ENC_METHOD SSLv3_enc_data = {
              size_t, const unsigned char *, size_t,
              int use_context))ssl_undefined_function,
     0,
-    SSL3_HM_HEADER_LENGTH,
     ssl3_set_handshake_header,
     tls_close_construct_packet,
     ssl3_handshake_write
@@ -3037,7 +3035,10 @@ long ssl3_ctrl(SSL *s, int cmd, long larg, void *parg)
 
     case SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP:
         *(unsigned char **)parg = s->tlsext_ocsp_resp;
-        return s->tlsext_ocsp_resplen;
+        if (s->tlsext_ocsp_resplen == 0
+                || s->tlsext_ocsp_resplen > LONG_MAX)
+            return -1;
+        return (long)s->tlsext_ocsp_resplen;
 
     case SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP:
         OPENSSL_free(s->tlsext_ocsp_resp);
@@ -3812,12 +3813,13 @@ int ssl3_shutdown(SSL *s)
             return (ret);
         }
     } else if (!(s->shutdown & SSL_RECEIVED_SHUTDOWN)) {
+        size_t readbytes;
         /*
          * If we are waiting for a close from our peer, we are closed
          */
-        s->method->ssl_read_bytes(s, 0, NULL, NULL, 0, 0);
+        s->method->ssl_read_bytes(s, 0, NULL, NULL, 0, 0, &readbytes);
         if (!(s->shutdown & SSL_RECEIVED_SHUTDOWN)) {
-            return (-1);        /* return WANT_READ */
+            return -1;        /* return WANT_READ */
         }
     }
 
@@ -3828,16 +3830,18 @@ int ssl3_shutdown(SSL *s)
         return (0);
 }
 
-int ssl3_write(SSL *s, const void *buf, int len)
+int ssl3_write(SSL *s, const void *buf, size_t len, size_t *written)
 {
     clear_sys_error();
     if (s->s3->renegotiate)
         ssl3_renegotiate_check(s);
 
-    return s->method->ssl_write_bytes(s, SSL3_RT_APPLICATION_DATA, buf, len);
+    return s->method->ssl_write_bytes(s, SSL3_RT_APPLICATION_DATA, buf, len,
+                                      written);
 }
 
-static int ssl3_read_internal(SSL *s, void *buf, int len, int peek)
+static int ssl3_read_internal(SSL *s, void *buf, size_t len, int peek,
+                              size_t *readbytes)
 {
     int ret;
 
@@ -3847,7 +3851,7 @@ static int ssl3_read_internal(SSL *s, void *buf, int len, int peek)
     s->s3->in_read_app_data = 1;
     ret =
         s->method->ssl_read_bytes(s, SSL3_RT_APPLICATION_DATA, NULL, buf, len,
-                                  peek);
+                                  peek, readbytes);
     if ((ret == -1) && (s->s3->in_read_app_data == 2)) {
         /*
          * ssl3_read_bytes decided to call s->handshake_func, which called
@@ -3859,22 +3863,22 @@ static int ssl3_read_internal(SSL *s, void *buf, int len, int peek)
         ossl_statem_set_in_handshake(s, 1);
         ret =
             s->method->ssl_read_bytes(s, SSL3_RT_APPLICATION_DATA, NULL, buf,
-                                      len, peek);
+                                      len, peek, readbytes);
         ossl_statem_set_in_handshake(s, 0);
     } else
         s->s3->in_read_app_data = 0;
 
-    return (ret);
+    return ret;
 }
 
-int ssl3_read(SSL *s, void *buf, int len)
+int ssl3_read(SSL *s, void *buf, size_t len, size_t *readbytes)
 {
-    return ssl3_read_internal(s, buf, len, 0);
+    return ssl3_read_internal(s, buf, len, 0, readbytes);
 }
 
-int ssl3_peek(SSL *s, void *buf, int len)
+int ssl3_peek(SSL *s, void *buf, size_t len, size_t *readbytes)
 {
-    return ssl3_read_internal(s, buf, len, 1);
+    return ssl3_read_internal(s, buf, len, 1, readbytes);
 }
 
 int ssl3_renegotiate(SSL *s)
@@ -3938,7 +3942,7 @@ long ssl_get_algorithm2(SSL *s)
  * Fill a ClientRandom or ServerRandom field of length len. Returns <= 0 on
  * failure, 1 on success.
  */
-int ssl_fill_hello_random(SSL *s, int server, unsigned char *result, int len)
+int ssl_fill_hello_random(SSL *s, int server, unsigned char *result, size_t len)
 {
     int send_time = 0;
 
@@ -3952,15 +3956,18 @@ int ssl_fill_hello_random(SSL *s, int server, unsigned char *result, int len)
         unsigned long Time = (unsigned long)time(NULL);
         unsigned char *p = result;
         l2n(Time, p);
-        return RAND_bytes(p, len - 4);
+        /* TODO(size_t): Convert this */
+        return RAND_bytes(p, (int)(len - 4));
     } else
-        return RAND_bytes(result, len);
+        return RAND_bytes(result, (int)len);
 }
 
 int ssl_generate_master_secret(SSL *s, unsigned char *pms, size_t pmslen,
                                int free_pms)
 {
     unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
+    int ret = 0;
+
     if (alg_k & SSL_PSK) {
 #ifndef OPENSSL_NO_PSK
         unsigned char *pskpms, *t;
@@ -3975,10 +3982,8 @@ int ssl_generate_master_secret(SSL *s, unsigned char *pms, size_t pmslen,
 
         pskpmslen = 4 + pmslen + psklen;
         pskpms = OPENSSL_malloc(pskpmslen);
-        if (pskpms == NULL) {
-            s->session->master_key_length = 0;
+        if (pskpms == NULL)
             goto err;
-        }
         t = pskpms;
         s2n(pmslen, t);
         if (alg_k & SSL_kPSK)
@@ -3991,23 +3996,23 @@ int ssl_generate_master_secret(SSL *s, unsigned char *pms, size_t pmslen,
 
         OPENSSL_clear_free(s->s3->tmp.psk, psklen);
         s->s3->tmp.psk = NULL;
-        s->session->master_key_length =
-            s->method->ssl3_enc->generate_master_secret(s,
-                                                        s->session->master_key,
-                                                        pskpms, pskpmslen);
+        if (!s->method->ssl3_enc->generate_master_secret(s,
+                    s->session->master_key,pskpms, pskpmslen,
+                    &s->session->master_key_length))
+            goto err;
         OPENSSL_clear_free(pskpms, pskpmslen);
 #else
         /* Should never happen */
-        s->session->master_key_length = 0;
         goto err;
 #endif
     } else {
-        s->session->master_key_length =
-            s->method->ssl3_enc->generate_master_secret(s,
-                                                        s->session->master_key,
-                                                        pms, pmslen);
+        if (!s->method->ssl3_enc->generate_master_secret(s,
+                s->session->master_key, pms, pmslen,
+                &s->session->master_key_length))
+            goto err;
     }
 
+    ret = 1;
  err:
     if (pms) {
         if (free_pms)
@@ -4017,7 +4022,7 @@ int ssl_generate_master_secret(SSL *s, unsigned char *pms, size_t pmslen,
     }
     if (s->server == 0)
         s->s3->tmp.pms = NULL;
-    return s->session->master_key_length >= 0;
+    return ret;
 }
 
 /* Generate a private key from parameters */
diff --git a/ssl/s3_msg.c b/ssl/s3_msg.c
index 82513d2..743a02b 100644
--- a/ssl/s3_msg.c
+++ b/ssl/s3_msg.c
@@ -13,8 +13,9 @@
 int ssl3_do_change_cipher_spec(SSL *s)
 {
     int i;
+    size_t finish_md_len;
     const char *sender;
-    int slen;
+    size_t slen;
 
     if (s->server)
         i = SSL3_CHANGE_CIPHER_SERVER_READ;
@@ -48,14 +49,13 @@ int ssl3_do_change_cipher_spec(SSL *s)
         slen = s->method->ssl3_enc->client_finished_label_len;
     }
 
-    i = s->method->ssl3_enc->final_finish_mac(s,
-                                              sender, slen,
-                                              s->s3->tmp.peer_finish_md);
-    if (i == 0) {
+    finish_md_len = s->method->ssl3_enc->final_finish_mac(s, sender, slen,
+                                            s->s3->tmp.peer_finish_md);
+    if (finish_md_len == 0) {
         SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
         return 0;
     }
-    s->s3->tmp.peer_finish_md_len = i;
+    s->s3->tmp.peer_finish_md_len = finish_md_len;
 
     return (1);
 }
@@ -90,12 +90,14 @@ int ssl3_send_alert(SSL *s, int level, int desc)
 int ssl3_dispatch_alert(SSL *s)
 {
     int i, j;
-    unsigned int alertlen;
+    size_t alertlen;
     void (*cb) (const SSL *ssl, int type, int val) = NULL;
+    size_t written;
 
     s->s3->alert_dispatch = 0;
     alertlen = 2;
-    i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], &alertlen, 1, 0);
+    i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], &alertlen, 1, 0,
+                      &written);
     if (i <= 0) {
         s->s3->alert_dispatch = 1;
     } else {
@@ -121,5 +123,5 @@ int ssl3_dispatch_alert(SSL *s)
             cb(s, SSL_CB_WRITE_ALERT, j);
         }
     }
-    return (i);
+    return i;
 }
diff --git a/ssl/ssl_asn1.c b/ssl/ssl_asn1.c
index aa6e3e6..fd13f90 100644
--- a/ssl/ssl_asn1.c
+++ b/ssl/ssl_asn1.c
@@ -102,7 +102,7 @@ static void ssl_session_oinit(ASN1_OCTET_STRING **dest, ASN1_OCTET_STRING *os,
                               unsigned char *data, size_t len)
 {
     os->data = data;
-    os->length = len;
+    os->length = (int)len;
     os->flags = 0;
     *dest = os;
 }
@@ -223,14 +223,14 @@ static int ssl_session_strndup(char **pdst, ASN1_OCTET_STRING *src)
 
 /* Copy an OCTET STRING, return error if it exceeds maximum length */
 
-static int ssl_session_memcpy(unsigned char *dst, unsigned int *pdstlen,
-                              ASN1_OCTET_STRING *src, int maxlen)
+static int ssl_session_memcpy(unsigned char *dst, size_t *pdstlen,
+                              ASN1_OCTET_STRING *src, size_t maxlen)
 {
     if (src == NULL) {
         *pdstlen = 0;
         return 1;
     }
-    if (src->length > maxlen)
+    if (src->length < 0 || src->length > (int)maxlen)
         return 0;
     memcpy(dst, src->data, src->length);
     *pdstlen = src->length;
@@ -241,7 +241,7 @@ SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a, const unsigned char **pp,
                              long length)
 {
     long id;
-    unsigned int tmpl;
+    size_t tmpl;
     const unsigned char *p = *pp;
     SSL_SESSION_ASN1 *as = NULL;
     SSL_SESSION *ret = NULL;
diff --git a/ssl/ssl_ciph.c b/ssl/ssl_ciph.c
index acc1840..9d259c1 100644
--- a/ssl/ssl_ciph.c
+++ b/ssl/ssl_ciph.c
@@ -175,7 +175,7 @@ static int ssl_cipher_info_find(const ssl_cipher_table * table,
     size_t i;
     for (i = 0; i < table_cnt; i++, table++) {
         if (table->mask == mask)
-            return i;
+            return (int)i;
     }
     return -1;
 }
@@ -197,7 +197,7 @@ static int ssl_mac_pkey_id[SSL_MD_NUM_IDX] = {
     EVP_PKEY_HMAC,
 };
 
-static int ssl_mac_secret_size[SSL_MD_NUM_IDX];
+static size_t ssl_mac_secret_size[SSL_MD_NUM_IDX];
 
 #define CIPHER_ADD      1
 #define CIPHER_KILL     2
@@ -399,8 +399,9 @@ void ssl_load_ciphers(void)
         if (md == NULL) {
             disabled_mac_mask |= t->mask;
         } else {
-            ssl_mac_secret_size[i] = EVP_MD_size(md);
-            OPENSSL_assert(ssl_mac_secret_size[i] >= 0);
+            int tmpsize = EVP_MD_size(md);
+            OPENSSL_assert(tmpsize >= 0);
+            ssl_mac_secret_size[i] = tmpsize;
         }
     }
     /* Make sure we can access MD5 and SHA1 */
@@ -502,7 +503,7 @@ static int load_builtin_compressions(void)
 
 int ssl_cipher_get_evp(const SSL_SESSION *s, const EVP_CIPHER **enc,
                        const EVP_MD **md, int *mac_pkey_type,
-                       int *mac_secret_size, SSL_COMP **comp, int use_etm)
+                       size_t *mac_secret_size, SSL_COMP **comp, int use_etm)
 {
     int i;
     const SSL_CIPHER *c;
diff --git a/ssl/ssl_err.c b/ssl/ssl_err.c
index c1a886a..5c2e961 100644
--- a/ssl/ssl_err.c
+++ b/ssl/ssl_err.c
@@ -181,7 +181,9 @@ static ERR_STRING_DATA SSL_str_functs[] = {
     {ERR_FUNC(SSL_F_SSL_PARSE_SERVERHELLO_USE_SRTP_EXT),
      "ssl_parse_serverhello_use_srtp_ext"},
     {ERR_FUNC(SSL_F_SSL_PEEK), "SSL_peek"},
+    {ERR_FUNC(SSL_F_SSL_PEEK_EX), "SSL_peek_ex"},
     {ERR_FUNC(SSL_F_SSL_READ), "SSL_read"},
+    {ERR_FUNC(SSL_F_SSL_READ_EX), "SSL_read_ex"},
     {ERR_FUNC(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT),
      "ssl_scan_clienthello_tlsext"},
     {ERR_FUNC(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT),
@@ -227,6 +229,7 @@ static ERR_STRING_DATA SSL_str_functs[] = {
     {ERR_FUNC(SSL_F_SSL_VALIDATE_CT), "ssl_validate_ct"},
     {ERR_FUNC(SSL_F_SSL_VERIFY_CERT_CHAIN), "ssl_verify_cert_chain"},
     {ERR_FUNC(SSL_F_SSL_WRITE), "SSL_write"},
+    {ERR_FUNC(SSL_F_SSL_WRITE_EX), "SSL_write_ex"},
     {ERR_FUNC(SSL_F_STATE_MACHINE), "state_machine"},
     {ERR_FUNC(SSL_F_TLS12_CHECK_PEER_SIGALG), "tls12_check_peer_sigalg"},
     {ERR_FUNC(SSL_F_TLS1_CHANGE_CIPHER_STATE), "tls1_change_cipher_state"},
diff --git a/ssl/ssl_lib.c b/ssl/ssl_lib.c
index 67eee74..363b4f4 100644
--- a/ssl/ssl_lib.c
+++ b/ssl/ssl_lib.c
@@ -59,15 +59,14 @@ SSL3_ENC_METHOD ssl3_undef_enc_method = {
      * evil casts, but these functions are only called if there's a library
      * bug
      */
-    (int (*)(SSL *, SSL3_RECORD *, unsigned int, int))ssl_undefined_function,
+    (int (*)(SSL *, SSL3_RECORD *, size_t, int))ssl_undefined_function,
     (int (*)(SSL *, SSL3_RECORD *, unsigned char *, int))ssl_undefined_function,
     ssl_undefined_function,
-    (int (*)(SSL *, unsigned char *, unsigned char *, int))
+    (int (*)(SSL *, unsigned char *, unsigned char *, size_t, size_t *))
         ssl_undefined_function,
     (int (*)(SSL *, int))ssl_undefined_function,
-    (int (*)(SSL *, const char *, int, unsigned char *))
+    (size_t (*)(SSL *, const char *, size_t, unsigned char *))
         ssl_undefined_function,
-    0,                          /* finish_mac_length */
     NULL,                       /* client_finished_label */
     0,                          /* client_finished_label_len */
     NULL,                       /* server_finished_label */
@@ -81,11 +80,11 @@ SSL3_ENC_METHOD ssl3_undef_enc_method = {
 struct ssl_async_args {
     SSL *s;
     void *buf;
-    int num;
+    size_t num;
     enum { READFUNC, WRITEFUNC, OTHERFUNC } type;
     union {
-        int (*func_read) (SSL *, void *, int);
-        int (*func_write) (SSL *, const void *, int);
+        int (*func_read) (SSL *, void *, size_t, size_t *);
+        int (*func_write) (SSL *, const void *, size_t, size_t *);
         int (*func_other) (SSL *);
     } f;
 };
@@ -319,14 +318,14 @@ static int dane_tlsa_add(SSL_DANE *dane,
     t->usage = usage;
     t->selector = selector;
     t->mtype = mtype;
-    t->data = OPENSSL_malloc(ilen);
+    t->data = OPENSSL_malloc(dlen);
     if (t->data == NULL) {
         tlsa_free(t);
         SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
         return -1;
     }
-    memcpy(t->data, data, ilen);
-    t->dlen = ilen;
+    memcpy(t->data, data, dlen);
+    t->dlen = dlen;
 
     /* Validate and cache full certificate or public key */
     if (mtype == DANETLS_MATCHING_FULL) {
@@ -336,7 +335,7 @@ static int dane_tlsa_add(SSL_DANE *dane,
 
         switch (selector) {
         case DANETLS_SELECTOR_CERT:
-            if (!d2i_X509(&cert, &p, dlen) || p < data ||
+            if (!d2i_X509(&cert, &p, ilen) || p < data ||
                 dlen != (size_t)(p - data)) {
                 tlsa_free(t);
                 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE);
@@ -371,7 +370,7 @@ static int dane_tlsa_add(SSL_DANE *dane,
             break;
 
         case DANETLS_SELECTOR_SPKI:
-            if (!d2i_PUBKEY(&pkey, &p, dlen) || p < data ||
+            if (!d2i_PUBKEY(&pkey, &p, ilen) || p < data ||
                 dlen != (size_t)(p - data)) {
                 tlsa_free(t);
                 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_PUBLIC_KEY);
@@ -598,7 +597,7 @@ SSL *SSL_new(SSL_CTX *ctx)
     s->tlsext_ocsp_ids = NULL;
     s->tlsext_ocsp_exts = NULL;
     s->tlsext_ocsp_resp = NULL;
-    s->tlsext_ocsp_resplen = -1;
+    s->tlsext_ocsp_resplen = 0;
     SSL_CTX_up_ref(ctx);
     s->initial_ctx = ctx;
 #ifndef OPENSSL_NO_EC
@@ -1293,14 +1292,19 @@ int SSL_get_read_ahead(const SSL *s)
 
 int SSL_pending(const SSL *s)
 {
+    size_t pending = s->method->ssl_pending(s);
+
     /*
      * SSL_pending cannot work properly if read-ahead is enabled
      * (SSL_[CTX_]ctrl(..., SSL_CTRL_SET_READ_AHEAD, 1, NULL)), and it is
      * impossible to fix since SSL_pending cannot report errors that may be
      * observed while scanning the new data. (Note that SSL_pending() is
      * often used as a boolean value, so we'd better not return -1.)
+     *
+     * SSL_pending also cannot work properly if the value >INT_MAX. In that case
+     * we just return INT_MAX.
      */
-    return (s->method->ssl_pending(s));
+    return pending < INT_MAX ? (int)pending : INT_MAX;
 }
 
 int SSL_has_pending(const SSL *s)
@@ -1378,7 +1382,7 @@ int SSL_copy_session_id(SSL *t, const SSL *f)
     CRYPTO_atomic_add(&f->cert->references, 1, &i, f->cert->lock);
     ssl_cert_free(t->cert);
     t->cert = f->cert;
-    if (!SSL_set_session_id_context(t, f->sid_ctx, f->sid_ctx_length)) {
+    if (!SSL_set_session_id_context(t, f->sid_ctx, (int)f->sid_ctx_length)) {
         return 0;
     }
 
@@ -1509,7 +1513,7 @@ static int ssl_io_intern(void *vargs)
     struct ssl_async_args *args;
     SSL *s;
     void *buf;
-    int num;
+    size_t num;
 
     args = (struct ssl_async_args *)vargs;
     s = args->s;
@@ -1517,9 +1521,9 @@ static int ssl_io_intern(void *vargs)
     num = args->num;
     switch (args->type) {
     case READFUNC:
-        return args->f.func_read(s, buf, num);
+        return args->f.func_read(s, buf, num, &s->asyncrw);
     case WRITEFUNC:
-        return args->f.func_write(s, buf, num);
+        return args->f.func_write(s, buf, num, &s->asyncrw);
     case OTHERFUNC:
         return args->f.func_other(s);
     }
@@ -1528,8 +1532,30 @@ static int ssl_io_intern(void *vargs)
 
 int SSL_read(SSL *s, void *buf, int num)
 {
+    int ret;
+    size_t readbytes;
+
+    if (num < 0) {
+        SSLerr(SSL_F_SSL_READ, SSL_R_BAD_LENGTH);
+        return -1;
+    }
+
+    ret = SSL_read_ex(s, buf, (size_t)num, &readbytes);
+
+    /*
+     * The cast is safe here because ret should be <= INT_MAX because num is
+     * <= INT_MAX
+     */
+    if (ret > 0)
+        ret = (int)readbytes;
+
+    return ret;
+}
+
+int SSL_read_ex(SSL *s, void *buf, size_t num, size_t *readbytes)
+{
     if (s->handshake_func == NULL) {
-        SSLerr(SSL_F_SSL_READ, SSL_R_UNINITIALIZED);
+        SSLerr(SSL_F_SSL_READ_EX, SSL_R_UNINITIALIZED);
         return -1;
     }
 
@@ -1540,6 +1566,7 @@ int SSL_read(SSL *s, void *buf, int num)
 
     if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
         struct ssl_async_args args;
+        int ret;
 
         args.s = s;
         args.buf = buf;
@@ -1547,16 +1574,40 @@ int SSL_read(SSL *s, void *buf, int num)
         args.type = READFUNC;
         args.f.func_read = s->method->ssl_read;
 
-        return ssl_start_async_job(s, &args, ssl_io_intern);
+        ret = ssl_start_async_job(s, &args, ssl_io_intern);
+        *readbytes = s->asyncrw;
+        return ret;
     } else {
-        return s->method->ssl_read(s, buf, num);
+        return s->method->ssl_read(s, buf, num, readbytes);
     }
 }
 
 int SSL_peek(SSL *s, void *buf, int num)
 {
+    int ret;
+    size_t readbytes;
+
+    if (num < 0) {
+        SSLerr(SSL_F_SSL_PEEK, SSL_R_BAD_LENGTH);
+        return -1;
+    }
+
+    ret = SSL_peek_ex(s, buf, (size_t)num, &readbytes);
+
+    /*
+     * The cast is safe here because ret should be <= INT_MAX because num is
+     * <= INT_MAX
+     */
+    if (ret > 0)
+        ret = (int)readbytes;
+
+    return ret;
+}
+
+int SSL_peek_ex(SSL *s, void *buf, size_t num, size_t *readbytes)
+{
     if (s->handshake_func == NULL) {
-        SSLerr(SSL_F_SSL_PEEK, SSL_R_UNINITIALIZED);
+        SSLerr(SSL_F_SSL_PEEK_EX, SSL_R_UNINITIALIZED);
         return -1;
     }
 
@@ -1565,6 +1616,7 @@ int SSL_peek(SSL *s, void *buf, int num)
     }
     if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
         struct ssl_async_args args;
+        int ret;
 
         args.s = s;
         args.buf = buf;
@@ -1572,26 +1624,51 @@ int SSL_peek(SSL *s, void *buf, int num)
         args.type = READFUNC;
         args.f.func_read = s->method->ssl_peek;
 
-        return ssl_start_async_job(s, &args, ssl_io_intern);
+        ret = ssl_start_async_job(s, &args, ssl_io_intern);
+        *readbytes = s->asyncrw;
+        return ret;
     } else {
-        return s->method->ssl_peek(s, buf, num);
+        return s->method->ssl_peek(s, buf, num, readbytes);
     }
 }
 
 int SSL_write(SSL *s, const void *buf, int num)
 {
+    int ret;
+    size_t written;
+
+    if (num < 0) {
+        SSLerr(SSL_F_SSL_WRITE, SSL_R_BAD_LENGTH);
+        return -1;
+    }
+
+    ret = SSL_write_ex(s, buf, (size_t)num, &written);
+
+    /*
+     * The cast is safe here because ret should be <= INT_MAX because num is
+     * <= INT_MAX
+     */
+    if (ret > 0)
+        ret = (int)written;
+
+    return ret;
+}
+
+int SSL_write_ex(SSL *s, const void *buf, size_t num, size_t *written)
+{
     if (s->handshake_func == NULL) {
-        SSLerr(SSL_F_SSL_WRITE, SSL_R_UNINITIALIZED);
+        SSLerr(SSL_F_SSL_WRITE_EX, SSL_R_UNINITIALIZED);
         return -1;
     }
 
     if (s->shutdown & SSL_SENT_SHUTDOWN) {
         s->rwstate = SSL_NOTHING;
-        SSLerr(SSL_F_SSL_WRITE, SSL_R_PROTOCOL_IS_SHUTDOWN);
+        SSLerr(SSL_F_SSL_WRITE_EX, SSL_R_PROTOCOL_IS_SHUTDOWN);
         return (-1);
     }
 
     if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
+        int ret;
         struct ssl_async_args args;
 
         args.s = s;
@@ -1600,9 +1677,11 @@ int SSL_write(SSL *s, const void *buf, int num)
         args.type = WRITEFUNC;
         args.f.func_write = s->method->ssl_write;
 
-        return ssl_start_async_job(s, &args, ssl_io_intern);
+        ret = ssl_start_async_job(s, &args, ssl_io_intern);
+        *written = s->asyncrw;
+        return ret;
     } else {
-        return s->method->ssl_write(s, buf, num);
+        return s->method->ssl_write(s, buf, num, written);
     }
 }
 
@@ -1688,11 +1767,13 @@ long SSL_ctrl(SSL *s, int cmd, long larg, void *parg)
     case SSL_CTRL_CLEAR_MODE:
         return (s->mode &= ~larg);
     case SSL_CTRL_GET_MAX_CERT_LIST:
-        return (s->max_cert_list);
+        return (long)(s->max_cert_list);
     case SSL_CTRL_SET_MAX_CERT_LIST:
-        l = s->max_cert_list;
-        s->max_cert_list = larg;
-        return (l);
+        if (larg < 0)
+            return 0;
+        l = (long)s->max_cert_list;
+        s->max_cert_list = (size_t)larg;
+        return l;
     case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
         if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
             return 0;
@@ -1701,7 +1782,7 @@ long SSL_ctrl(SSL *s, int cmd, long larg, void *parg)
             s->split_send_fragment = s->max_send_fragment;
         return 1;
     case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
-        if ((unsigned int)larg > s->max_send_fragment || larg == 0)
+        if ((size_t)larg > s->max_send_fragment || larg == 0)
             return 0;
         s->split_send_fragment = larg;
         return 1;
@@ -1800,18 +1881,22 @@ long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
         return 1;
 
     case SSL_CTRL_GET_MAX_CERT_LIST:
-        return (ctx->max_cert_list);
+        return (long)(ctx->max_cert_list);
     case SSL_CTRL_SET_MAX_CERT_LIST:
-        l = ctx->max_cert_list;
-        ctx->max_cert_list = larg;
-        return (l);
+        if (larg < 0)
+            return 0;
+        l = (long)ctx->max_cert_list;
+        ctx->max_cert_list = (size_t)larg;
+        return l;
 
     case SSL_CTRL_SET_SESS_CACHE_SIZE:
-        l = ctx->session_cache_size;
-        ctx->session_cache_size = larg;
-        return (l);
+        if (larg < 0)
+            return 0;
+        l = (long)ctx->session_cache_size;
+        ctx->session_cache_size = (size_t)larg;
+        return l;
     case SSL_CTRL_GET_SESS_CACHE_SIZE:
-        return (ctx->session_cache_size);
+        return (long)(ctx->session_cache_size);
     case SSL_CTRL_SET_SESS_CACHE_MODE:
         l = ctx->session_cache_mode;
         ctx->session_cache_mode = larg;
@@ -1855,7 +1940,7 @@ long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
             ctx->split_send_fragment = ctx->max_send_fragment;
         return 1;
     case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
-        if ((unsigned int)larg > ctx->max_send_fragment || larg == 0)
+        if ((size_t)larg > ctx->max_send_fragment || larg == 0)
             return 0;
         ctx->split_send_fragment = larg;
         return 1;
@@ -2170,7 +2255,7 @@ void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
     if (!*data) {
         *len = 0;
     } else {
-        *len = s->next_proto_negotiated_len;
+        *len = (unsigned int)s->next_proto_negotiated_len;
     }
 }
 
@@ -2287,7 +2372,7 @@ void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
     if (*data == NULL)
         *len = 0;
     else
-        *len = ssl->s3->alpn_selected_len;
+        *len = (unsigned int)ssl->s3->alpn_selected_len;
 }
 
 int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen,
@@ -2923,72 +3008,69 @@ int SSL_get_error(const SSL *s, int i)
             return (SSL_ERROR_SSL);
     }
 
-    if (i < 0) {
-        if (SSL_want_read(s)) {
-            bio = SSL_get_rbio(s);
-            if (BIO_should_read(bio))
-                return (SSL_ERROR_WANT_READ);
-            else if (BIO_should_write(bio))
-                /*
-                 * This one doesn't make too much sense ... We never try to write
-                 * to the rbio, and an application program where rbio and wbio
-                 * are separate couldn't even know what it should wait for.
-                 * However if we ever set s->rwstate incorrectly (so that we have
-                 * SSL_want_read(s) instead of SSL_want_write(s)) and rbio and
-                 * wbio *are* the same, this test works around that bug; so it
-                 * might be safer to keep it.
-                 */
-                return (SSL_ERROR_WANT_WRITE);
-            else if (BIO_should_io_special(bio)) {
-                reason = BIO_get_retry_reason(bio);
-                if (reason == BIO_RR_CONNECT)
-                    return (SSL_ERROR_WANT_CONNECT);
-                else if (reason == BIO_RR_ACCEPT)
-                    return (SSL_ERROR_WANT_ACCEPT);
-                else
-                    return (SSL_ERROR_SYSCALL); /* unknown */
-            }
+    if (SSL_want_read(s)) {
+        bio = SSL_get_rbio(s);
+        if (BIO_should_read(bio))
+            return (SSL_ERROR_WANT_READ);
+        else if (BIO_should_write(bio))
+            /*
+             * This one doesn't make too much sense ... We never try to write
+             * to the rbio, and an application program where rbio and wbio
+             * are separate couldn't even know what it should wait for.
+             * However if we ever set s->rwstate incorrectly (so that we have
+             * SSL_want_read(s) instead of SSL_want_write(s)) and rbio and
+             * wbio *are* the same, this test works around that bug; so it
+             * might be safer to keep it.
+             */
+            return (SSL_ERROR_WANT_WRITE);
+        else if (BIO_should_io_special(bio)) {
+            reason = BIO_get_retry_reason(bio);
+            if (reason == BIO_RR_CONNECT)
+                return (SSL_ERROR_WANT_CONNECT);
+            else if (reason == BIO_RR_ACCEPT)
+                return (SSL_ERROR_WANT_ACCEPT);
+            else
+                return (SSL_ERROR_SYSCALL); /* unknown */
         }
+    }
 
-        if (SSL_want_write(s)) {
+    if (SSL_want_write(s)) {
+        /*
+         * Access wbio directly - in order to use the buffered bio if
+         * present
+         */
+        bio = s->wbio;
+        if (BIO_should_write(bio))
+            return (SSL_ERROR_WANT_WRITE);
+        else if (BIO_should_read(bio))
             /*
-             * Access wbio directly - in order to use the buffered bio if
-             * present
+             * See above (SSL_want_read(s) with BIO_should_write(bio))
              */
-            bio = s->wbio;
-            if (BIO_should_write(bio))
-                return (SSL_ERROR_WANT_WRITE);
-            else if (BIO_should_read(bio))
-                /*
-                 * See above (SSL_want_read(s) with BIO_should_write(bio))
-                 */
-                return (SSL_ERROR_WANT_READ);
-            else if (BIO_should_io_special(bio)) {
-                reason = BIO_get_retry_reason(bio);
-                if (reason == BIO_RR_CONNECT)
-                    return (SSL_ERROR_WANT_CONNECT);
-                else if (reason == BIO_RR_ACCEPT)
-                    return (SSL_ERROR_WANT_ACCEPT);
-                else
-                    return (SSL_ERROR_SYSCALL);
-            }
-        }
-        if (SSL_want_x509_lookup(s)) {
-            return (SSL_ERROR_WANT_X509_LOOKUP);
-        }
-        if (SSL_want_async(s)) {
-            return SSL_ERROR_WANT_ASYNC;
-        }
-        if (SSL_want_async_job(s)) {
-            return SSL_ERROR_WANT_ASYNC_JOB;
+            return (SSL_ERROR_WANT_READ);
+        else if (BIO_should_io_special(bio)) {
+            reason = BIO_get_retry_reason(bio);
+            if (reason == BIO_RR_CONNECT)
+                return (SSL_ERROR_WANT_CONNECT);
+            else if (reason == BIO_RR_ACCEPT)
+                return (SSL_ERROR_WANT_ACCEPT);
+            else
+                return (SSL_ERROR_SYSCALL);
         }
     }
-
-    if (i == 0) {
-        if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
-            (s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY))
-            return (SSL_ERROR_ZERO_RETURN);
+    if (SSL_want_x509_lookup(s)) {
+        return (SSL_ERROR_WANT_X509_LOOKUP);
+    }
+    if (SSL_want_async(s)) {
+        return SSL_ERROR_WANT_ASYNC;
     }
+    if (SSL_want_async_job(s)) {
+        return SSL_ERROR_WANT_ASYNC_JOB;
+    }
+
+    if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
+        (s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY))
+        return (SSL_ERROR_ZERO_RETURN);
+
     return (SSL_ERROR_SYSCALL);
 }
 
@@ -3151,7 +3233,8 @@ SSL *SSL_dup(SSL *s)
                 goto err;
         }
 
-        if (!SSL_set_session_id_context(ret, s->sid_ctx, s->sid_ctx_length))
+        if (!SSL_set_session_id_context(ret, s->sid_ctx,
+                                        (int)s->sid_ctx_length))
             goto err;
     }
 
@@ -3518,13 +3601,9 @@ size_t SSL_get_server_random(const SSL *ssl, unsigned char *out, size_t outlen)
 size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
                                   unsigned char *out, size_t outlen)
 {
-    if (session->master_key_length < 0) {
-        /* Should never happen */
-        return 0;
-    }
     if (outlen == 0)
         return session->master_key_length;
-    if (outlen > (size_t)session->master_key_length)
+    if (outlen > session->master_key_length)
         outlen = session->master_key_length;
     memcpy(out, session->master_key, outlen);
     return outlen;
@@ -3755,23 +3834,28 @@ void ssl_clear_hash_ctx(EVP_MD_CTX **hash)
 }
 
 /* Retrieve handshake hashes */
-int ssl_handshake_hash(SSL *s, unsigned char *out, int outlen)
+int ssl_handshake_hash(SSL *s, unsigned char *out, size_t outlen,
+                       size_t *hashlen)
 {
     EVP_MD_CTX *ctx = NULL;
     EVP_MD_CTX *hdgst = s->s3->handshake_dgst;
-    int ret = EVP_MD_CTX_size(hdgst);
-    if (ret < 0 || ret > outlen) {
-        ret = 0;
+    int hashleni = EVP_MD_CTX_size(hdgst);
+    int ret = 0;
+
+    if (hashleni < 0 || (size_t)hashleni > outlen)
         goto err;
-    }
+
     ctx = EVP_MD_CTX_new();
-    if (ctx == NULL) {
-        ret = 0;
+    if (ctx == NULL)
         goto err;
-    }
+
     if (!EVP_MD_CTX_copy_ex(ctx, hdgst)
         || EVP_DigestFinal_ex(ctx, out, NULL) <= 0)
-        ret = 0;
+        goto err;
+
+    *hashlen = hashleni;
+
+    ret = 1;
  err:
     EVP_MD_CTX_free(ctx);
     return ret;
@@ -3991,7 +4075,7 @@ static int ct_extract_ocsp_response_scts(SSL *s)
         goto err;
 
     p = s->tlsext_ocsp_resp;
-    rsp = d2i_OCSP_RESPONSE(NULL, &p, s->tlsext_ocsp_resplen);
+    rsp = d2i_OCSP_RESPONSE(NULL, &p, (int)s->tlsext_ocsp_resplen);
     if (rsp == NULL)
         goto err;
 
diff --git a/ssl/ssl_locl.h b/ssl/ssl_locl.h
index 1cf27b9..0c6bd31 100644
--- a/ssl/ssl_locl.h
+++ b/ssl/ssl_locl.h
@@ -444,22 +444,24 @@ struct ssl_method_st {
     void (*ssl_free) (SSL *s);
     int (*ssl_accept) (SSL *s);
     int (*ssl_connect) (SSL *s);
-    int (*ssl_read) (SSL *s, void *buf, int len);
-    int (*ssl_peek) (SSL *s, void *buf, int len);
-    int (*ssl_write) (SSL *s, const void *buf, int len);
+    int (*ssl_read) (SSL *s, void *buf, size_t len, size_t *readbytes);
+    int (*ssl_peek) (SSL *s, void *buf, size_t len, size_t *readbytes);
+    int (*ssl_write) (SSL *s, const void *buf, size_t len, size_t *written);
     int (*ssl_shutdown) (SSL *s);
     int (*ssl_renegotiate) (SSL *s);
     int (*ssl_renegotiate_check) (SSL *s);
     int (*ssl_read_bytes) (SSL *s, int type, int *recvd_type,
-                           unsigned char *buf, int len, int peek);
-    int (*ssl_write_bytes) (SSL *s, int type, const void *buf_, int len);
+                           unsigned char *buf, size_t len, int peek,
+                           size_t *readbytes);
+    int (*ssl_write_bytes) (SSL *s, int type, const void *buf_, size_t len,
+                            size_t *written);
     int (*ssl_dispatch_alert) (SSL *s);
     long (*ssl_ctrl) (SSL *s, int cmd, long larg, void *parg);
     long (*ssl_ctx_ctrl) (SSL_CTX *ctx, int cmd, long larg, void *parg);
     const SSL_CIPHER *(*get_cipher_by_char) (const unsigned char *ptr);
     int (*put_cipher_by_char) (const SSL_CIPHER *cipher, WPACKET *pkt,
                                size_t *len);
-    int (*ssl_pending) (const SSL *s);
+    size_t (*ssl_pending) (const SSL *s);
     int (*num_ciphers) (void);
     const SSL_CIPHER *(*get_cipher) (unsigned ncipher);
     long (*get_timeout) (void);
@@ -498,17 +500,17 @@ struct ssl_method_st {
 struct ssl_session_st {
     int ssl_version;            /* what ssl version session info is being kept
                                  * in here? */
-    int master_key_length;
+    size_t master_key_length;
     unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
     /* session_id - valid? */
-    unsigned int session_id_length;
+    size_t session_id_length;
     unsigned char session_id[SSL_MAX_SSL_SESSION_ID_LENGTH];
     /*
      * this is used to determine whether the session is being reused in the
      * appropriate context. It is up to the application to set this, via
      * SSL_new
      */
-    unsigned int sid_ctx_length;
+    size_t sid_ctx_length;
     unsigned char sid_ctx[SSL_MAX_SID_CTX_LENGTH];
 # ifndef OPENSSL_NO_PSK
     char *psk_identity_hint;
@@ -610,7 +612,7 @@ struct ssl_ctx_st {
      * Most session-ids that will be cached, default is
      * SSL_SESSION_CACHE_MAX_SIZE_DEFAULT. 0 is unlimited.
      */
-    unsigned long session_cache_size;
+    size_t session_cache_size;
     struct ssl_session_st *session_cache_head;
     struct ssl_session_st *session_cache_tail;
     /*
@@ -709,7 +711,7 @@ struct ssl_ctx_st {
     uint32_t mode;
     int min_proto_version;
     int max_proto_version;
-    long max_cert_list;
+    size_t max_cert_list;
 
     struct cert_st /* CERT */ *cert;
     int read_ahead;
@@ -720,7 +722,7 @@ struct ssl_ctx_st {
     void *msg_callback_arg;
 
     uint32_t verify_mode;
-    unsigned int sid_ctx_length;
+    size_t sid_ctx_length;
     unsigned char sid_ctx[SSL_MAX_SID_CTX_LENGTH];
     /* called 'verify_callback' in the SSL */
     int (*default_verify_callback) (int ok, X509_STORE_CTX *ctx);
@@ -746,15 +748,15 @@ struct ssl_ctx_st {
      * If we're using more than one pipeline how should we divide the data
      * up between the pipes?
      */
-    unsigned int split_send_fragment;
+    size_t split_send_fragment;
     /*
      * Maximum amount of data to send in one fragment. actual record size can
      * be more than this due to padding and MAC overheads.
      */
-    unsigned int max_send_fragment;
+    size_t max_send_fragment;
 
     /* Up to how many pipelines should we use? If 0 then 1 is assumed */
-    unsigned int max_pipelines;
+    size_t max_pipelines;
 
     /* The default read buffer length to use (0 means not set) */
     size_t default_read_buf_len;
@@ -846,7 +848,7 @@ struct ssl_ctx_st {
      * format.
      */
     unsigned char *alpn_client_proto_list;
-    unsigned alpn_client_proto_list_len;
+    size_t alpn_client_proto_list_len;
 
     /* Shared DANE context */
     struct dane_ctx_st dane;
@@ -922,8 +924,8 @@ struct ssl_st {
     BUF_MEM *init_buf;          /* buffer used during init */
     void *init_msg;             /* pointer to handshake message body, set by
                                  * ssl3_get_message() */
-    int init_num;               /* amount read/written */
-    int init_off;               /* amount read/written */
+    size_t init_num;               /* amount read/written */
+    size_t init_off;               /* amount read/written */
     struct ssl3_state_st *s3;   /* SSLv3 variables */
     struct dtls1_state_st *d1;  /* DTLSv1 variables */
     /* callback that allows applications to peek at protocol messages */
@@ -956,7 +958,7 @@ struct ssl_st {
      * the session_id_context is used to ensure sessions are only reused in
      * the appropriate context
      */
-    unsigned int sid_ctx_length;
+    size_t sid_ctx_length;
     unsigned char sid_ctx[SSL_MAX_SID_CTX_LENGTH];
     /* This can also be in the session once a session is established */
     SSL_SESSION *session;
@@ -1001,7 +1003,7 @@ struct ssl_st {
     uint32_t mode;
     int min_proto_version;
     int max_proto_version;
-    long max_cert_list;
+    size_t max_cert_list;
     int first_packet;
     /* what was passed, used for SSLv3/TLS rollback check */
     int client_version;
@@ -1009,14 +1011,14 @@ struct ssl_st {
      * If we're using more than one pipeline how should we divide the data
      * up between the pipes?
      */
-    unsigned int split_send_fragment;
+    size_t split_send_fragment;
     /*
      * Maximum amount of data to send in one fragment. actual record size can
      * be more than this due to padding and MAC overheads.
      */
-    unsigned int max_send_fragment;
+    size_t max_send_fragment;
     /* Up to how many pipelines should we use? If 0 then 1 is assumed */
-    unsigned int max_pipelines;
+    size_t max_pipelines;
     /* TLS extension debug callback */
     void (*tlsext_debug_cb) (SSL *s, int client_server, int type,
                              const unsigned char *data, int len, void *arg);
@@ -1059,7 +1061,7 @@ struct ssl_st {
     X509_EXTENSIONS *tlsext_ocsp_exts;
     /* OCSP response received or to be sent */
     unsigned char *tlsext_ocsp_resp;
-    int tlsext_ocsp_resplen;
+    size_t tlsext_ocsp_resplen;
     /* RFC4507 session ticket expected to be received or sent */
     int tlsext_ticket_expected;
 # ifndef OPENSSL_NO_EC
@@ -1088,7 +1090,7 @@ struct ssl_st {
      * the Finished message.
      */
     unsigned char *next_proto_negotiated;
-    unsigned char next_proto_negotiated_len;
+    size_t next_proto_negotiated_len;
 # endif
 # define session_ctx initial_ctx
     /* What we'll do */
@@ -1111,7 +1113,7 @@ struct ssl_st {
      * format.
      */
     unsigned char *alpn_client_proto_list;
-    unsigned alpn_client_proto_list_len;
+    size_t alpn_client_proto_list_len;
     /*-
      * 1 if we are renegotiating.
      * 2 if we are a server and are inside a handshake
@@ -1135,14 +1137,16 @@ struct ssl_st {
     /* Async Job info */
     ASYNC_JOB *job;
     ASYNC_WAIT_CTX *waitctx;
+    size_t asyncrw;
+
     CRYPTO_RWLOCK *lock;
 };
 
 typedef struct ssl3_state_st {
     long flags;
-    int read_mac_secret_size;
+    size_t read_mac_secret_size;
     unsigned char read_mac_secret[EVP_MAX_MD_SIZE];
-    int write_mac_secret_size;
+    size_t write_mac_secret_size;
     unsigned char write_mac_secret[EVP_MAX_MD_SIZE];
     unsigned char server_random[SSL3_RANDOM_SIZE];
     unsigned char client_random[SSL3_RANDOM_SIZE];
@@ -1181,10 +1185,10 @@ typedef struct ssl3_state_st {
     struct {
         /* actually only need to be 16+20 for SSLv3 and 12 for TLS */
         unsigned char finish_md[EVP_MAX_MD_SIZE * 2];
-        int finish_md_len;
+        size_t finish_md_len;
         unsigned char peer_finish_md[EVP_MAX_MD_SIZE * 2];
-        int peer_finish_md_len;
-        unsigned long message_size;
+        size_t peer_finish_md_len;
+        size_t message_size;
         int message_type;
         /* used to hold the new cipher we are going to use */
         const SSL_CIPHER *new_cipher;
@@ -1196,12 +1200,12 @@ typedef struct ssl3_state_st {
         int ctype_num;
         char ctype[SSL3_CT_NUMBER];
         STACK_OF(X509_NAME) *ca_names;
-        int key_block_length;
+        size_t key_block_length;
         unsigned char *key_block;
         const EVP_CIPHER *new_sym_enc;
         const EVP_MD *new_hash;
         int new_mac_pkey_type;
-        int new_mac_secret_size;
+        size_t new_mac_secret_size;
 # ifndef OPENSSL_NO_COMP
         const SSL_COMP *new_compression;
 # else
@@ -1255,9 +1259,9 @@ typedef struct ssl3_state_st {
 
     /* Connection binding to prevent renegotiation attacks */
     unsigned char previous_client_finished[EVP_MAX_MD_SIZE];
-    unsigned char previous_client_finished_len;
+    size_t previous_client_finished_len;
     unsigned char previous_server_finished[EVP_MAX_MD_SIZE];
-    unsigned char previous_server_finished_len;
+    size_t previous_server_finished_len;
     int send_connection_binding; /* TODOEKR */
 
 # ifndef OPENSSL_NO_NEXTPROTONEG
@@ -1326,10 +1330,10 @@ struct dtls1_retransmit_state {
 
 struct hm_header_st {
     unsigned char type;
-    unsigned long msg_len;
+    size_t msg_len;
     unsigned short seq;
-    unsigned long frag_off;
-    unsigned long frag_len;
+    size_t frag_off;
+    size_t frag_len;
     unsigned int is_ccs;
     struct dtls1_retransmit_state saved_retransmit_state;
 };
@@ -1370,11 +1374,11 @@ pitem *pqueue_pop(pqueue *pq);
 pitem *pqueue_find(pqueue *pq, unsigned char *prio64be);
 pitem *pqueue_iterator(pqueue *pq);
 pitem *pqueue_next(piterator *iter);
-int pqueue_size(pqueue *pq);
+size_t pqueue_size(pqueue *pq);
 
 typedef struct dtls1_state_st {
     unsigned char cookie[DTLS1_COOKIE_LENGTH];
-    unsigned int cookie_len;
+    size_t cookie_len;
     unsigned int cookie_verified;
     /* handshake message numbers */
     unsigned short handshake_write_seq;
@@ -1384,8 +1388,8 @@ typedef struct dtls1_state_st {
     pqueue *buffered_messages;
     /* Buffered (sent) handshake records */
     pqueue *sent_messages;
-    unsigned int link_mtu;      /* max on-the-wire DTLS packet size */
-    unsigned int mtu;           /* max DTLS packet size */
+    size_t link_mtu;      /* max on-the-wire DTLS packet size */
+    size_t mtu;           /* max DTLS packet size */
     struct hm_header_st w_msg_hdr;
     struct hm_header_st r_msg_hdr;
     struct dtls1_timeout_st timeout;
@@ -1562,18 +1566,17 @@ struct tls_sigalgs_st {
  * of a mess of functions, but hell, think of it as an opaque structure :-)
  */
 typedef struct ssl3_enc_method {
-    int (*enc) (SSL *, SSL3_RECORD *, unsigned int, int);
+    int (*enc) (SSL *, SSL3_RECORD *, size_t, int);
     int (*mac) (SSL *, SSL3_RECORD *, unsigned char *, int);
     int (*setup_key_block) (SSL *);
     int (*generate_master_secret) (SSL *, unsigned char *, unsigned char *,
-                                   int);
+                                   size_t, size_t *);
     int (*change_cipher_state) (SSL *, int);
-    int (*final_finish_mac) (SSL *, const char *, int, unsigned char *);
-    int finish_mac_length;
+    size_t (*final_finish_mac) (SSL *, const char *, size_t, unsigned char *);
     const char *client_finished_label;
-    int client_finished_label_len;
+    size_t client_finished_label_len;
     const char *server_finished_label;
-    int server_finished_label_len;
+    size_t server_finished_label_len;
     int (*alert_value) (int);
     int (*export_keying_material) (SSL *, unsigned char *, size_t,
                                    const char *, size_t,
@@ -1581,8 +1584,6 @@ typedef struct ssl3_enc_method {
                                    int use_context);
     /* Various flags indicating protocol version requirements */
     uint32_t enc_flags;
-    /* Handshake header length */
-    unsigned int hhlen;
     /* Set the handshake header */
     int (*set_handshake_header) (SSL *s, WPACKET *pkt, int type);
     /* Close construction of the handshake message */
@@ -1591,9 +1592,6 @@ typedef struct ssl3_enc_method {
     int (*do_write) (SSL *s);
 } SSL3_ENC_METHOD;
 
-# define SSL_HM_HEADER_LENGTH(s) s->method->ssl3_enc->hhlen
-# define ssl_handshake_start(s) \
-        (((unsigned char *)s->init_buf->data) + s->method->ssl3_enc->hhlen)
 # define ssl_set_handshake_header(s, pkt, htype) \
         s->method->ssl3_enc->set_handshake_header((s), (pkt), (htype))
 # define ssl_close_construct_packet(s, pkt, htype) \
@@ -1815,7 +1813,7 @@ __owur STACK_OF(SSL_CIPHER) *ssl_create_cipher_list(const SSL_METHOD *meth,
 void ssl_update_cache(SSL *s, int mode);
 __owur int ssl_cipher_get_evp(const SSL_SESSION *s, const EVP_CIPHER **enc,
                               const EVP_MD **md, int *mac_pkey_type,
-                              int *mac_secret_size, SSL_COMP **comp,
+                              size_t *mac_secret_size, SSL_COMP **comp,
                               int use_etm);
 __owur int ssl_cipher_get_overhead(const SSL_CIPHER *c, size_t *mac_overhead,
                                    size_t *int_overhead, size_t *blocksize,
@@ -1858,7 +1856,7 @@ __owur int ssl_verify_alarm_type(long type);
 void ssl_sort_cipher_list(void);
 void ssl_load_ciphers(void);
 __owur int ssl_fill_hello_random(SSL *s, int server, unsigned char *field,
-                                 int len);
+                                 size_t len);
 __owur int ssl_generate_master_secret(SSL *s, unsigned char *pms, size_t pmslen,
                                       int free_pms);
 __owur EVP_PKEY *ssl_generate_pkey(EVP_PKEY *pm);
@@ -1875,16 +1873,17 @@ void ssl3_cleanup_key_block(SSL *s);
 __owur int ssl3_do_write(SSL *s, int type);
 int ssl3_send_alert(SSL *s, int level, int desc);
 __owur int ssl3_generate_master_secret(SSL *s, unsigned char *out,
-                                       unsigned char *p, int len);
+                                       unsigned char *p, size_t len,
+                                       size_t *secret_size);
 __owur int ssl3_get_req_cert_type(SSL *s, WPACKET *pkt);
 __owur int ssl3_num_ciphers(void);
 __owur const SSL_CIPHER *ssl3_get_cipher(unsigned int u);
 int ssl3_renegotiate(SSL *ssl);
 int ssl3_renegotiate_check(SSL *ssl);
 __owur int ssl3_dispatch_alert(SSL *s);
-__owur int ssl3_final_finish_mac(SSL *s, const char *sender, int slen,
-                                 unsigned char *p);
-__owur int ssl3_finish_mac(SSL *s, const unsigned char *buf, int len);
+__owur size_t ssl3_final_finish_mac(SSL *s, const char *sender, size_t slen,
+                                    unsigned char *p);
+__owur int ssl3_finish_mac(SSL *s, const unsigned char *buf, size_t len);
 void ssl3_free_digest_list(SSL *s);
 __owur unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt,
                                             CERT_PKEY *cpk);
@@ -1894,9 +1893,9 @@ __owur const SSL_CIPHER *ssl3_choose_cipher(SSL *ssl,
 __owur int ssl3_digest_cached_records(SSL *s, int keep);
 __owur int ssl3_new(SSL *s);
 void ssl3_free(SSL *s);
-__owur int ssl3_read(SSL *s, void *buf, int len);
-__owur int ssl3_peek(SSL *s, void *buf, int len);
-__owur int ssl3_write(SSL *s, const void *buf, int len);
+__owur int ssl3_read(SSL *s, void *buf, size_t len, size_t *readbytes);
+__owur int ssl3_peek(SSL *s, void *buf, size_t len, size_t *readbytes);
+__owur int ssl3_write(SSL *s, const void *buf, size_t len, size_t *written);
 __owur int ssl3_shutdown(SSL *s);
 void ssl3_clear(SSL *s);
 __owur long ssl3_ctrl(SSL *s, int cmd, long larg, void *parg);
@@ -1929,11 +1928,11 @@ __owur long tls1_default_timeout(void);
 __owur int dtls1_do_write(SSL *s, int type);
 void dtls1_set_message_header(SSL *s,
                               unsigned char mt,
-                              unsigned long len,
-                              unsigned long frag_off, unsigned long frag_len);
+                              size_t len,
+                              size_t frag_off, size_t frag_len);
 
-__owur int dtls1_write_app_data_bytes(SSL *s, int type, const void *buf,
-                                      int len);
+int dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, size_t len,
+                               size_t *written);
 
 __owur int dtls1_read_failed(SSL *s, int code);
 __owur int dtls1_buffer_message(SSL *s, int ccs);
@@ -1953,9 +1952,9 @@ void dtls1_stop_timer(SSL *s);
 __owur int dtls1_is_timer_expired(SSL *s);
 void dtls1_double_timeout(SSL *s);
 __owur int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,
-                                         unsigned char cookie_len);
+                                         size_t cookie_len);
 __owur int dtls1_send_newsession_ticket(SSL *s);
-__owur unsigned int dtls1_min_mtu(SSL *s);
+__owur size_t dtls1_min_mtu(SSL *s);
 void dtls1_hm_fragment_free(hm_fragment *frag);
 __owur int dtls1_query_mtu(SSL *s);
 
@@ -1978,10 +1977,11 @@ void ssl_free_wbio_buffer(SSL *s);
 
 __owur int tls1_change_cipher_state(SSL *s, int which);
 __owur int tls1_setup_key_block(SSL *s);
-__owur int tls1_final_finish_mac(SSL *s,
-                                 const char *str, int slen, unsigned char *p);
+__owur size_t tls1_final_finish_mac(SSL *s, const char *str, size_t slen,
+                                    unsigned char *p);
 __owur int tls1_generate_master_secret(SSL *s, unsigned char *out,
-                                       unsigned char *p, int len);
+                                       unsigned char *p, size_t len,
+                                       size_t *secret_size);
 __owur int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
                                        const char *label, size_t llen,
                                        const unsigned char *p, size_t plen,
@@ -2031,7 +2031,7 @@ __owur int ssl_prepare_serverhello_tlsext(SSL *s);
 #  ifndef OPENSSL_NO_HEARTBEATS
 __owur int dtls1_heartbeat(SSL *s);
 __owur int dtls1_process_heartbeat(SSL *s, unsigned char *p,
-                                   unsigned int length);
+                                   size_t length);
 #  endif
 
 __owur int tls_check_serverhello_tlsext_early(SSL *s, const PACKET *ext,
@@ -2071,7 +2071,7 @@ __owur int ssl_parse_clienthello_renegotiate_ext(SSL *s, PACKET *pkt, int *al);
 __owur long ssl_get_algorithm2(SSL *s);
 __owur int tls12_copy_sigalgs(SSL *s, WPACKET *pkt,
                               const unsigned char *psig, size_t psiglen);
-__owur int tls1_save_sigalgs(SSL *s, const unsigned char *data, int dsize);
+__owur int tls1_save_sigalgs(SSL *s, const unsigned char *data, size_t dsize);
 __owur int tls1_process_sigalgs(SSL *s);
 __owur size_t tls12_get_psigalgs(SSL *s, const unsigned char **psigs);
 __owur int tls12_check_peer_sigalg(const EVP_MD **pmd, SSL *s,
@@ -2082,7 +2082,8 @@ __owur int ssl_cipher_disabled(SSL *s, const SSL_CIPHER *c, int op);
 __owur int ssl_parse_clienthello_use_srtp_ext(SSL *s, PACKET *pkt, int *al);
 __owur int ssl_parse_serverhello_use_srtp_ext(SSL *s, PACKET *pkt, int *al);
 
-__owur int ssl_handshake_hash(SSL *s, unsigned char *out, int outlen);
+__owur int ssl_handshake_hash(SSL *s, unsigned char *out, size_t outlen,
+                                 size_t *hashlen);
 __owur const EVP_MD *ssl_md(int idx);
 __owur const EVP_MD *ssl_handshake_md(SSL *s);
 __owur const EVP_MD *ssl_prf_md(SSL *s);
@@ -2097,7 +2098,7 @@ __owur int ssl3_cbc_digest_record(const EVP_MD_CTX *ctx,
                                   size_t data_plus_mac_size,
                                   size_t data_plus_mac_plus_padding_size,
                                   const unsigned char *mac_secret,
-                                  unsigned mac_secret_length, char is_sslv3);
+                                  size_t mac_secret_length, char is_sslv3);
 
 __owur int tls_fips_digest_extra(const EVP_CIPHER_CTX *cipher_ctx,
                                  EVP_MD_CTX *mac_ctx, const unsigned char *data,
diff --git a/ssl/ssl_mcnf.c b/ssl/ssl_mcnf.c
index c2d9dba..59674f3 100644
--- a/ssl/ssl_mcnf.c
+++ b/ssl/ssl_mcnf.c
@@ -73,7 +73,7 @@ static int ssl_module_init(CONF_IMODULE *md, const CONF *cnf)
     ssl_names_count = cnt;
     for (i = 0; i < ssl_names_count; i++) {
         struct ssl_conf_name *ssl_name = ssl_names + i;
-        CONF_VALUE *sect = sk_CONF_VALUE_value(cmd_lists, i);
+        CONF_VALUE *sect = sk_CONF_VALUE_value(cmd_lists, (int)i);
         STACK_OF(CONF_VALUE) *cmds = NCONF_get_section(cnf, sect->value);
         if (sk_CONF_VALUE_num(cmds) <= 0) {
             if (cmds == NULL)
@@ -94,7 +94,7 @@ static int ssl_module_init(CONF_IMODULE *md, const CONF *cnf)
         ssl_name->cmd_count = cnt;
         for (j = 0; j < cnt; j++) {
             const char *name;
-            CONF_VALUE *cmd_conf = sk_CONF_VALUE_value(cmds, j);
+            CONF_VALUE *cmd_conf = sk_CONF_VALUE_value(cmds, (int)j);
             struct ssl_conf_cmd *cmd = ssl_name->cmds + j;
             /* Skip any initial dot in name */
             name = strchr(cmd_conf->name, '.');
diff --git a/ssl/ssl_sess.c b/ssl/ssl_sess.c
index e0ec918..44101cb 100644
--- a/ssl/ssl_sess.c
+++ b/ssl/ssl_sess.c
@@ -236,14 +236,14 @@ SSL_SESSION *ssl_session_dup(SSL_SESSION *src, int ticket)
 const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s, unsigned int *len)
 {
     if (len)
-        *len = s->session_id_length;
+        *len = (unsigned int)s->session_id_length;
     return s->session_id;
 }
 const unsigned char *SSL_SESSION_get0_id_context(const SSL_SESSION *s,
                                                 unsigned int *len)
 {
     if (len != NULL)
-        *len = s->sid_ctx_length;
+        *len = (unsigned int)s->sid_ctx_length;
     return s->sid_ctx;
 }
 
@@ -369,7 +369,7 @@ int ssl_get_new_session(SSL *s, int session)
         CRYPTO_THREAD_unlock(s->lock);
         /* Choose a session ID */
         memset(ss->session_id, 0, ss->session_id_length);
-        tmp = ss->session_id_length;
+        tmp = (int)ss->session_id_length;
         if (!cb(s, ss->session_id, &tmp)) {
             /* The callback failed */
             SSLerr(SSL_F_SSL_GET_NEW_SESSION,
@@ -391,7 +391,7 @@ int ssl_get_new_session(SSL *s, int session)
         ss->session_id_length = tmp;
         /* Finally, check for a conflict */
         if (SSL_has_matching_session_id(s, ss->session_id,
-                                        ss->session_id_length)) {
+                                        (unsigned int)ss->session_id_length)) {
             SSLerr(SSL_F_SSL_GET_NEW_SESSION, SSL_R_SSL_SESSION_ID_CONFLICT);
             SSL_SESSION_free(ss);
             return (0);
@@ -502,7 +502,7 @@ int ssl_get_prev_session(SSL *s, const PACKET *ext, const PACKET *session_id)
         ret == NULL && s->session_ctx->get_session_cb != NULL) {
         int copy = 1;
         ret = s->session_ctx->get_session_cb(s, PACKET_data(session_id),
-                                             PACKET_remaining(session_id),
+                                             (int)PACKET_remaining(session_id),
                                              &copy);
 
         if (ret != NULL) {
diff --git a/ssl/ssl_txt.c b/ssl/ssl_txt.c
index dbbf9d9..06ea646 100644
--- a/ssl/ssl_txt.c
+++ b/ssl/ssl_txt.c
@@ -57,7 +57,7 @@ int SSL_SESSION_print_fp(FILE *fp, const SSL_SESSION *x)
 
 int SSL_SESSION_print(BIO *bp, const SSL_SESSION *x)
 {
-    unsigned int i;
+    size_t i;
     const char *s;
 
     if (x == NULL)
@@ -98,7 +98,7 @@ int SSL_SESSION_print(BIO *bp, const SSL_SESSION *x)
     }
     if (BIO_puts(bp, "\n    Master-Key: ") <= 0)
         goto err;
-    for (i = 0; i < (unsigned int)x->master_key_length; i++) {
+    for (i = 0; i < x->master_key_length; i++) {
         if (BIO_printf(bp, "%02X", x->master_key[i]) <= 0)
             goto err;
     }
@@ -128,8 +128,9 @@ int SSL_SESSION_print(BIO *bp, const SSL_SESSION *x)
     if (x->tlsext_tick) {
         if (BIO_puts(bp, "\n    TLS session ticket:\n") <= 0)
             goto err;
+        /* TODO(size_t): Convert this call */
         if (BIO_dump_indent
-            (bp, (const char *)x->tlsext_tick, x->tlsext_ticklen, 4)
+            (bp, (const char *)x->tlsext_tick, (int)x->tlsext_ticklen, 4)
             <= 0)
             goto err;
     }
@@ -181,7 +182,7 @@ int SSL_SESSION_print(BIO *bp, const SSL_SESSION *x)
  */
 int SSL_SESSION_print_keylog(BIO *bp, const SSL_SESSION *x)
 {
-    unsigned int i;
+    size_t i;
 
     if (x == NULL)
         goto err;
@@ -204,7 +205,7 @@ int SSL_SESSION_print_keylog(BIO *bp, const SSL_SESSION *x)
     }
     if (BIO_puts(bp, " Master-Key:") <= 0)
         goto err;
-    for (i = 0; i < (unsigned int)x->master_key_length; i++) {
+    for (i = 0; i < x->master_key_length; i++) {
         if (BIO_printf(bp, "%02X", x->master_key[i]) <= 0)
             goto err;
     }
diff --git a/ssl/statem/statem.c b/ssl/statem/statem.c
index 786eb24..901a3f2 100644
--- a/ssl/statem/statem.c
+++ b/ssl/statem/statem.c
@@ -490,12 +490,12 @@ static SUB_STATE_RETURN read_state_machine(SSL *s)
 {
     OSSL_STATEM *st = &s->statem;
     int ret, mt;
-    unsigned long len = 0;
+    size_t len = 0;
     int (*transition) (SSL *s, int mt);
     PACKET pkt;
     MSG_PROCESS_RETURN(*process_message) (SSL *s, PACKET *pkt);
     WORK_STATE(*post_process_message) (SSL *s, WORK_STATE wst);
-    unsigned long (*max_message_size) (SSL *s);
+    size_t (*max_message_size) (SSL *s);
     void (*cb) (const SSL *ssl, int type, int val) = NULL;
 
     cb = get_callback(s);
diff --git a/ssl/statem/statem_clnt.c b/ssl/statem/statem_clnt.c
index 51513d5..d8fbf58 100644
--- a/ssl/statem/statem_clnt.c
+++ b/ssl/statem/statem_clnt.c
@@ -568,7 +568,7 @@ int ossl_statem_client_construct_message(SSL *s, WPACKET *pkt,
  * Returns the maximum allowed length for the current message that we are
  * reading. Excludes the message header.
  */
-unsigned long ossl_statem_client_max_message_size(SSL *s)
+size_t ossl_statem_client_max_message_size(SSL *s)
 {
     OSSL_STATEM *st = &s->statem;
 
@@ -696,8 +696,8 @@ WORK_STATE ossl_statem_client_post_process_message(SSL *s, WORK_STATE wst)
 int tls_construct_client_hello(SSL *s, WPACKET *pkt)
 {
     unsigned char *p;
-    int i;
-    int protverr;
+    size_t sess_id_len;
+    int i, protverr;
     int al = SSL_AD_HANDSHAKE_FAILURE;
 #ifndef OPENSSL_NO_COMP
     SSL_COMP *comp;
@@ -788,12 +788,13 @@ int tls_construct_client_hello(SSL *s, WPACKET *pkt)
 
     /* Session ID */
     if (s->new_session)
-        i = 0;
+        sess_id_len = 0;
     else
-        i = s->session->session_id_length;
-    if (i > (int)sizeof(s->session->session_id)
+        sess_id_len = s->session->session_id_length;
+    if (sess_id_len > sizeof(s->session->session_id)
             || !WPACKET_start_sub_packet_u8(pkt)
-            || (i != 0 && !WPACKET_memcpy(pkt, s->session->session_id, i))
+            || (sess_id_len != 0 && !WPACKET_memcpy(pkt, s->session->session_id,
+                                                    sess_id_len))
             || !WPACKET_close(pkt)) {
         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
         return 0;
@@ -869,7 +870,7 @@ int tls_construct_client_hello(SSL *s, WPACKET *pkt)
 MSG_PROCESS_RETURN dtls_process_hello_verify(SSL *s, PACKET *pkt)
 {
     int al;
-    unsigned int cookie_len;
+    size_t cookie_len;
     PACKET cookiepkt;
 
     if (!PACKET_forward(pkt, 2)
@@ -973,11 +974,18 @@ MSG_PROCESS_RETURN tls_process_server_hello(SSL *s, PACKET *pkt)
     if (s->version >= TLS1_VERSION && s->tls_session_secret_cb &&
         s->session->tlsext_tick) {
         const SSL_CIPHER *pref_cipher = NULL;
-        s->session->master_key_length = sizeof(s->session->master_key);
+        /*
+         * s->session->master_key_length is a size_t, but this is an int for
+         * backwards compat reasons
+         */
+        int master_key_length;
+        master_key_length = sizeof(s->session->master_key);
         if (s->tls_session_secret_cb(s, s->session->master_key,
-                                     &s->session->master_key_length,
+                                     &master_key_length,
                                      NULL, &pref_cipher,
-                                     s->tls_session_secret_cb_arg)) {
+                                     s->tls_session_secret_cb_arg)
+                 && master_key_length > 0) {
+            s->session->master_key_length = master_key_length;
             s->session->cipher = pref_cipher ?
                 pref_cipher : ssl_get_cipher_by_char(s, cipherchars);
         } else {
@@ -1350,18 +1358,19 @@ static int tls_process_ske_srp(SSL *s, PACKET *pkt, EVP_PKEY **pkey, int *al)
         return 0;
     }
 
+    /* TODO(size_t): Convert BN_bin2bn() calls */
     if ((s->srp_ctx.N =
          BN_bin2bn(PACKET_data(&prime),
-                   PACKET_remaining(&prime), NULL)) == NULL
+                   (int)PACKET_remaining(&prime), NULL)) == NULL
         || (s->srp_ctx.g =
             BN_bin2bn(PACKET_data(&generator),
-                      PACKET_remaining(&generator), NULL)) == NULL
+                      (int)PACKET_remaining(&generator), NULL)) == NULL
         || (s->srp_ctx.s =
             BN_bin2bn(PACKET_data(&salt),
-                      PACKET_remaining(&salt), NULL)) == NULL
+                      (int)PACKET_remaining(&salt), NULL)) == NULL
         || (s->srp_ctx.B =
             BN_bin2bn(PACKET_data(&server_pub),
-                      PACKET_remaining(&server_pub), NULL)) == NULL) {
+                      (int)PACKET_remaining(&server_pub), NULL)) == NULL) {
         *al = SSL_AD_INTERNAL_ERROR;
         SSLerr(SSL_F_TLS_PROCESS_SKE_SRP, ERR_R_BN_LIB);
         return 0;
@@ -1411,10 +1420,12 @@ static int tls_process_ske_dhe(SSL *s, PACKET *pkt, EVP_PKEY **pkey, int *al)
         goto err;
     }
 
-    p = BN_bin2bn(PACKET_data(&prime), PACKET_remaining(&prime), NULL);
-    g = BN_bin2bn(PACKET_data(&generator), PACKET_remaining(&generator), NULL);
-    bnpub_key = BN_bin2bn(PACKET_data(&pub_key), PACKET_remaining(&pub_key),
-                          NULL);
+    /* TODO(size_t): Convert these calls */
+    p = BN_bin2bn(PACKET_data(&prime), (int)PACKET_remaining(&prime), NULL);
+    g = BN_bin2bn(PACKET_data(&generator), (int)PACKET_remaining(&generator),
+                  NULL);
+    bnpub_key = BN_bin2bn(PACKET_data(&pub_key),
+                          (int)PACKET_remaining(&pub_key), NULL);
     if (p == NULL || g == NULL || bnpub_key == NULL) {
         *al = SSL_AD_INTERNAL_ERROR;
         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_BN_LIB);
@@ -1702,8 +1713,10 @@ MSG_PROCESS_RETURN tls_process_key_exchange(SSL *s, PACKET *pkt)
             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EVP_LIB);
             goto err;
         }
+        /* TODO(size_t): Convert this call */
         if (EVP_VerifyFinal(md_ctx, PACKET_data(&signature),
-                            PACKET_remaining(&signature), pkey) <= 0) {
+                            (unsigned int)PACKET_remaining(&signature),
+                            pkey) <= 0) {
             /* bad signature */
             EVP_MD_CTX_free(md_ctx);
             al = SSL_AD_DECRYPT_ERROR;
@@ -1772,7 +1785,7 @@ MSG_PROCESS_RETURN tls_process_certificate_request(SSL *s, PACKET *pkt)
             goto err;
         }
         memcpy(s->cert->ctypes, data, ctype_num);
-        s->cert->ctype_num = (size_t)ctype_num;
+        s->cert->ctype_num = ctype_num;
         ctype_num = SSL3_CT_NUMBER;
     }
     for (i = 0; i < ctype_num; i++)
@@ -1873,6 +1886,7 @@ MSG_PROCESS_RETURN tls_process_new_session_ticket(SSL *s, PACKET *pkt)
     int al;
     unsigned int ticklen;
     unsigned long ticket_lifetime_hint;
+    unsigned int sess_len;
 
     if (!PACKET_get_net_4(pkt, &ticket_lifetime_hint)
         || !PACKET_get_net_2(pkt, &ticklen)
@@ -1937,12 +1951,17 @@ MSG_PROCESS_RETURN tls_process_new_session_ticket(SSL *s, PACKET *pkt)
      * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
      * SHA256 is disabled) hash of the ticket.
      */
+    /*
+     * TODO(size_t): we use sess_len here because EVP_Digest expects an int
+     * but s->session->session_id_length is a size_t
+     */
     if (!EVP_Digest(s->session->tlsext_tick, ticklen,
-                    s->session->session_id, &s->session->session_id_length,
+                    s->session->session_id, &sess_len,
                     EVP_sha256(), NULL)) {
         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_EVP_LIB);
         goto err;
     }
+    s->session->session_id_length = sess_len;
     return MSG_PROCESS_CONTINUE_READING;
  f_err:
     ssl3_send_alert(s, SSL3_AL_FATAL, al);
@@ -1954,7 +1973,7 @@ MSG_PROCESS_RETURN tls_process_new_session_ticket(SSL *s, PACKET *pkt)
 MSG_PROCESS_RETURN tls_process_cert_status(SSL *s, PACKET *pkt)
 {
     int al;
-    unsigned long resplen;
+    size_t resplen;
     unsigned int type;
 
     if (!PACKET_get_1(pkt, &type)
@@ -1963,7 +1982,7 @@ MSG_PROCESS_RETURN tls_process_cert_status(SSL *s, PACKET *pkt)
         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_UNSUPPORTED_STATUS_TYPE);
         goto f_err;
     }
-    if (!PACKET_get_net_3(pkt, &resplen)
+    if (!PACKET_get_net_3_len(pkt, &resplen)
         || PACKET_remaining(pkt) != resplen) {
         al = SSL_AD_DECODE_ERROR;
         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
@@ -2177,7 +2196,8 @@ static int tls_construct_cke_rsa(SSL *s, WPACKET *pkt, int *al)
 
     pms[0] = s->client_version >> 8;
     pms[1] = s->client_version & 0xff;
-    if (RAND_bytes(pms + 2, pmslen - 2) <= 0) {
+    /* TODO(size_t): Convert this function */
+    if (RAND_bytes(pms + 2, (int)(pmslen - 2)) <= 0) {
         goto err;
     }
 
@@ -2267,7 +2287,7 @@ static int tls_construct_cke_ecdhe(SSL *s, WPACKET *pkt, int *al)
 {
 #ifndef OPENSSL_NO_EC
     unsigned char *encodedPoint = NULL;
-    int encoded_pt_len = 0;
+    size_t encoded_pt_len = 0;
     EVP_PKEY *ckey = NULL, *skey = NULL;
     int ret = 0;
 
@@ -2359,8 +2379,10 @@ static int tls_construct_cke_gost(SSL *s, WPACKET *pkt, int *al)
     }
 
     if (EVP_PKEY_encrypt_init(pkey_ctx) <= 0
-        /* Generate session key */
-        || RAND_bytes(pms, pmslen) <= 0) {
+        /* Generate session key
+         * TODO(size_t): Convert this function
+         */
+        || RAND_bytes(pms, (int)pmslen) <= 0) {
         *al = SSL_AD_INTERNAL_ERROR;
         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
         goto err;
@@ -2601,7 +2623,7 @@ int tls_construct_client_verify(SSL *s, WPACKET *pkt)
         || !EVP_SignUpdate(mctx, hdata, hdatalen)
         || (s->version == SSL3_VERSION
             && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
-                                s->session->master_key_length,
+                                (int)s->session->master_key_length,
                                 s->session->master_key))
         || !EVP_SignFinal(mctx, sig, &u, pkey)) {
         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_EVP_LIB);
diff --git a/ssl/statem/statem_dtls.c b/ssl/statem/statem_dtls.c
index 5b90c56..52e62a4 100644
--- a/ssl/statem/statem_dtls.c
+++ b/ssl/statem/statem_dtls.c
@@ -43,18 +43,17 @@ static unsigned char bitmask_start_values[] =
 static unsigned char bitmask_end_values[] =
     { 0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f };
 
-static void dtls1_fix_message_header(SSL *s, unsigned long frag_off,
-                                     unsigned long frag_len);
+static void dtls1_fix_message_header(SSL *s, size_t frag_off,
+                                     size_t frag_len);
 static unsigned char *dtls1_write_message_header(SSL *s, unsigned char *p);
 static void dtls1_set_message_header_int(SSL *s, unsigned char mt,
-                                         unsigned long len,
+                                         size_t len,
                                          unsigned short seq_num,
-                                         unsigned long frag_off,
-                                         unsigned long frag_len);
-static int dtls_get_reassembled_message(SSL *s, long *len);
+                                         size_t frag_off,
+                                         size_t frag_len);
+static int dtls_get_reassembled_message(SSL *s, int *errtype, size_t *len);
 
-static hm_fragment *dtls1_hm_fragment_new(unsigned long frag_len,
-                                          int reassembly)
+static hm_fragment *dtls1_hm_fragment_new(size_t frag_len, int reassembly)
 {
     hm_fragment *frag = NULL;
     unsigned char *buf = NULL;
@@ -111,9 +110,10 @@ void dtls1_hm_fragment_free(hm_fragment *frag)
 int dtls1_do_write(SSL *s, int type)
 {
     int ret;
-    unsigned int curr_mtu;
+    size_t written;
+    size_t curr_mtu;
     int retry = 1;
-    unsigned int len, frag_off, mac_size, blocksize, used_len;
+    size_t len, frag_off, mac_size, blocksize, used_len;
 
     if (!dtls1_query_mtu(s))
         return -1;
@@ -124,7 +124,7 @@ int dtls1_do_write(SSL *s, int type)
 
     if (s->init_off == 0 && type == SSL3_RT_HANDSHAKE)
         OPENSSL_assert(s->init_num ==
-                       (int)s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH);
+                       s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH);
 
     if (s->write_hash) {
         if (s->enc_write_ctx
@@ -214,10 +214,6 @@ int dtls1_do_write(SSL *s, int type)
         else
             len = s->init_num;
 
-        /* Shouldn't ever happen */
-        if (len > INT_MAX)
-            len = INT_MAX;
-
         /*
          * XDTLS: this function is too long.  split out the CCS part
          */
@@ -236,7 +232,8 @@ int dtls1_do_write(SSL *s, int type)
                                        data[s->init_off]);
         }
 
-        ret = dtls1_write_bytes(s, type, &s->init_buf->data[s->init_off], len);
+        ret = dtls1_write_bytes(s, type, &s->init_buf->data[s->init_off], len,
+                                &written);
         if (ret < 0) {
             /*
              * might need to update MTU here, but we don't know which
@@ -262,7 +259,7 @@ int dtls1_do_write(SSL *s, int type)
              * bad if this assert fails, only part of the handshake message
              * got sent.  but why would this happen?
              */
-            OPENSSL_assert(len == (unsigned int)ret);
+            OPENSSL_assert(len == written);
 
             if (type == SSL3_RT_HANDSHAKE && !s->d1->retransmitting) {
                 /*
@@ -272,7 +269,7 @@ int dtls1_do_write(SSL *s, int type)
                 unsigned char *p =
                     (unsigned char *)&s->init_buf->data[s->init_off];
                 const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
-                int xlen;
+                size_t xlen;
 
                 if (frag_off == 0 && s->version != DTLS1_BAD_VER) {
                     /*
@@ -285,17 +282,17 @@ int dtls1_do_write(SSL *s, int type)
                     l2n3(0, p);
                     l2n3(msg_hdr->msg_len, p);
                     p -= DTLS1_HM_HEADER_LENGTH;
-                    xlen = ret;
+                    xlen = written;
                 } else {
                     p += DTLS1_HM_HEADER_LENGTH;
-                    xlen = ret - DTLS1_HM_HEADER_LENGTH;
+                    xlen = written - DTLS1_HM_HEADER_LENGTH;
                 }
 
                 if (!ssl3_finish_mac(s, p, xlen))
                     return -1;
             }
 
-            if (ret == s->init_num) {
+            if (written == s->init_num) {
                 if (s->msg_callback)
                     s->msg_callback(1, s->version, type, s->init_buf->data,
                                     (size_t)(s->init_off + s->init_num), s,
@@ -304,12 +301,12 @@ int dtls1_do_write(SSL *s, int type)
                 s->init_off = 0; /* done writing this message */
                 s->init_num = 0;
 
-                return (1);
+                return 1;
             }
-            s->init_off += ret;
-            s->init_num -= ret;
-            ret -= DTLS1_HM_HEADER_LENGTH;
-            frag_off += ret;
+            s->init_off += written;
+            s->init_num -= written;
+            written -= DTLS1_HM_HEADER_LENGTH;
+            frag_off += written;
 
             /*
              * We save the fragment offset for the next fragment so we have it
@@ -320,32 +317,34 @@ int dtls1_do_write(SSL *s, int type)
             dtls1_fix_message_header(s, frag_off, 0);
         }
     }
-    return (0);
+    return 0;
 }
 
-int dtls_get_message(SSL *s, int *mt, unsigned long *len)
+int dtls_get_message(SSL *s, int *mt, size_t *len)
 {
     struct hm_header_st *msg_hdr;
     unsigned char *p;
-    unsigned long msg_len;
-    int ok;
-    long tmplen;
+    size_t msg_len;
+    size_t tmplen;
+    int errtype;
 
     msg_hdr = &s->d1->r_msg_hdr;
     memset(msg_hdr, 0, sizeof(*msg_hdr));
 
  again:
-    ok = dtls_get_reassembled_message(s, &tmplen);
-    if (tmplen == DTLS1_HM_BAD_FRAGMENT || tmplen == DTLS1_HM_FRAGMENT_RETRY) {
-        /* bad fragment received */
-        goto again;
-    } else if (tmplen <= 0 && !ok) {
+    if (!dtls_get_reassembled_message(s, &errtype, &tmplen)) {
+        if (errtype == DTLS1_HM_BAD_FRAGMENT
+                || errtype == DTLS1_HM_FRAGMENT_RETRY) {
+            /* bad fragment received */
+            goto again;
+        }
         return 0;
     }
 
     *mt = s->s3->tmp.message_type;
 
     p = (unsigned char *)s->init_buf->data;
+    *len = s->init_num;
 
     if (*mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
         if (s->msg_callback) {
@@ -355,7 +354,6 @@ int dtls_get_message(SSL *s, int *mt, unsigned long *len)
         /*
          * This isn't a real handshake message so skip the processing below.
          */
-        *len = (unsigned long)tmplen;
         return 1;
     }
 
@@ -383,7 +381,6 @@ int dtls_get_message(SSL *s, int *mt, unsigned long *len)
     s->d1->handshake_read_seq++;
 
     s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
-    *len = s->init_num;
 
     return 1;
 }
@@ -393,11 +390,10 @@ int dtls_get_message(SSL *s, int *mt, unsigned long *len)
  * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but
  * may be greater if the maximum certificate list size requires it.
  */
-static unsigned long dtls1_max_handshake_message_len(const SSL *s)
+static size_t dtls1_max_handshake_message_len(const SSL *s)
 {
-    unsigned long max_len =
-        DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
-    if (max_len < (unsigned long)s->max_cert_list)
+    size_t max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
+    if (max_len < s->max_cert_list)
         return s->max_cert_list;
     return max_len;
 }
@@ -444,7 +440,7 @@ static int dtls1_preprocess_fragment(SSL *s, struct hm_header_st *msg_hdr)
     return 0;                   /* no error */
 }
 
-static int dtls1_retrieve_buffered_fragment(SSL *s, int *ok)
+static int dtls1_retrieve_buffered_fragment(SSL *s, size_t *len)
 {
     /*-
      * (0) check whether the desired fragment is available
@@ -456,8 +452,6 @@ static int dtls1_retrieve_buffered_fragment(SSL *s, int *ok)
     hm_fragment *frag;
     int al;
 
-    *ok = 0;
-
     do {
         item = pqueue_peek(s->d1->buffered_messages);
         if (item == NULL)
@@ -480,7 +474,7 @@ static int dtls1_retrieve_buffered_fragment(SSL *s, int *ok)
         return 0;
 
     if (s->d1->handshake_read_seq == frag->msg_header.seq) {
-        unsigned long frag_len = frag->msg_header.frag_len;
+        size_t frag_len = frag->msg_header.frag_len;
         pqueue_pop(s->d1->buffered_messages);
 
         al = dtls1_preprocess_fragment(s, &frag->msg_header);
@@ -496,33 +490,35 @@ static int dtls1_retrieve_buffered_fragment(SSL *s, int *ok)
         pitem_free(item);
 
         if (al == 0) {
-            *ok = 1;
-            return frag_len;
+            *len = frag_len;
+            return 1;
         }
 
         ssl3_send_alert(s, SSL3_AL_FATAL, al);
         s->init_num = 0;
-        *ok = 0;
-        return -1;
-    } else
         return 0;
+    } else {
+        return 0;
+    }
 }
 
 static int
-dtls1_reassemble_fragment(SSL *s, const struct hm_header_st *msg_hdr, int *ok)
+dtls1_reassemble_fragment(SSL *s, const struct hm_header_st *msg_hdr)
 {
     hm_fragment *frag = NULL;
     pitem *item = NULL;
     int i = -1, is_complete;
     unsigned char seq64be[8];
-    unsigned long frag_len = msg_hdr->frag_len;
+    size_t frag_len = msg_hdr->frag_len;
+    size_t readbytes;
 
     if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len ||
         msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
         goto err;
 
-    if (frag_len == 0)
+    if (frag_len == 0) {
         return DTLS1_HM_FRAGMENT_RETRY;
+    }
 
     /* Try to find item in queue */
     memset(seq64be, 0, sizeof(seq64be));
@@ -559,10 +555,10 @@ dtls1_reassemble_fragment(SSL *s, const struct hm_header_st *msg_hdr, int *ok)
                                           devnull,
                                           frag_len >
                                           sizeof(devnull) ? sizeof(devnull) :
-                                          frag_len, 0);
+                                          frag_len, 0, &readbytes);
             if (i <= 0)
                 goto err;
-            frag_len -= i;
+            frag_len -= readbytes;
         }
         return DTLS1_HM_FRAGMENT_RETRY;
     }
@@ -570,8 +566,8 @@ dtls1_reassemble_fragment(SSL *s, const struct hm_header_st *msg_hdr, int *ok)
     /* read the body of the fragment (header has already been read */
     i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
                                   frag->fragment + msg_hdr->frag_off,
-                                  frag_len, 0);
-    if ((unsigned long)i != frag_len)
+                                  frag_len, 0, &readbytes);
+    if (i <= 0 || readbytes != frag_len)
         i = -1;
     if (i <= 0)
         goto err;
@@ -609,19 +605,18 @@ dtls1_reassemble_fragment(SSL *s, const struct hm_header_st *msg_hdr, int *ok)
  err:
     if (item == NULL)
         dtls1_hm_fragment_free(frag);
-    *ok = 0;
-    return i;
+    return -1;
 }
 
 static int
-dtls1_process_out_of_seq_message(SSL *s, const struct hm_header_st *msg_hdr,
-                                 int *ok)
+dtls1_process_out_of_seq_message(SSL *s, const struct hm_header_st *msg_hdr)
 {
     int i = -1;
     hm_fragment *frag = NULL;
     pitem *item = NULL;
     unsigned char seq64be[8];
-    unsigned long frag_len = msg_hdr->frag_len;
+    size_t frag_len = msg_hdr->frag_len;
+    size_t readbytes;
 
     if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
         goto err;
@@ -654,14 +649,15 @@ dtls1_process_out_of_seq_message(SSL *s, const struct hm_header_st *msg_hdr,
                                           devnull,
                                           frag_len >
                                           sizeof(devnull) ? sizeof(devnull) :
-                                          frag_len, 0);
+                                          frag_len, 0, &readbytes);
             if (i <= 0)
                 goto err;
-            frag_len -= i;
+            frag_len -= readbytes;
         }
     } else {
-        if (frag_len != msg_hdr->msg_len)
-            return dtls1_reassemble_fragment(s, msg_hdr, ok);
+        if (frag_len != msg_hdr->msg_len) {
+            return dtls1_reassemble_fragment(s, msg_hdr);;
+        }
 
         if (frag_len > dtls1_max_handshake_message_len(s))
             goto err;
@@ -677,8 +673,9 @@ dtls1_process_out_of_seq_message(SSL *s, const struct hm_header_st *msg_hdr,
              * read the body of the fragment (header has already been read
              */
             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
-                                          frag->fragment, frag_len, 0);
-            if ((unsigned long)i != frag_len)
+                                          frag->fragment, frag_len, 0,
+                                          &readbytes);
+            if (i<=0 || readbytes != frag_len)
                 i = -1;
             if (i <= 0)
                 goto err;
@@ -705,33 +702,33 @@ dtls1_process_out_of_seq_message(SSL *s, const struct hm_header_st *msg_hdr,
  err:
     if (item == NULL)
         dtls1_hm_fragment_free(frag);
-    *ok = 0;
-    return i;
+    return 0;
 }
 
-static int dtls_get_reassembled_message(SSL *s, long *len)
+static int dtls_get_reassembled_message(SSL *s, int *errtype, size_t *len)
 {
     unsigned char wire[DTLS1_HM_HEADER_LENGTH];
-    unsigned long mlen, frag_off, frag_len;
+    size_t mlen, frag_off, frag_len;
     int i, al, recvd_type;
     struct hm_header_st msg_hdr;
-    int ok;
+    size_t readbytes;
+
+    *errtype = 0;
 
  redo:
     /* see if we have the required fragment already */
-    if ((frag_len = dtls1_retrieve_buffered_fragment(s, &ok)) || ok) {
-        if (ok)
-            s->init_num = frag_len;
+    if (dtls1_retrieve_buffered_fragment(s, &frag_len)) {
+        s->init_num = frag_len;
         *len = frag_len;
-        return ok;
+        return 1;
     }
 
     /* read handshake message header */
     i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type, wire,
-                                  DTLS1_HM_HEADER_LENGTH, 0);
+                                  DTLS1_HM_HEADER_LENGTH, 0, &readbytes);
     if (i <= 0) {               /* nbio, or an error */
         s->rwstate = SSL_READING;
-        *len = i;
+        *len = 0;
         return 0;
     }
     if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
@@ -742,17 +739,17 @@ static int dtls_get_reassembled_message(SSL *s, long *len)
             goto f_err;
         }
 
-        memcpy(s->init_buf->data, wire, i);
-        s->init_num = i - 1;
+        memcpy(s->init_buf->data, wire, readbytes);
+        s->init_num = readbytes - 1;
         s->init_msg = s->init_buf->data + 1;
         s->s3->tmp.message_type = SSL3_MT_CHANGE_CIPHER_SPEC;
-        s->s3->tmp.message_size = i - 1;
-        *len = i - 1;
+        s->s3->tmp.message_size = readbytes - 1;
+        *len = readbytes - 1;
         return 1;
     }
 
     /* Handshake fails if message header is incomplete */
-    if (i != DTLS1_HM_HEADER_LENGTH) {
+    if (readbytes != DTLS1_HM_HEADER_LENGTH) {
         al = SSL_AD_UNEXPECTED_MESSAGE;
         SSLerr(SSL_F_DTLS_GET_REASSEMBLED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
         goto f_err;
@@ -782,13 +779,13 @@ static int dtls_get_reassembled_message(SSL *s, long *len)
      * although we're still expecting seq 0 (ClientHello)
      */
     if (msg_hdr.seq != s->d1->handshake_read_seq) {
-        *len = dtls1_process_out_of_seq_message(s, &msg_hdr, &ok);
-        return ok;
+        *errtype = dtls1_process_out_of_seq_message(s, &msg_hdr);
+        return 0;
     }
 
     if (frag_len && frag_len < mlen) {
-        *len = dtls1_reassemble_fragment(s, &msg_hdr, &ok);
-        return ok;
+        *errtype = dtls1_reassemble_fragment(s, &msg_hdr);
+        return 0;
     }
 
     if (!s->server && s->d1->r_msg_hdr.frag_off == 0 &&
@@ -823,7 +820,7 @@ static int dtls_get_reassembled_message(SSL *s, long *len)
             (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
 
         i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
-                                      &p[frag_off], frag_len, 0);
+                                      &p[frag_off], frag_len, 0, &readbytes);
 
         /*
          * This shouldn't ever fail due to NBIO because we already checked
@@ -831,17 +828,18 @@ static int dtls_get_reassembled_message(SSL *s, long *len)
          */
         if (i <= 0) {
             s->rwstate = SSL_READING;
-            *len = i;
+            *len = 0;
             return 0;
         }
-    } else
-        i = 0;
+    } else {
+        readbytes = 0;
+    }
 
     /*
      * XDTLS: an incorrectly formatted fragment should cause the handshake
      * to fail
      */
-    if (i != (int)frag_len) {
+    if (readbytes != frag_len) {
         al = SSL3_AD_ILLEGAL_PARAMETER;
         SSLerr(SSL_F_DTLS_GET_REASSEMBLED_MESSAGE, SSL3_AD_ILLEGAL_PARAMETER);
         goto f_err;
@@ -859,7 +857,7 @@ static int dtls_get_reassembled_message(SSL *s, long *len)
  f_err:
     ssl3_send_alert(s, SSL3_AL_FATAL, al);
     s->init_num = 0;
-    *len = -1;
+    *len = 0;
     return 0;
 }
 
@@ -1116,8 +1114,8 @@ int dtls1_retransmit_message(SSL *s, unsigned short seq, int *found)
 }
 
 void dtls1_set_message_header(SSL *s,
-                              unsigned char mt, unsigned long len,
-                              unsigned long frag_off, unsigned long frag_len)
+                              unsigned char mt, size_t len,
+                              size_t frag_off, size_t frag_len)
 {
     if (frag_off == 0) {
         s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
@@ -1131,8 +1129,8 @@ void dtls1_set_message_header(SSL *s,
 /* don't actually do the writing, wait till the MTU has been retrieved */
 static void
 dtls1_set_message_header_int(SSL *s, unsigned char mt,
-                             unsigned long len, unsigned short seq_num,
-                             unsigned long frag_off, unsigned long frag_len)
+                             size_t len, unsigned short seq_num,
+                             size_t frag_off, size_t frag_len)
 {
     struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
 
@@ -1144,7 +1142,7 @@ dtls1_set_message_header_int(SSL *s, unsigned char mt,
 }
 
 static void
-dtls1_fix_message_header(SSL *s, unsigned long frag_off, unsigned long frag_len)
+dtls1_fix_message_header(SSL *s, size_t frag_off, size_t frag_len)
 {
     struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
 
diff --git a/ssl/statem/statem_lib.c b/ssl/statem/statem_lib.c
index a3d8d1e..990510a 100644
--- a/ssl/statem/statem_lib.c
+++ b/ssl/statem/statem_lib.c
@@ -30,9 +30,10 @@
 int ssl3_do_write(SSL *s, int type)
 {
     int ret;
+    size_t written = 0;
 
     ret = ssl3_write_bytes(s, type, &s->init_buf->data[s->init_off],
-                           s->init_num);
+                           s->init_num, &written);
     if (ret < 0)
         return (-1);
     if (type == SSL3_RT_HANDSHAKE)
@@ -42,18 +43,18 @@ int ssl3_do_write(SSL *s, int type)
          */
         if (!ssl3_finish_mac(s,
                              (unsigned char *)&s->init_buf->data[s->init_off],
-                             ret))
+                             written))
             return -1;
 
-    if (ret == s->init_num) {
+    if (written == s->init_num) {
         if (s->msg_callback)
             s->msg_callback(1, s->version, type, s->init_buf->data,
                             (size_t)(s->init_off + s->init_num), s,
                             s->msg_callback_arg);
         return (1);
     }
-    s->init_off += ret;
-    s->init_num -= ret;
+    s->init_off += written;
+    s->init_num -= written;
     return (0);
 }
 
@@ -73,9 +74,9 @@ int tls_close_construct_packet(SSL *s, WPACKET *pkt, int htype)
 
 int tls_construct_finished(SSL *s, WPACKET *pkt)
 {
-    int i;
+    size_t finish_md_len;
     const char *sender;
-    int slen;
+    size_t slen;
 
     if (s->server) {
         sender = s->method->ssl3_enc->server_finished_label;
@@ -85,17 +86,17 @@ int tls_construct_finished(SSL *s, WPACKET *pkt)
         slen = s->method->ssl3_enc->client_finished_label_len;
     }
 
-    i = s->method->ssl3_enc->final_finish_mac(s,
-                                              sender, slen,
-                                              s->s3->tmp.finish_md);
-    if (i <= 0) {
+    finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
+                                                          sender, slen,
+                                                          s->s3->tmp.finish_md);
+    if (finish_md_len == 0) {
         SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
         goto err;
     }
 
-    s->s3->tmp.finish_md_len = i;
+    s->s3->tmp.finish_md_len = finish_md_len;
 
-    if (!WPACKET_memcpy(pkt, s->s3->tmp.finish_md, i)) {
+    if (!WPACKET_memcpy(pkt, s->s3->tmp.finish_md, finish_md_len)) {
         SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
         goto err;
     }
@@ -104,13 +105,15 @@ int tls_construct_finished(SSL *s, WPACKET *pkt)
      * Copy the finished so we can use it for renegotiation checks
      */
     if (!s->server) {
-        OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
-        memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md, i);
-        s->s3->previous_client_finished_len = i;
+        OPENSSL_assert(finish_md_len <= EVP_MAX_MD_SIZE);
+        memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md,
+               finish_md_len);
+        s->s3->previous_client_finished_len = finish_md_len;
     } else {
-        OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
-        memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md, i);
-        s->s3->previous_server_finished_len = i;
+        OPENSSL_assert(finish_md_len <= EVP_MAX_MD_SIZE);
+        memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md,
+               finish_md_len);
+        s->s3->previous_server_finished_len = finish_md_len;
     }
 
     return 1;
@@ -127,7 +130,7 @@ int tls_construct_finished(SSL *s, WPACKET *pkt)
 static void ssl3_take_mac(SSL *s)
 {
     const char *sender;
-    int slen;
+    size_t slen;
     /*
      * If no new cipher setup return immediately: other functions will set
      * the appropriate error.
@@ -152,7 +155,7 @@ static void ssl3_take_mac(SSL *s)
 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
 {
     int al;
-    long remain;
+    size_t remain;
 
     remain = PACKET_remaining(pkt);
     /*
@@ -218,7 +221,8 @@ MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
 
 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
 {
-    int al, i;
+    int al;
+    size_t md_len;
 
     /* If this occurs, we have missed a message */
     if (!s->s3->change_cipher_spec) {
@@ -228,15 +232,16 @@ MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
     }
     s->s3->change_cipher_spec = 0;
 
-    i = s->s3->tmp.peer_finish_md_len;
+    md_len = s->s3->tmp.peer_finish_md_len;
 
-    if ((unsigned long)i != PACKET_remaining(pkt)) {
+    if (md_len != PACKET_remaining(pkt)) {
         al = SSL_AD_DECODE_ERROR;
         SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_BAD_DIGEST_LENGTH);
         goto f_err;
     }
 
-    if (CRYPTO_memcmp(PACKET_data(pkt), s->s3->tmp.peer_finish_md, i) != 0) {
+    if (CRYPTO_memcmp(PACKET_data(pkt), s->s3->tmp.peer_finish_md,
+                      md_len) != 0) {
         al = SSL_AD_DECRYPT_ERROR;
         SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_DIGEST_CHECK_FAILED);
         goto f_err;
@@ -246,13 +251,15 @@ MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
      * Copy the finished so we can use it for renegotiation checks
      */
     if (s->server) {
-        OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
-        memcpy(s->s3->previous_client_finished, s->s3->tmp.peer_finish_md, i);
-        s->s3->previous_client_finished_len = i;
+        OPENSSL_assert(md_len <= EVP_MAX_MD_SIZE);
+        memcpy(s->s3->previous_client_finished, s->s3->tmp.peer_finish_md,
+               md_len);
+        s->s3->previous_client_finished_len = md_len;
     } else {
-        OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
-        memcpy(s->s3->previous_server_finished, s->s3->tmp.peer_finish_md, i);
-        s->s3->previous_server_finished_len = i;
+        OPENSSL_assert(md_len <= EVP_MAX_MD_SIZE);
+        memcpy(s->s3->previous_server_finished, s->s3->tmp.peer_finish_md,
+               md_len);
+        s->s3->previous_server_finished_len = md_len;
     }
 
     return MSG_PROCESS_FINISHED_READING;
@@ -357,7 +364,7 @@ int tls_get_message_header(SSL *s, int *mt)
     /* s->init_num < SSL3_HM_HEADER_LENGTH */
     int skip_message, i, recvd_type, al;
     unsigned char *p;
-    unsigned long l;
+    size_t l, readbytes;
 
     p = (unsigned char *)s->init_buf->data;
 
@@ -366,7 +373,7 @@ int tls_get_message_header(SSL *s, int *mt)
             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
                                           &p[s->init_num],
                                           SSL3_HM_HEADER_LENGTH - s->init_num,
-                                          0);
+                                          0, &readbytes);
             if (i <= 0) {
                 s->rwstate = SSL_READING;
                 return 0;
@@ -376,22 +383,22 @@ int tls_get_message_header(SSL *s, int *mt)
                  * A ChangeCipherSpec must be a single byte and may not occur
                  * in the middle of a handshake message.
                  */
-                if (s->init_num != 0 || i != 1 || p[0] != SSL3_MT_CCS) {
+                if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
                     al = SSL_AD_UNEXPECTED_MESSAGE;
                     SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER,
                            SSL_R_BAD_CHANGE_CIPHER_SPEC);
                     goto f_err;
                 }
                 s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
-                s->init_num = i - 1;
-                s->s3->tmp.message_size = i;
+                s->init_num = readbytes - 1;
+                s->s3->tmp.message_size = readbytes;
                 return 1;
             } else if (recvd_type != SSL3_RT_HANDSHAKE) {
                 al = SSL_AD_UNEXPECTED_MESSAGE;
                 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_CCS_RECEIVED_EARLY);
                 goto f_err;
             }
-            s->init_num += i;
+            s->init_num += readbytes;
         }
 
         skip_message = 0;
@@ -452,9 +459,9 @@ int tls_get_message_header(SSL *s, int *mt)
     return 0;
 }
 
-int tls_get_message_body(SSL *s, unsigned long *len)
+int tls_get_message_body(SSL *s, size_t *len)
 {
-    long n;
+    size_t n, readbytes;
     unsigned char *p;
     int i;
 
@@ -468,14 +475,14 @@ int tls_get_message_body(SSL *s, unsigned long *len)
     n = s->s3->tmp.message_size - s->init_num;
     while (n > 0) {
         i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
-                                      &p[s->init_num], n, 0);
+                                      &p[s->init_num], n, 0, &readbytes);
         if (i <= 0) {
             s->rwstate = SSL_READING;
             *len = 0;
             return 0;
         }
-        s->init_num += i;
-        n -= i;
+        s->init_num += readbytes;
+        n -= readbytes;
     }
 
 #ifndef OPENSSL_NO_NEXTPROTONEG
@@ -513,17 +520,7 @@ int tls_get_message_body(SSL *s, unsigned long *len)
                             s->msg_callback_arg);
     }
 
-    /*
-     * init_num should never be negative...should probably be declared
-     * unsigned
-     */
-    if (s->init_num < 0) {
-        SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_INTERNAL_ERROR);
-        ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
-        *len = 0;
-        return 0;
-    }
-    *len = (unsigned long)s->init_num;
+    *len = s->init_num;
     return 1;
 }
 
diff --git a/ssl/statem/statem_locl.h b/ssl/statem/statem_locl.h
index 6b57b25..a360fc9 100644
--- a/ssl/statem/statem_locl.h
+++ b/ssl/statem/statem_locl.h
@@ -54,7 +54,7 @@ WORK_STATE ossl_statem_client_pre_work(SSL *s, WORK_STATE wst);
 WORK_STATE ossl_statem_client_post_work(SSL *s, WORK_STATE wst);
 int ossl_statem_client_construct_message(SSL *s, WPACKET *pkt,
                                          confunc_f *confunc, int *mt);
-unsigned long ossl_statem_client_max_message_size(SSL *s);
+size_t ossl_statem_client_max_message_size(SSL *s);
 MSG_PROCESS_RETURN ossl_statem_client_process_message(SSL *s, PACKET *pkt);
 WORK_STATE ossl_statem_client_post_process_message(SSL *s, WORK_STATE wst);
 
@@ -67,14 +67,14 @@ WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst);
 WORK_STATE ossl_statem_server_post_work(SSL *s, WORK_STATE wst);
 int ossl_statem_server_construct_message(SSL *s, WPACKET *pkt,
                                          confunc_f *confunc,int *mt);
-unsigned long ossl_statem_server_max_message_size(SSL *s);
+size_t ossl_statem_server_max_message_size(SSL *s);
 MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL *s, PACKET *pkt);
 WORK_STATE ossl_statem_server_post_process_message(SSL *s, WORK_STATE wst);
 
 /* Functions for getting new message data */
 __owur int tls_get_message_header(SSL *s, int *mt);
-__owur int tls_get_message_body(SSL *s, unsigned long *len);
-__owur int dtls_get_message(SSL *s, int *mt, unsigned long *len);
+__owur int tls_get_message_body(SSL *s, size_t *len);
+__owur int dtls_get_message(SSL *s, int *mt, size_t *len);
 
 /* Message construction and processing functions */
 __owur MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt);
diff --git a/ssl/statem/statem_srvr.c b/ssl/statem/statem_srvr.c
index 009d06c..6aa897b 100644
--- a/ssl/statem/statem_srvr.c
+++ b/ssl/statem/statem_srvr.c
@@ -717,7 +717,7 @@ int ossl_statem_server_construct_message(SSL *s, WPACKET *pkt,
  * Returns the maximum allowed length for the current message that we are
  * reading. Excludes the message header.
  */
-unsigned long ossl_statem_server_max_message_size(SSL *s)
+size_t ossl_statem_server_max_message_size(SSL *s)
 {
     OSSL_STATEM *st = &s->statem;
 
@@ -853,7 +853,7 @@ static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
 #endif
 
 int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,
-                                  unsigned char cookie_len)
+                                  size_t cookie_len)
 {
     /* Always use DTLS 1.0 version: see RFC 6347 */
     if (!WPACKET_put_bytes_u16(pkt, DTLS1_VERSION)
@@ -865,14 +865,16 @@ int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,
 
 int dtls_construct_hello_verify_request(SSL *s, WPACKET *pkt)
 {
+    unsigned int cookie_leni;
     if (s->ctx->app_gen_cookie_cb == NULL ||
         s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
-                                  &(s->d1->cookie_len)) == 0 ||
-        s->d1->cookie_len > 255) {
+                                  &cookie_leni) == 0 ||
+        cookie_leni > 255) {
         SSLerr(SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST,
                SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
         return 0;
     }
+    s->d1->cookie_len = cookie_leni;
 
     if (!dtls_raw_hello_verify_request(pkt, s->d1->cookie,
                                               s->d1->cookie_len)) {
@@ -886,7 +888,8 @@ int dtls_construct_hello_verify_request(SSL *s, WPACKET *pkt)
 MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
 {
     int i, al = SSL_AD_INTERNAL_ERROR;
-    unsigned int j, complen = 0;
+    unsigned int j;
+    size_t loop, complen = 0;
     unsigned long id;
     const SSL_CIPHER *c;
 #ifndef OPENSSL_NO_COMP
@@ -1085,8 +1088,7 @@ MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
         if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
             if (s->ctx->app_verify_cookie_cb != NULL) {
                 if (s->ctx->app_verify_cookie_cb(s, PACKET_data(&cookie),
-                                                 PACKET_remaining(&cookie)) ==
-                    0) {
+                        (unsigned int)PACKET_remaining(&cookie)) == 0) {
                     al = SSL_AD_HANDSHAKE_FAILURE;
                     SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
                            SSL_R_COOKIE_MISMATCH);
@@ -1195,12 +1197,12 @@ MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
     }
 
     complen = PACKET_remaining(&compression);
-    for (j = 0; j < complen; j++) {
-        if (PACKET_data(&compression)[j] == 0)
+    for (loop = 0; loop < complen; loop++) {
+        if (PACKET_data(&compression)[loop] == 0)
             break;
     }
 
-    if (j >= complen) {
+    if (loop >= complen) {
         /* no compress */
         al = SSL_AD_DECODE_ERROR;
         SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
@@ -1231,12 +1233,19 @@ MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
 
     if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
         const SSL_CIPHER *pref_cipher = NULL;
+        /*
+         * s->session->master_key_length is a size_t, but this is an int for
+         * backwards compat reasons
+         */
+        int master_key_length;
 
-        s->session->master_key_length = sizeof(s->session->master_key);
+        master_key_length = sizeof(s->session->master_key);
         if (s->tls_session_secret_cb(s, s->session->master_key,
-                                     &s->session->master_key_length, ciphers,
+                                     &master_key_length, ciphers,
                                      &pref_cipher,
-                                     s->tls_session_secret_cb_arg)) {
+                                     s->tls_session_secret_cb_arg)
+                && master_key_length > 0) {
+            s->session->master_key_length = master_key_length;
             s->hit = 1;
             s->session->ciphers = ciphers;
             s->session->verify_result = X509_V_OK;
@@ -1484,8 +1493,8 @@ WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
 
 int tls_construct_server_hello(SSL *s, WPACKET *pkt)
 {
-    int sl, compm, al = SSL_AD_INTERNAL_ERROR;
-    size_t len;
+    int compm, al = SSL_AD_INTERNAL_ERROR;
+    size_t sl, len;
 
     if (!WPACKET_put_bytes_u16(pkt, s->version)
                /*
@@ -1519,7 +1528,7 @@ int tls_construct_server_hello(SSL *s, WPACKET *pkt)
         s->session->session_id_length = 0;
 
     sl = s->session->session_id_length;
-    if (sl > (int)sizeof(s->session->session_id)) {
+    if (sl > sizeof(s->session->session_id)) {
         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
         goto err;
     }
@@ -1567,7 +1576,7 @@ int tls_construct_server_key_exchange(SSL *s, WPACKET *pkt)
 #endif
 #ifndef OPENSSL_NO_EC
     unsigned char *encodedPoint = NULL;
-    int encodedlen = 0;
+    size_t encodedlen = 0;
     int curve_id = 0;
 #endif
     EVP_PKEY *pkey;
@@ -1900,7 +1909,7 @@ int tls_construct_server_key_exchange(SSL *s, WPACKET *pkt)
 
 int tls_construct_certificate_request(SSL *s, WPACKET *pkt)
 {
-    int i, nl;
+    int i;
     STACK_OF(X509_NAME) *sk = NULL;
 
     /* get the list of acceptable cert types */
@@ -1913,7 +1922,7 @@ int tls_construct_certificate_request(SSL *s, WPACKET *pkt)
 
     if (SSL_USE_SIGALGS(s)) {
         const unsigned char *psigs;
-        nl = tls12_get_psigalgs(s, &psigs);
+        size_t nl = tls12_get_psigalgs(s, &psigs);
         if (!WPACKET_start_sub_packet_u16(pkt)
                 || !tls12_copy_sigalgs(s, pkt, psigs, nl)
                 || !WPACKET_close(pkt)) {
@@ -2094,9 +2103,10 @@ static int tls_process_cke_rsa(SSL *s, PACKET *pkt, int *al)
      * Decrypt with no padding. PKCS#1 padding will be removed as part of
      * the timing-sensitive code below.
      */
-    decrypt_len = RSA_private_decrypt(PACKET_remaining(&enc_premaster),
-                                      PACKET_data(&enc_premaster),
-                                      rsa_decrypt, rsa, RSA_NO_PADDING);
+     /* TODO(size_t): Convert this function */
+    decrypt_len = (int)RSA_private_decrypt((int)PACKET_remaining(&enc_premaster),
+                                           PACKET_data(&enc_premaster),
+                                           rsa_decrypt, rsa, RSA_NO_PADDING);
     if (decrypt_len < 0)
         goto err;
 
@@ -2377,7 +2387,7 @@ static int tls_process_cke_gost(SSL *s, PACKET *pkt, int *al)
     unsigned long alg_a;
     int Ttag, Tclass;
     long Tlen;
-    long sess_key_len;
+    size_t sess_key_len;
     const unsigned char *data;
     int ret = 0;
 
@@ -2427,8 +2437,9 @@ static int tls_process_cke_gost(SSL *s, PACKET *pkt, int *al)
         SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
         goto err;
     }
+    /* TODO(size_t): Convert this function */
     if (ASN1_get_object((const unsigned char **)&data, &Tlen, &Ttag,
-                        &Tclass, sess_key_len) != V_ASN1_CONSTRUCTED
+                        &Tclass, (long)sess_key_len) != V_ASN1_CONSTRUCTED
         || Ttag != V_ASN1_SEQUENCE || Tclass != V_ASN1_UNIVERSAL) {
         *al = SSL_AD_DECODE_ERROR;
         SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, SSL_R_DECRYPTION_FAILED);
@@ -2730,7 +2741,7 @@ MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
 
     if (s->version == SSL3_VERSION
         && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
-                            s->session->master_key_length,
+                            (int)s->session->master_key_length,
                             s->session->master_key)) {
         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
         al = SSL_AD_INTERNAL_ERROR;
diff --git a/ssl/t1_enc.c b/ssl/t1_enc.c
index 4aa5ddd..8d1e350 100644
--- a/ssl/t1_enc.c
+++ b/ssl/t1_enc.c
@@ -43,19 +43,18 @@
 
 /* seed1 through seed5 are concatenated */
 static int tls1_PRF(SSL *s,
-                    const void *seed1, int seed1_len,
-                    const void *seed2, int seed2_len,
-                    const void *seed3, int seed3_len,
-                    const void *seed4, int seed4_len,
-                    const void *seed5, int seed5_len,
-                    const unsigned char *sec, int slen,
-                    unsigned char *out, int olen)
+                    const void *seed1, size_t seed1_len,
+                    const void *seed2, size_t seed2_len,
+                    const void *seed3, size_t seed3_len,
+                    const void *seed4, size_t seed4_len,
+                    const void *seed5, size_t seed5_len,
+                    const unsigned char *sec, size_t slen,
+                    unsigned char *out, size_t olen)
 {
     const EVP_MD *md = ssl_prf_md(s);
     EVP_PKEY_CTX *pctx = NULL;
 
     int ret = 0;
-    size_t outlen = olen;
 
     if (md == NULL) {
         /* Should never happen */
@@ -65,21 +64,21 @@ static int tls1_PRF(SSL *s,
     pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1_PRF, NULL);
     if (pctx == NULL || EVP_PKEY_derive_init(pctx) <= 0
         || EVP_PKEY_CTX_set_tls1_prf_md(pctx, md) <= 0
-        || EVP_PKEY_CTX_set1_tls1_prf_secret(pctx, sec, slen) <= 0)
+        || EVP_PKEY_CTX_set1_tls1_prf_secret(pctx, sec, (int)slen) <= 0)
         goto err;
 
-    if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed1, seed1_len) <= 0)
+    if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed1, (int)seed1_len) <= 0)
         goto err;
-    if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed2, seed2_len) <= 0)
+    if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed2, (int)seed2_len) <= 0)
         goto err;
-    if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed3, seed3_len) <= 0)
+    if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed3, (int)seed3_len) <= 0)
         goto err;
-    if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed4, seed4_len) <= 0)
+    if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed4, (int)seed4_len) <= 0)
         goto err;
-    if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed5, seed5_len) <= 0)
+    if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed5, (int)seed5_len) <= 0)
         goto err;
 
-    if (EVP_PKEY_derive(pctx, out, &outlen) <= 0)
+    if (EVP_PKEY_derive(pctx, out, &olen) <= 0)
         goto err;
     ret = 1;
 
@@ -88,7 +87,7 @@ static int tls1_PRF(SSL *s,
     return ret;
 }
 
-static int tls1_generate_key_block(SSL *s, unsigned char *km, int num)
+static int tls1_generate_key_block(SSL *s, unsigned char *km, size_t num)
 {
     int ret;
     ret = tls1_PRF(s,
@@ -116,10 +115,10 @@ int tls1_change_cipher_state(SSL *s, int which)
 #endif
     const EVP_MD *m;
     int mac_type;
-    int *mac_secret_size;
+    size_t *mac_secret_size;
     EVP_MD_CTX *mac_ctx;
     EVP_PKEY *mac_key;
-    int n, i, j, k, cl;
+    size_t n, i, j, k, cl;
     int reuse_dd = 0;
 
     c = s->s3->tmp.new_sym_enc;
@@ -214,6 +213,7 @@ int tls1_change_cipher_state(SSL *s, int which)
     p = s->s3->tmp.key_block;
     i = *mac_secret_size = s->s3->tmp.new_mac_secret_size;
 
+    /* TODO(size_t): convert me */
     cl = EVP_CIPHER_key_length(c);
     j = cl;
     /* Was j=(exp)?5:EVP_CIPHER_key_length(c); */
@@ -250,8 +250,9 @@ int tls1_change_cipher_state(SSL *s, int which)
     memcpy(mac_secret, ms, i);
 
     if (!(EVP_CIPHER_flags(c) & EVP_CIPH_FLAG_AEAD_CIPHER)) {
+        /* TODO(size_t): Convert this function */
         mac_key = EVP_PKEY_new_mac_key(mac_type, NULL,
-                                       mac_secret, *mac_secret_size);
+                                       mac_secret, (int)*mac_secret_size);
         if (mac_key == NULL
             || EVP_DigestSignInit(mac_ctx, NULL, m, NULL, mac_key) <= 0) {
             EVP_PKEY_free(mac_key);
@@ -263,7 +264,7 @@ int tls1_change_cipher_state(SSL *s, int which)
 #ifdef SSL_DEBUG
     printf("which = %04X\nmac key=", which);
     {
-        int z;
+        size_t z;
         for (z = 0; z < i; z++)
             printf("%02X%c", ms[z], ((z + 1) % 16) ? ' ' : '\n');
     }
@@ -271,7 +272,8 @@ int tls1_change_cipher_state(SSL *s, int which)
 
     if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE) {
         if (!EVP_CipherInit_ex(dd, c, NULL, key, NULL, (which & SSL3_CC_WRITE))
-            || !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_GCM_SET_IV_FIXED, k, iv)) {
+            || !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_GCM_SET_IV_FIXED, (int)k,
+                                    iv)) {
             SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
             goto err2;
         }
@@ -285,7 +287,7 @@ int tls1_change_cipher_state(SSL *s, int which)
         if (!EVP_CipherInit_ex(dd, c, NULL, NULL, NULL, (which & SSL3_CC_WRITE))
             || !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_IVLEN, 12, NULL)
             || !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_TAG, taglen, NULL)
-            || !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_CCM_SET_IV_FIXED, k, iv)
+            || !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_CCM_SET_IV_FIXED, (int)k, iv)
             || !EVP_CipherInit_ex(dd, NULL, NULL, key, NULL, -1)) {
             SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
             goto err2;
@@ -299,7 +301,7 @@ int tls1_change_cipher_state(SSL *s, int which)
     /* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
     if ((EVP_CIPHER_flags(c) & EVP_CIPH_FLAG_AEAD_CIPHER) && *mac_secret_size
         && !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_MAC_KEY,
-                                *mac_secret_size, mac_secret)) {
+                                (int)*mac_secret_size, mac_secret)) {
         SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
         goto err2;
     }
@@ -332,7 +334,7 @@ int tls1_change_cipher_state(SSL *s, int which)
     }
     printf("\niv=");
     {
-        int z;
+        size_t z;
         for (z = 0; z < k; z++)
             printf("%02X%c", iv[z], ((z + 1) % 16) ? ' ' : '\n');
     }
@@ -359,9 +361,9 @@ int tls1_setup_key_block(SSL *s)
     unsigned char *p;
     const EVP_CIPHER *c;
     const EVP_MD *hash;
-    int num;
     SSL_COMP *comp;
-    int mac_type = NID_undef, mac_secret_size = 0;
+    int mac_type = NID_undef;
+    size_t num, mac_secret_size = 0;
     int ret = 0;
 
     if (s->s3->tmp.key_block_length != 0)
@@ -408,7 +410,7 @@ int tls1_setup_key_block(SSL *s)
     }
     printf("master key\n");
     {
-        int z;
+        size_t z;
         for (z = 0; z < s->session->master_key_length; z++)
             printf("%02X%c", s->session->master_key[z],
                    ((z + 1) % 16) ? ' ' : '\n');
@@ -419,7 +421,7 @@ int tls1_setup_key_block(SSL *s)
 #ifdef SSL_DEBUG
     printf("\nkey block\n");
     {
-        int z;
+        size_t z;
         for (z = 0; z < num; z++)
             printf("%02X%c", p[z], ((z + 1) % 16) ? ' ' : '\n');
     }
@@ -449,17 +451,16 @@ int tls1_setup_key_block(SSL *s)
     return (ret);
 }
 
-int tls1_final_finish_mac(SSL *s, const char *str, int slen, unsigned char *out)
+size_t tls1_final_finish_mac(SSL *s, const char *str, size_t slen,
+                             unsigned char *out)
 {
-    int hashlen;
+    size_t hashlen;
     unsigned char hash[EVP_MAX_MD_SIZE];
 
     if (!ssl3_digest_cached_records(s, 0))
         return 0;
 
-    hashlen = ssl_handshake_hash(s, hash, sizeof(hash));
-
-    if (hashlen == 0)
+    if (!ssl_handshake_hash(s, hash, sizeof(hash), &hashlen))
         return 0;
 
     if (!tls1_PRF(s, str, slen, hash, hashlen, NULL, 0, NULL, 0, NULL, 0,
@@ -471,19 +472,20 @@ int tls1_final_finish_mac(SSL *s, const char *str, int slen, unsigned char *out)
 }
 
 int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
-                                int len)
+                                size_t len, size_t *secret_size)
 {
     if (s->session->flags & SSL_SESS_FLAG_EXTMS) {
         unsigned char hash[EVP_MAX_MD_SIZE * 2];
-        int hashlen;
+        size_t hashlen;
         /*
          * Digest cached records keeping record buffer (if present): this wont
          * affect client auth because we're freezing the buffer at the same
          * point (after client key exchange and before certificate verify)
          */
         if (!ssl3_digest_cached_records(s, 1))
-            return -1;
-        hashlen = ssl_handshake_hash(s, hash, sizeof(hash));
+            return 0;
+        if(!ssl_handshake_hash(s, hash, sizeof(hash), &hashlen))
+            return 0;
 #ifdef SSL_DEBUG
         fprintf(stderr, "Handshake hashes:\n");
         BIO_dump_fp(stderr, (char *)hash, hashlen);
@@ -535,7 +537,8 @@ int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
     }
 #endif
 
-    return (SSL3_MASTER_SECRET_SIZE);
+    *secret_size = SSL3_MASTER_SECRET_SIZE;
+    return 1;
 }
 
 int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
diff --git a/ssl/t1_lib.c b/ssl/t1_lib.c
index e19f93d..0523e54 100644
--- a/ssl/t1_lib.c
+++ b/ssl/t1_lib.c
@@ -20,8 +20,8 @@
 #include "ssl_locl.h"
 #include <openssl/ct.h>
 
-static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen,
-                              const unsigned char *sess_id, int sesslen,
+static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, size_t ticklen,
+                              const unsigned char *sess_id, size_t sesslen,
                               SSL_SESSION **psess);
 static int ssl_check_clienthello_tlsext_early(SSL *s);
 static int ssl_check_serverhello_tlsext(SSL *s);
@@ -33,13 +33,11 @@ SSL3_ENC_METHOD const TLSv1_enc_data = {
     tls1_generate_master_secret,
     tls1_change_cipher_state,
     tls1_final_finish_mac,
-    TLS1_FINISH_MAC_LENGTH,
     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
     tls1_alert_code,
     tls1_export_keying_material,
     0,
-    SSL3_HM_HEADER_LENGTH,
     ssl3_set_handshake_header,
     tls_close_construct_packet,
     ssl3_handshake_write
@@ -52,13 +50,11 @@ SSL3_ENC_METHOD const TLSv1_1_enc_data = {
     tls1_generate_master_secret,
     tls1_change_cipher_state,
     tls1_final_finish_mac,
-    TLS1_FINISH_MAC_LENGTH,
     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
     tls1_alert_code,
     tls1_export_keying_material,
     SSL_ENC_FLAG_EXPLICIT_IV,
-    SSL3_HM_HEADER_LENGTH,
     ssl3_set_handshake_header,
     tls_close_construct_packet,
     ssl3_handshake_write
@@ -71,14 +67,12 @@ SSL3_ENC_METHOD const TLSv1_2_enc_data = {
     tls1_generate_master_secret,
     tls1_change_cipher_state,
     tls1_final_finish_mac,
-    TLS1_FINISH_MAC_LENGTH,
     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
     tls1_alert_code,
     tls1_export_keying_material,
     SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS | SSL_ENC_FLAG_SHA256_PRF
         | SSL_ENC_FLAG_TLS1_2_CIPHERS,
-    SSL3_HM_HEADER_LENGTH,
     ssl3_set_handshake_header,
     tls_close_construct_packet,
     ssl3_handshake_write
@@ -91,14 +85,12 @@ SSL3_ENC_METHOD const TLSv1_3_enc_data = {
     tls1_generate_master_secret,
     tls1_change_cipher_state,
     tls1_final_finish_mac,
-    TLS1_FINISH_MAC_LENGTH,
     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
     tls1_alert_code,
     tls1_export_keying_material,
     SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS | SSL_ENC_FLAG_SHA256_PRF
         | SSL_ENC_FLAG_TLS1_2_CIPHERS,
-    SSL3_HM_HEADER_LENGTH,
     ssl3_set_handshake_header,
     tls_close_construct_packet,
     ssl3_handshake_write
@@ -254,7 +246,7 @@ int tls1_ec_nid2curve_id(int nid)
     size_t i;
     for (i = 0; i < OSSL_NELEM(nid_list); i++) {
         if (nid_list[i].nid == nid)
-            return i + 1;
+            return (int)(i + 1);
     }
     return 0;
 }
@@ -1159,7 +1151,7 @@ int ssl_add_clienthello_tlsext(SSL *s, WPACKET *pkt, int *al)
 #endif                          /* OPENSSL_NO_EC */
 
     if (tls_use_ticket(s)) {
-        int ticklen;
+        size_t ticklen;
         if (!s->new_session && s->session && s->session->tlsext_tick)
             ticklen = s->session->tlsext_ticklen;
         else if (s->session && s->tlsext_session_ticket &&
@@ -1671,7 +1663,7 @@ static int tls1_alpn_handle_client_hello_late(SSL *s, int *al)
     if (s->ctx->alpn_select_cb != NULL && s->s3->alpn_proposed != NULL) {
         int r = s->ctx->alpn_select_cb(s, &selected, &selected_len,
                                        s->s3->alpn_proposed,
-                                       s->s3->alpn_proposed_len,
+                                       (unsigned int)s->s3->alpn_proposed_len,
                                        s->ctx->alpn_select_cb_arg);
 
         if (r == SSL_TLSEXT_ERR_OK) {
@@ -1833,7 +1825,7 @@ static int ssl_scan_clienthello_tlsext(SSL *s, PACKET *pkt, int *al)
 
         if (s->tlsext_debug_cb)
             s->tlsext_debug_cb(s, 0, type, PACKET_data(&extension),
-                               PACKET_remaining(&extension),
+                               (int)PACKET_remaining(&extension),
                                s->tlsext_debug_arg);
 
         if (type == TLSEXT_TYPE_renegotiate) {
@@ -1985,7 +1977,7 @@ static int ssl_scan_clienthello_tlsext(SSL *s, PACKET *pkt, int *al)
         else if (type == TLSEXT_TYPE_session_ticket) {
             if (s->tls_session_ticket_ext_cb &&
                 !s->tls_session_ticket_ext_cb(s, PACKET_data(&extension),
-                                              PACKET_remaining(&extension),
+                                              (int)PACKET_remaining(&extension),
                                               s->tls_session_ticket_ext_cb_arg))
             {
                 *al = TLS1_AD_INTERNAL_ERROR;
@@ -2047,8 +2039,9 @@ static int ssl_scan_clienthello_tlsext(SSL *s, PACKET *pkt, int *al)
                     }
 
                     id_data = PACKET_data(&responder_id);
+                    /* TODO(size_t): Convert d2i_* to size_t */
                     id = d2i_OCSP_RESPID(NULL, &id_data,
-                                         PACKET_remaining(&responder_id));
+                                         (int)PACKET_remaining(&responder_id));
                     if (id == NULL)
                         return 0;
 
@@ -2074,7 +2067,7 @@ static int ssl_scan_clienthello_tlsext(SSL *s, PACKET *pkt, int *al)
                                                X509_EXTENSION_free);
                     s->tlsext_ocsp_exts =
                         d2i_X509_EXTENSIONS(NULL, &ext_data,
-                                            PACKET_remaining(&exts));
+                                            (int)PACKET_remaining(&exts));
                     if (s->tlsext_ocsp_exts == NULL
                         || ext_data != PACKET_end(&exts)) {
                         return 0;
@@ -2765,7 +2758,7 @@ int ssl_check_serverhello_tlsext(SSL *s)
      */
     OPENSSL_free(s->tlsext_ocsp_resp);
     s->tlsext_ocsp_resp = NULL;
-    s->tlsext_ocsp_resplen = -1;
+    s->tlsext_ocsp_resplen = 0;
 
     switch (ret) {
     case SSL_TLSEXT_ERR_ALERT_FATAL:
@@ -2963,13 +2956,14 @@ int tls_check_serverhello_tlsext_early(SSL *s, const PACKET *ext,
  *    4: same as 3, but the ticket needs to be renewed.
  */
 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick,
-                              int eticklen, const unsigned char *sess_id,
-                              int sesslen, SSL_SESSION **psess)
+                              size_t eticklen, const unsigned char *sess_id,
+                              size_t sesslen, SSL_SESSION **psess)
 {
     SSL_SESSION *sess;
     unsigned char *sdec;
     const unsigned char *p;
-    int slen, mlen, renew_ticket = 0, ret = -1;
+    int slen, renew_ticket = 0, ret = -1, declen;
+    size_t mlen;
     unsigned char tick_hmac[EVP_MAX_MD_SIZE];
     HMAC_CTX *hctx = NULL;
     EVP_CIPHER_CTX *ctx;
@@ -3018,7 +3012,7 @@ static int tls_decrypt_ticket(SSL *s, const unsigned char *etick,
      * checks on ticket.
      */
     mlen = HMAC_size(hctx);
-    if (mlen < 0) {
+    if (mlen == 0) {
         goto err;
     }
     /* Sanity check ticket length: must exceed keyname + IV + HMAC */
@@ -3043,17 +3037,18 @@ static int tls_decrypt_ticket(SSL *s, const unsigned char *etick,
     p = etick + 16 + EVP_CIPHER_CTX_iv_length(ctx);
     eticklen -= 16 + EVP_CIPHER_CTX_iv_length(ctx);
     sdec = OPENSSL_malloc(eticklen);
-    if (sdec == NULL || EVP_DecryptUpdate(ctx, sdec, &slen, p, eticklen) <= 0) {
+    if (sdec == NULL || EVP_DecryptUpdate(ctx, sdec, &slen, p,
+                                          (int)eticklen) <= 0) {
         EVP_CIPHER_CTX_free(ctx);
         OPENSSL_free(sdec);
         return -1;
     }
-    if (EVP_DecryptFinal(ctx, sdec + slen, &mlen) <= 0) {
+    if (EVP_DecryptFinal(ctx, sdec + slen, &declen) <= 0) {
         EVP_CIPHER_CTX_free(ctx);
         OPENSSL_free(sdec);
         return 2;
     }
-    slen += mlen;
+    slen += declen;
     EVP_CIPHER_CTX_free(ctx);
     ctx = NULL;
     p = sdec;
@@ -3334,9 +3329,9 @@ int tls12_copy_sigalgs(SSL *s, WPACKET *pkt,
 }
 
 /* Given preference and allowed sigalgs set shared sigalgs */
-static int tls12_shared_sigalgs(SSL *s, TLS_SIGALGS *shsig,
-                                const unsigned char *pref, size_t preflen,
-                                const unsigned char *allow, size_t allowlen)
+static size_t tls12_shared_sigalgs(SSL *s, TLS_SIGALGS *shsig,
+                                   const unsigned char *pref, size_t preflen,
+                                   const unsigned char *allow, size_t allowlen)
 {
     const unsigned char *ptmp, *atmp;
     size_t i, j, nmatch = 0;
@@ -3411,7 +3406,7 @@ static int tls1_set_shared_sigalgs(SSL *s)
 
 /* Set preferred digest for each key type */
 
-int tls1_save_sigalgs(SSL *s, const unsigned char *data, int dsize)
+int tls1_save_sigalgs(SSL *s, const unsigned char *data, size_t dsize)
 {
     CERT *c = s->cert;
     /* Extension ignored for inappropriate versions */
@@ -3498,7 +3493,8 @@ int SSL_get_sigalgs(SSL *s, int idx,
                     unsigned char *rsig, unsigned char *rhash)
 {
     const unsigned char *psig = s->s3->tmp.peer_sigalgs;
-    if (psig == NULL)
+    size_t numsigalgs = s->s3->tmp.peer_sigalgslen / 2;
+    if (psig == NULL || numsigalgs > INT_MAX)
         return 0;
     if (idx >= 0) {
         idx <<= 1;
@@ -3511,7 +3507,7 @@ int SSL_get_sigalgs(SSL *s, int idx,
             *rsig = psig[1];
         tls1_lookup_sigalg(phash, psign, psignhash, psig);
     }
-    return s->s3->tmp.peer_sigalgslen / 2;
+    return (int)numsigalgs;
 }
 
 int SSL_get_shared_sigalgs(SSL *s, int idx,
@@ -3519,7 +3515,8 @@ int SSL_get_shared_sigalgs(SSL *s, int idx,
                            unsigned char *rsig, unsigned char *rhash)
 {
     TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs;
-    if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen)
+    if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen
+            || s->cert->shared_sigalgslen > INT_MAX)
         return 0;
     shsigalgs += idx;
     if (phash)
@@ -3532,7 +3529,7 @@ int SSL_get_shared_sigalgs(SSL *s, int idx,
         *rsig = shsigalgs->rsign;
     if (rhash)
         *rhash = shsigalgs->rhash;
-    return s->cert->shared_sigalgslen;
+    return (int)s->cert->shared_sigalgslen;
 }
 
 #define MAX_SIGALGLEN   (TLSEXT_hash_num * TLSEXT_signature_num * 2)
@@ -3705,7 +3702,7 @@ int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
         /* idx == -2 means checking client certificate chains */
         if (idx == -2) {
             cpk = c->key;
-            idx = cpk - c->pkeys;
+            idx = (int)(cpk - c->pkeys);
         } else
             cpk = c->pkeys + idx;
         pvalid = s->s3->tmp.valid_flags + idx;
diff --git a/ssl/t1_reneg.c b/ssl/t1_reneg.c
index f3e01bb..492386e 100644
--- a/ssl/t1_reneg.c
+++ b/ssl/t1_reneg.c
@@ -71,9 +71,9 @@ int ssl_add_serverhello_renegotiate_ext(SSL *s, WPACKET *pkt)
  */
 int ssl_parse_serverhello_renegotiate_ext(SSL *s, PACKET *pkt, int *al)
 {
-    unsigned int expected_len = s->s3->previous_client_finished_len
+    size_t expected_len = s->s3->previous_client_finished_len
         + s->s3->previous_server_finished_len;
-    unsigned int ilen;
+    size_t ilen;
     const unsigned char *data;
 
     /* Check for logic errors */
@@ -81,7 +81,7 @@ int ssl_parse_serverhello_renegotiate_ext(SSL *s, PACKET *pkt, int *al)
     OPENSSL_assert(!expected_len || s->s3->previous_server_finished_len);
 
     /* Parse the length byte */
-    if (!PACKET_get_1(pkt, &ilen)) {
+    if (!PACKET_get_1_len(pkt, &ilen)) {
         SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_RENEGOTIATE_EXT,
                SSL_R_RENEGOTIATION_ENCODING_ERR);
         *al = SSL_AD_ILLEGAL_PARAMETER;
diff --git a/test/constant_time_test.c b/test/constant_time_test.c
index 3ee6a81..41587e2 100644
--- a/test/constant_time_test.c
+++ b/test/constant_time_test.c
@@ -9,6 +9,7 @@
 
 #include "internal/constant_time_locl.h"
 #include "e_os.h"
+#include <openssl/e_os2.h>
 
 #include <limits.h>
 #include <stdio.h>
@@ -18,6 +19,8 @@ static const unsigned int CONSTTIME_TRUE = (unsigned)(~0);
 static const unsigned int CONSTTIME_FALSE = 0;
 static const unsigned char CONSTTIME_TRUE_8 = 0xff;
 static const unsigned char CONSTTIME_FALSE_8 = 0;
+static const size_t CONSTTIME_TRUE_S = ~((size_t)0);
+static const size_t CONSTTIME_FALSE_S = 0;
 
 static int test_binary_op(unsigned int (*op) (unsigned int a, unsigned int b),
                           const char *op_name, unsigned int a, unsigned int b,
@@ -54,6 +57,25 @@ static int test_binary_op_8(unsigned
     return 0;
 }
 
+static int test_binary_op_s(size_t (*op) (size_t a, size_t b),
+                            const char *op_name, size_t a, size_t b,
+                            int is_true)
+{
+    size_t c = op(a, b);
+    if (is_true && c != CONSTTIME_TRUE_S) {
+        fprintf(stderr, "Test failed for %s(%"OSSLzu", %"OSSLzu
+        "): expected %"OSSLzu" (TRUE), got %"OSSLzu"\n",
+        op_name, a, b, CONSTTIME_TRUE_S, c);
+        return 1;
+    } else if (!is_true && c != CONSTTIME_FALSE_S) {
+        fprintf(stderr, "Test failed for  %s(%"OSSLzu", %"OSSLzu
+        "): expected %" OSSLzu " (FALSE), got %"OSSLzu"\n",
+        op_name, a, b, CONSTTIME_FALSE_S, c);
+        return 1;
+    }
+    return 0;
+}
+
 static int test_is_zero(unsigned int a)
 {
     unsigned int c = constant_time_is_zero(a);
@@ -84,6 +106,22 @@ static int test_is_zero_8(unsigned int a)
     return 0;
 }
 
+static int test_is_zero_s(size_t a)
+{
+    size_t c = constant_time_is_zero_s(a);
+    if (a == 0 && c != CONSTTIME_TRUE_S) {
+        fprintf(stderr, "Test failed for constant_time_is_zero_s(%"OSSLzu"): "
+                "expected %"OSSLzu" (TRUE), got %"OSSLzu"\n",
+                a, CONSTTIME_TRUE_S, c);
+        return 1;
+    } else if (a != 0 && c != CONSTTIME_FALSE) {
+        fprintf(stderr, "Test failed for constant_time_is_zero_s(%"OSSLzu"): "
+                "expected %"OSSLzu" (FALSE), got %"OSSLzu"\n",
+                a, CONSTTIME_FALSE_S, c);
+        return 1;
+    }
+    return 0;
+}
 static int test_select(unsigned int a, unsigned int b)
 {
     unsigned int selected = constant_time_select(CONSTTIME_TRUE, a, b);
@@ -141,6 +179,28 @@ static int test_select_int(int a, int b)
     return 0;
 }
 
+
+static int test_select_s(size_t a, size_t b)
+{
+    size_t selected = constant_time_select_s(CONSTTIME_TRUE_S, a, b);
+    if (selected != a) {
+        fprintf(stderr, "Test failed for constant_time_select_s(%"OSSLzu
+                ", %"OSSLzu",%"OSSLzu"): expected %"OSSLzu
+                "(first value), got %"OSSLzu"\n",
+                CONSTTIME_TRUE_S, a, b, a, selected);
+        return 1;
+    }
+    selected = constant_time_select_s(CONSTTIME_FALSE_S, a, b);
+    if (selected != b) {
+        fprintf(stderr, "Test failed for constant_time_select_s(%"OSSLzu
+                ", %"OSSLzu",%"OSSLzu"): expected %"OSSLzu
+                "(second value), got %"OSSLzu"\n",
+                CONSTTIME_FALSE_S, a, b, b, selected);
+        return 1;
+    }
+    return 0;
+}
+
 static int test_eq_int(int a, int b)
 {
     unsigned int equal = constant_time_eq_int(a, b);
@@ -173,6 +233,23 @@ static int test_eq_int_8(int a, int b)
     return 0;
 }
 
+static int test_eq_s(size_t a, size_t b)
+{
+    size_t equal = constant_time_eq_s(a, b);
+    if (a == b && equal != CONSTTIME_TRUE_S) {
+        fprintf(stderr, "Test failed for constant_time_eq_int(%"OSSLzu
+                ", %"OSSLzu"): expected %"OSSLzu"(TRUE), got %"OSSLzu"\n",
+                a, b, CONSTTIME_TRUE_S, equal);
+        return 1;
+    } else if (a != b && equal != CONSTTIME_FALSE_S) {
+        fprintf(stderr, "Test failed for constant_time_eq_int(%"OSSLzu", %"
+                OSSLzu"): expected %"OSSLzu"(FALSE), got %"OSSLzu"\n",
+                a, b, CONSTTIME_FALSE_S, equal);
+        return 1;
+    }
+    return 0;
+}
+
 static unsigned int test_values[] =
     { 0, 1, 1024, 12345, 32000, UINT_MAX / 2 - 1,
     UINT_MAX / 2, UINT_MAX / 2 + 1, UINT_MAX - 1,
@@ -187,34 +264,55 @@ static int signed_test_values[] = { 0, 1, -1, 1024, -1024, 12345, -12345,
     INT_MIN + 1
 };
 
+static size_t test_values_s[] =
+    { 0, 1, 1024, 12345, 32000, SIZE_MAX / 2 - 1,
+    SIZE_MAX / 2, SIZE_MAX / 2 + 1, SIZE_MAX - 1,
+    SIZE_MAX
+};
+
 int main(int argc, char *argv[])
 {
     unsigned int a, b, i, j;
     int c, d;
     unsigned char e, f;
+    size_t g, h;
     int num_failed = 0, num_all = 0;
     fprintf(stdout, "Testing constant time operations...\n");
 
+    if (OSSL_NELEM(test_values) != OSSL_NELEM(test_values_s)) {
+        fprintf(stdout, "Unexpected number of tests\n");
+        return EXIT_FAILURE;
+    }
+
     for (i = 0; i < OSSL_NELEM(test_values); ++i) {
         a = test_values[i];
+        g = test_values_s[i];
         num_failed += test_is_zero(a);
         num_failed += test_is_zero_8(a);
-        num_all += 2;
+        num_failed += test_is_zero_s(g);
+        num_all += 3;
         for (j = 0; j < OSSL_NELEM(test_values); ++j) {
             b = test_values[j];
+            h = test_values[j];
             num_failed += test_binary_op(&constant_time_lt,
                                          "constant_time_lt", a, b, a < b);
             num_failed += test_binary_op_8(&constant_time_lt_8,
                                            "constant_time_lt_8", a, b, a < b);
+            num_failed += test_binary_op_s(&constant_time_lt_s,
+                                           "constant_time_lt_s", g, h, g < h);
             num_failed += test_binary_op(&constant_time_lt,
-                                         "constant_time_lt_8", b, a, b < a);
+                                         "constant_time_lt", b, a, b < a);
             num_failed += test_binary_op_8(&constant_time_lt_8,
                                            "constant_time_lt_8", b, a, b < a);
+            num_failed += test_binary_op_s(&constant_time_lt_s,
+                                           "constant_time_lt_s", h, g, h < g);
             num_failed += test_binary_op(&constant_time_ge,
                                          "constant_time_ge", a, b, a >= b);
             num_failed += test_binary_op_8(&constant_time_ge_8,
                                            "constant_time_ge_8", a, b,
                                            a >= b);
+            num_failed += test_binary_op_s(&constant_time_ge_s,
+                                           "constant_time_ge_s", g, h, g >= h);
             num_failed +=
                 test_binary_op(&constant_time_ge, "constant_time_ge", b, a,
                                b >= a);
@@ -222,19 +320,30 @@ int main(int argc, char *argv[])
                 test_binary_op_8(&constant_time_ge_8, "constant_time_ge_8", b,
                                  a, b >= a);
             num_failed +=
+                test_binary_op_s(&constant_time_ge_s, "constant_time_ge_s", h, g,
+                                 h >= g);
+            num_failed +=
                 test_binary_op(&constant_time_eq, "constant_time_eq", a, b,
                                a == b);
             num_failed +=
                 test_binary_op_8(&constant_time_eq_8, "constant_time_eq_8", a,
                                  b, a == b);
             num_failed +=
+                test_binary_op_s(&constant_time_eq_s, "constant_time_eq_s", g, h,
+                                 g == h);
+            num_failed +=
                 test_binary_op(&constant_time_eq, "constant_time_eq", b, a,
                                b == a);
             num_failed +=
                 test_binary_op_8(&constant_time_eq_8, "constant_time_eq_8", b,
                                  a, b == a);
+            num_failed +=
+                test_binary_op_s(&constant_time_eq_s, "constant_time_eq_s", h, g,
+                                 h == g);
             num_failed += test_select(a, b);
-            num_all += 13;
+            num_failed += test_select_s(g, h);
+            num_failed += test_eq_s(g, h);
+            num_all += 21;
         }
     }
 
diff --git a/util/libssl.num b/util/libssl.num
index 9f44b38..7d1e8d8 100644
--- a/util/libssl.num
+++ b/util/libssl.num
@@ -405,3 +405,6 @@ SSL_SESSION_get0_id_context             405	1_1_0	EXIST::FUNCTION:
 SSL_SESSION_set1_id                     406	1_1_0	EXIST::FUNCTION:
 SSL_CTX_set1_cert_store                 407	1_1_1	EXIST::FUNCTION:
 DTLS_get_data_mtu                       408	1_1_1	EXIST::FUNCTION:
+SSL_read_ex                             409	1_1_1	EXIST::FUNCTION:
+SSL_peek_ex                             410	1_1_1	EXIST::FUNCTION:
+SSL_write_ex                            411	1_1_1	EXIST::FUNCTION:


More information about the openssl-commits mailing list