testutil: always print errors on failure
[openssl.git] / test / asynciotest.c
1 /*
2  * Copyright 2016 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 = 0;
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 = 0;
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                              &serverctx, &clientctx, argv[1], argv[2])) {
259         printf("Failed to create SSL_CTX pair\n");
260         goto end;
261     }
262
263     /*
264      * We do 2 test runs. The first time around we just do a normal handshake
265      * with lots of async io going on. The second time around we also break up
266      * all records so that the content is only one byte length (up until the
267      * CCS)
268      */
269     for (test = 1; test < 3; test++) {
270         if (test == 2)
271             fragment = 1;
272
273
274         s_to_c_fbio = BIO_new(bio_f_async_filter());
275         c_to_s_fbio = BIO_new(bio_f_async_filter());
276         if (s_to_c_fbio == NULL || c_to_s_fbio == NULL) {
277             printf("Failed to create filter BIOs\n");
278             BIO_free(s_to_c_fbio);
279             BIO_free(c_to_s_fbio);
280             goto end;
281         }
282
283         /* BIOs get freed on error */
284         if (!create_ssl_objects(serverctx, clientctx, &serverssl, &clientssl,
285                                 s_to_c_fbio, c_to_s_fbio)) {
286             printf("Test %d failed: Create SSL objects failed\n", test);
287             goto end;
288         }
289
290         if (!create_ssl_connection(serverssl, clientssl)) {
291             printf("Test %d failed: Create SSL connection failed\n", test);
292             goto end;
293         }
294
295         /*
296          * Send and receive some test data. Do the whole thing twice to ensure
297          * we hit at least one async event in both reading and writing
298          */
299         for (j = 0; j < 2; j++) {
300             /*
301              * Write some test data. It should never take more than 2 attempts
302              * (the first one might be a retryable fail). A zero return from
303              * SSL_write() is a non-retryable failure, so fail immediately if
304              * we get that.
305              */
306             for (ret = -1, i = 0; ret < 0 && i < 2 * sizeof(testdata); i++)
307                 ret = SSL_write(clientssl, testdata, sizeof(testdata));
308             if (ret <= 0) {
309                 printf("Test %d failed: Failed to write app data\n", test);
310                 goto end;
311             }
312             /*
313              * Now read the test data. It may take more attemps here because
314              * it could fail once for each byte read, including all overhead
315              * bytes from the record header/padding etc. Fail immediately if we
316              * get a zero return from SSL_read().
317              */
318             for (ret = -1, i = 0; ret < 0 && i < MAX_ATTEMPTS; i++)
319                 ret = SSL_read(serverssl, buf, sizeof(buf));
320             if (ret <= 0) {
321                 printf("Test %d failed: Failed to read app data\n", test);
322                 goto end;
323             }
324             if (ret != sizeof(testdata)
325                     || memcmp(buf, testdata, sizeof(testdata)) != 0) {
326                 printf("Test %d failed: Unexpected app data received\n", test);
327                 goto end;
328             }
329         }
330
331         /* Also frees the BIOs */
332         SSL_free(clientssl);
333         SSL_free(serverssl);
334         clientssl = serverssl = NULL;
335     }
336
337     printf("Test success\n");
338
339     err = 0;
340  end:
341     if (err)
342         ERR_print_errors_fp(stderr);
343
344     SSL_free(clientssl);
345     SSL_free(serverssl);
346     SSL_CTX_free(clientctx);
347     SSL_CTX_free(serverctx);
348
349 # ifndef OPENSSL_NO_CRYPTO_MDEBUG
350     CRYPTO_mem_leaks_fp(stderr);
351 # endif
352
353     return err;
354 }