consume all data after a socket write error
[project/ustream-ssl.git] / ustream-io-cyassl.c
1 /*
2  * ustream-ssl - library for SSL over ustream
3  *
4  * Copyright (C) 2012 Felix Fietkau <nbd@openwrt.org>
5  *
6  * Permission to use, copy, modify, and/or distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18
19 #include <string.h>
20
21 #include <libubox/ustream.h>
22
23 #include "ustream-ssl.h"
24 #include "ustream-internal.h"
25
26 /* not defined in the header file */
27 typedef int (*CallbackIORecv)(char *buf, int sz, void *ctx);
28 typedef int (*CallbackIOSend)(char *buf, int sz, void *ctx);
29
30 void SetCallbackIORecv_Ctx(SSL_CTX*, CallbackIORecv);
31 void SetCallbackIOSend_Ctx(SSL_CTX*, CallbackIOSend);
32 void SetCallbackIO_ReadCtx(SSL* ssl, void *rctx);
33 void SetCallbackIO_WriteCtx(SSL* ssl, void *wctx);
34
35 static int s_ustream_read(char *buf, int len, void *ctx)
36 {
37         struct ustream *s = ctx;
38         char *sbuf;
39         int slen;
40
41         if (s->eof)
42                 return -3;
43
44         sbuf = ustream_get_read_buf(s, &slen);
45         if (slen > len)
46                 slen = len;
47
48         if (!slen)
49                 return -2;
50
51         memcpy(buf, sbuf, slen);
52         ustream_consume(s, slen);
53
54         return slen;
55 }
56
57 static int s_ustream_write(char *buf, int len, void *ctx)
58 {
59         struct ustream *s = ctx;
60
61         if (s->write_error)
62                 return len;
63
64         return ustream_write(s, buf, len, false);
65 }
66
67 __hidden void ustream_set_io(void *ctx, void *ssl, struct ustream *conn)
68 {
69         SetCallbackIO_ReadCtx(ssl, conn);
70         SetCallbackIO_WriteCtx(ssl, conn);
71         SetCallbackIORecv_Ctx(ctx, s_ustream_read);
72         SetCallbackIOSend_Ctx(ctx, s_ustream_write);
73 }