2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 #include <openssl/ssl.h>
12 #include <openssl/bio.h>
15 static SSL *get_ssl(BIO *bio) {
16 return reinterpret_cast<SSL *>(bio->ptr);
19 static int ssl_read(BIO *bio, char *out, int outl) {
20 SSL *ssl = get_ssl(bio);
25 BIO_clear_retry_flags(bio);
27 const int ret = SSL_read(ssl, out, outl);
29 switch (SSL_get_error(ssl, ret)) {
30 case SSL_ERROR_WANT_READ:
31 BIO_set_retry_read(bio);
34 case SSL_ERROR_WANT_WRITE:
35 BIO_set_retry_write(bio);
38 case SSL_ERROR_WANT_ACCEPT:
39 BIO_set_retry_special(bio);
40 bio->retry_reason = BIO_RR_ACCEPT;
43 case SSL_ERROR_WANT_CONNECT:
44 BIO_set_retry_special(bio);
45 bio->retry_reason = BIO_RR_CONNECT;
49 case SSL_ERROR_SYSCALL:
51 case SSL_ERROR_ZERO_RETURN:
59 static int ssl_write(BIO *bio, const char *out, int outl) {
60 SSL *ssl = get_ssl(bio);
65 BIO_clear_retry_flags(bio);
67 const int ret = SSL_write(ssl, out, outl);
69 switch (SSL_get_error(ssl, ret)) {
70 case SSL_ERROR_WANT_WRITE:
71 BIO_set_retry_write(bio);
74 case SSL_ERROR_WANT_READ:
75 BIO_set_retry_read(bio);
78 case SSL_ERROR_WANT_CONNECT:
79 BIO_set_retry_special(bio);
80 bio->retry_reason = BIO_RR_CONNECT;
84 case SSL_ERROR_SYSCALL:
93 static long ssl_ctrl(BIO *bio, int cmd, long num, void *ptr) {
94 SSL *ssl = get_ssl(bio);
95 if (ssl == NULL && cmd != BIO_C_SET_SSL) {
106 case BIO_CTRL_GET_CLOSE:
107 return bio->shutdown;
109 case BIO_CTRL_SET_CLOSE:
113 case BIO_CTRL_WPENDING:
114 return BIO_ctrl(SSL_get_wbio(ssl), cmd, num, ptr);
116 case BIO_CTRL_PENDING:
117 return SSL_pending(ssl);
119 case BIO_CTRL_FLUSH: {
120 BIO_clear_retry_flags(bio);
121 long ret = BIO_ctrl(SSL_get_wbio(ssl), cmd, num, ptr);
122 BIO_copy_next_retry(bio);
132 return BIO_ctrl(SSL_get_rbio(ssl), cmd, num, ptr);
136 static int ssl_new(BIO *bio) {
140 static int ssl_free(BIO *bio) {
141 SSL *ssl = get_ssl(bio);
155 static long ssl_callback_ctrl(BIO *bio, int cmd, bio_info_cb fp) {
156 SSL *ssl = get_ssl(bio);
162 case BIO_CTRL_SET_CALLBACK:
166 return BIO_callback_ctrl(SSL_get_rbio(ssl), cmd, fp);
170 static const BIO_METHOD ssl_method = {
171 BIO_TYPE_SSL, "SSL", ssl_write, ssl_read, NULL,
172 NULL, ssl_ctrl, ssl_new, ssl_free, ssl_callback_ctrl,
175 const BIO_METHOD *BIO_f_ssl(void) { return &ssl_method; }
177 long BIO_set_ssl(BIO *bio, SSL *ssl, int take_owership) {
178 return BIO_ctrl(bio, BIO_C_SET_SSL, take_owership, ssl);