1 /* Copyright (c) 2014, Google Inc.
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
15 #include "async_bio.h"
18 #include <openssl/mem.h>
22 extern const BIO_METHOD async_bio_method;
30 async_bio *get_data(BIO *bio) {
31 if (bio->method != &async_bio_method) {
34 return (async_bio *)bio->ptr;
37 static int async_write(BIO *bio, const char *in, int inl) {
38 async_bio *a = get_data(bio);
39 if (a == NULL || bio->next_bio == NULL) {
44 // Perform writes synchronously; the DTLS implementation drops any packets
45 // that failed to send.
46 return BIO_write(bio->next_bio, in, inl);
49 BIO_clear_retry_flags(bio);
51 if (a->write_quota == 0) {
52 BIO_set_retry_write(bio);
57 if (!a->datagram && (size_t)inl > a->write_quota) {
60 int ret = BIO_write(bio->next_bio, in, inl);
62 BIO_copy_next_retry(bio);
64 a->write_quota -= ret;
69 static int async_read(BIO *bio, char *out, int outl) {
70 async_bio *a = get_data(bio);
71 if (a == NULL || bio->next_bio == NULL) {
75 BIO_clear_retry_flags(bio);
77 if (a->read_quota == 0) {
78 BIO_set_retry_read(bio);
83 if (!a->datagram && (size_t)outl > a->read_quota) {
86 int ret = BIO_read(bio->next_bio, out, outl);
88 BIO_copy_next_retry(bio);
90 a->read_quota -= (a->datagram ? 1 : ret);
95 static long async_ctrl(BIO *bio, int cmd, long num, void *ptr) {
96 if (bio->next_bio == NULL) {
99 BIO_clear_retry_flags(bio);
100 int ret = BIO_ctrl(bio->next_bio, cmd, num, ptr);
101 BIO_copy_next_retry(bio);
105 static int async_new(BIO *bio) {
106 async_bio *a = (async_bio *)OPENSSL_malloc(sizeof(*a));
110 memset(a, 0, sizeof(*a));
112 bio->ptr = (char *)a;
116 static int async_free(BIO *bio) {
121 OPENSSL_free(bio->ptr);
128 static long async_callback_ctrl(BIO *bio, int cmd, bio_info_cb fp) {
129 if (bio->next_bio == NULL) {
132 return BIO_callback_ctrl(bio->next_bio, cmd, fp);
135 const BIO_METHOD async_bio_method = {
150 BIO *async_bio_create() {
151 return BIO_new(&async_bio_method);
154 BIO *async_bio_create_datagram() {
155 BIO *ret = BIO_new(&async_bio_method);
159 get_data(ret)->datagram = true;
163 void async_bio_allow_read(BIO *bio, size_t count) {
164 async_bio *a = get_data(bio);
168 a->read_quota += count;
171 void async_bio_allow_write(BIO *bio, size_t count) {
172 async_bio *a = get_data(bio);
176 a->write_quota += count;