Update copyright year
[oweals/openssl.git] / test / asynciotest.c
1 /*
2  * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL licenses, (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * https://www.openssl.org/source/license.html
8  * or in the file LICENSE in the source distribution.
9  */
10
11 #include <string.h>
12 #include <openssl/ssl.h>
13 #include <openssl/bio.h>
14 #include <openssl/err.h>
15
16 #include "../ssl/packet_locl.h"
17
18 #include "ssltestlib.h"
19
20 /* Should we fragment records or not? 0 = no, !0 = yes*/
21 static int fragment = 0;
22
23 static int async_new(BIO *bi);
24 static int async_free(BIO *a);
25 static int async_read(BIO *b, char *out, int outl);
26 static int async_write(BIO *b, const char *in, int inl);
27 static long async_ctrl(BIO *b, int cmd, long num, void *ptr);
28 static int async_gets(BIO *bp, char *buf, int size);
29 static int async_puts(BIO *bp, const char *str);
30
31 /* Choose a sufficiently large type likely to be unused for this custom BIO */
32 # define BIO_TYPE_ASYNC_FILTER  (0x80 | BIO_TYPE_FILTER)
33
34 static BIO_METHOD *methods_async = NULL;
35
36 struct async_ctrs {
37     unsigned int rctr;
38     unsigned int wctr;
39 };
40
41 static const BIO_METHOD *bio_f_async_filter()
42 {
43     if (methods_async == NULL) {
44         methods_async = BIO_meth_new(BIO_TYPE_ASYNC_FILTER, "Async filter");
45         if (   methods_async == NULL
46             || !BIO_meth_set_write(methods_async, async_write)
47             || !BIO_meth_set_read(methods_async, async_read)
48             || !BIO_meth_set_puts(methods_async, async_puts)
49             || !BIO_meth_set_gets(methods_async, async_gets)
50             || !BIO_meth_set_ctrl(methods_async, async_ctrl)
51             || !BIO_meth_set_create(methods_async, async_new)
52             || !BIO_meth_set_destroy(methods_async, async_free))
53             return NULL;
54     }
55     return methods_async;
56 }
57
58 static int async_new(BIO *bio)
59 {
60     struct async_ctrs *ctrs;
61
62     ctrs = OPENSSL_zalloc(sizeof(struct async_ctrs));
63     if (ctrs == NULL)
64         return 0;
65
66     BIO_set_data(bio, ctrs);
67     BIO_set_init(bio, 1);
68     return 1;
69 }
70
71 static int async_free(BIO *bio)
72 {
73     struct async_ctrs *ctrs;
74
75     if (bio == NULL)
76         return 0;
77     ctrs = BIO_get_data(bio);
78     OPENSSL_free(ctrs);
79     BIO_set_data(bio, NULL);
80     BIO_set_init(bio, 0);
81
82     return 1;
83 }
84
85 static int async_read(BIO *bio, char *out, int outl)
86 {
87     struct async_ctrs *ctrs;
88     int ret = -1;
89     BIO *next = BIO_next(bio);
90
91     if (outl <= 0)
92         return 0;
93     if (next == NULL)
94         return 0;
95
96     ctrs = BIO_get_data(bio);
97
98     BIO_clear_retry_flags(bio);
99
100     if (ctrs->rctr > 0) {
101         ret = BIO_read(next, out, 1);
102         if (ret <= 0 && BIO_should_read(next))
103             BIO_set_retry_read(bio);
104         ctrs->rctr = 0;
105     } else {
106         ctrs->rctr++;
107         BIO_set_retry_read(bio);
108     }
109
110     return ret;
111 }
112
113 #define MIN_RECORD_LEN  6
114
115 #define CONTENTTYPEPOS  0
116 #define VERSIONHIPOS    1
117 #define VERSIONLOPOS    2
118 #define DATAPOS         5
119
120 static int async_write(BIO *bio, const char *in, int inl)
121 {
122     struct async_ctrs *ctrs;
123     int ret = -1;
124     size_t written = 0;
125     BIO *next = BIO_next(bio);
126
127     if (inl <= 0)
128         return 0;
129     if (next == NULL)
130         return 0;
131
132     ctrs = BIO_get_data(bio);
133
134     BIO_clear_retry_flags(bio);
135
136     if (ctrs->wctr > 0) {
137         ctrs->wctr = 0;
138         if (fragment) {
139             PACKET pkt;
140
141             if (!PACKET_buf_init(&pkt, (const unsigned char *)in, inl))
142                 abort();
143
144             while (PACKET_remaining(&pkt) > 0) {
145                 PACKET payload;
146                 unsigned int contenttype, versionhi, versionlo, data;
147
148                 if (   !PACKET_get_1(&pkt, &contenttype)
149                     || !PACKET_get_1(&pkt, &versionhi)
150                     || !PACKET_get_1(&pkt, &versionlo)
151                     || !PACKET_get_length_prefixed_2(&pkt, &payload))
152                     abort();
153
154                 /* Pretend we wrote out the record header */
155                 written += SSL3_RT_HEADER_LENGTH;
156
157                 while (PACKET_get_1(&payload, &data)) {
158                     /* Create a new one byte long record for each byte in the
159                      * record in the input buffer
160                      */
161                     char smallrec[MIN_RECORD_LEN] = {
162                         0, /* Content type */
163                         0, /* Version hi */
164                         0, /* Version lo */
165                         0, /* Length hi */
166                         1, /* Length lo */
167                         0  /* Data */
168                     };
169
170                     smallrec[CONTENTTYPEPOS] = contenttype;
171                     smallrec[VERSIONHIPOS] = versionhi;
172                     smallrec[VERSIONLOPOS] = versionlo;
173                     smallrec[DATAPOS] = data;
174                     ret = BIO_write(next, smallrec, MIN_RECORD_LEN);
175                     if (ret <= 0)
176                         abort();
177                     written++;
178                 }
179                 /*
180                  * We can't fragment anything after the CCS, otherwise we
181                  * get a bad record MAC
182                  */
183                 if (contenttype == SSL3_RT_CHANGE_CIPHER_SPEC) {
184                     fragment = 0;
185                     break;
186                 }
187             }
188         }
189         /* Write any data we have left after fragmenting */
190         ret = 0;
191         if ((int)written < inl) {
192             ret = BIO_write(next, in + written , inl - written);
193         }
194
195         if (ret <= 0 && BIO_should_write(next))
196             BIO_set_retry_write(bio);
197         else
198             ret += written;
199     } else {
200         ctrs->wctr++;
201         BIO_set_retry_write(bio);
202     }
203
204     return ret;
205 }
206
207 static long async_ctrl(BIO *bio, int cmd, long num, void *ptr)
208 {
209     long ret;
210     BIO *next = BIO_next(bio);
211
212     if (next == NULL)
213         return 0;
214
215     switch (cmd) {
216     case BIO_CTRL_DUP:
217         ret = 0L;
218         break;
219     default:
220         ret = BIO_ctrl(next, cmd, num, ptr);
221         break;
222     }
223     return ret;
224 }
225
226 static int async_gets(BIO *bio, char *buf, int size)
227 {
228     /* We don't support this - not needed anyway */
229     return -1;
230 }
231
232 static int async_puts(BIO *bio, const char *str)
233 {
234     return async_write(bio, str, strlen(str));
235 }
236
237 #define MAX_ATTEMPTS    100
238
239 int main(int argc, char *argv[])
240 {
241     SSL_CTX *serverctx = NULL, *clientctx = NULL;
242     SSL *serverssl = NULL, *clientssl = NULL;
243     BIO *s_to_c_fbio = NULL, *c_to_s_fbio = NULL;
244     int test, err = 1, ret;
245     size_t i, j;
246     const char testdata[] = "Test data";
247     char buf[sizeof(testdata)];
248
249     CRYPTO_set_mem_debug(1);
250     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
251
252     if (argc != 3) {
253         printf("Invalid argument count\n");
254         goto end;
255     }
256
257     if (!create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
258                              TLS1_VERSION, TLS_MAX_VERSION,
259                              &serverctx, &clientctx, argv[1], argv[2])) {
260         printf("Failed to create SSL_CTX pair\n");
261         goto end;
262     }
263
264     /*
265      * We do 2 test runs. The first time around we just do a normal handshake
266      * with lots of async io going on. The second time around we also break up
267      * all records so that the content is only one byte length (up until the
268      * CCS)
269      */
270     for (test = 1; test < 3; test++) {
271         if (test == 2)
272             fragment = 1;
273
274
275         s_to_c_fbio = BIO_new(bio_f_async_filter());
276         c_to_s_fbio = BIO_new(bio_f_async_filter());
277         if (s_to_c_fbio == NULL || c_to_s_fbio == NULL) {
278             printf("Failed to create filter BIOs\n");
279             BIO_free(s_to_c_fbio);
280             BIO_free(c_to_s_fbio);
281             goto end;
282         }
283
284         /* BIOs get freed on error */
285         if (!create_ssl_objects(serverctx, clientctx, &serverssl, &clientssl,
286                                 s_to_c_fbio, c_to_s_fbio)) {
287             printf("Test %d failed: Create SSL objects failed\n", test);
288             goto end;
289         }
290
291         if (!create_ssl_connection(serverssl, clientssl)) {
292             printf("Test %d failed: Create SSL connection failed\n", test);
293             goto end;
294         }
295
296         /*
297          * Send and receive some test data. Do the whole thing twice to ensure
298          * we hit at least one async event in both reading and writing
299          */
300         for (j = 0; j < 2; j++) {
301             int len;
302
303             /*
304              * Write some test data. It should never take more than 2 attempts
305              * (the first one might be a retryable fail).
306              */
307             for (ret = -1, i = 0, len = 0; len != sizeof(testdata) && i < 2;
308                 i++) {
309                 ret = SSL_write(clientssl, testdata + len,
310                     sizeof(testdata) - len);
311                 if (ret > 0) {
312                     len += ret;
313                 } else {
314                     int ssl_error = SSL_get_error(clientssl, ret);
315
316                     if (ssl_error == SSL_ERROR_SYSCALL ||
317                         ssl_error == SSL_ERROR_SSL) {
318                         printf("Test %d failed: Failed to write app data\n", test);
319                         err = -1;
320                         goto end;
321                     }
322                 }
323             }
324             if (len != sizeof(testdata)) {
325                 err = -1;
326                 printf("Test %d failed: Failed to write all app data\n", test);
327                 goto end;
328             }
329             /*
330              * Now read the test data. It may take more attempts here because
331              * it could fail once for each byte read, including all overhead
332              * bytes from the record header/padding etc.
333              */
334             for (ret = -1, i = 0, len = 0; len != sizeof(testdata) &&
335                 i < MAX_ATTEMPTS; i++)
336             {
337                 ret = SSL_read(serverssl, buf + len, sizeof(buf) - len);
338                 if (ret > 0) {
339                     len += ret;
340                 } else {
341                     int ssl_error = SSL_get_error(serverssl, ret);
342
343                     if (ssl_error == SSL_ERROR_SYSCALL ||
344                         ssl_error == SSL_ERROR_SSL) {
345                         printf("Test %d failed: Failed to read app data\n", test);
346                         err = -1;
347                         goto end;
348                     }
349                 }
350             }
351             if (len != sizeof(testdata)
352                     || memcmp(buf, testdata, sizeof(testdata)) != 0) {
353                 err = -1;
354                 printf("Test %d failed: Unexpected app data received\n", test);
355                 goto end;
356             }
357         }
358
359         /* Also frees the BIOs */
360         SSL_free(clientssl);
361         SSL_free(serverssl);
362         clientssl = serverssl = NULL;
363     }
364
365     printf("Test success\n");
366
367     err = 0;
368  end:
369     if (err)
370         ERR_print_errors_fp(stderr);
371
372     SSL_free(clientssl);
373     SSL_free(serverssl);
374     SSL_CTX_free(clientctx);
375     SSL_CTX_free(serverctx);
376
377 # ifndef OPENSSL_NO_CRYPTO_MDEBUG
378     CRYPTO_mem_leaks_fp(stderr);
379 # endif
380
381     return err;
382 }