2 * Copyright 2021 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (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/bio.h>
13 static const char *filename = NULL;
16 * Test that a BIO_f_readbuffer() with a BIO_new_file() behaves nicely if
17 * BIO_gets() and BIO_read_ex() are both called.
18 * Since the BIO_gets() calls buffer the reads, the BIO_read_ex() should
19 * still be able to read the buffered data if we seek back to the start.
21 * The following cases are tested using tstid:
22 * 0 : Just use BIO_read_ex().
23 * 1 : Try a few reads using BIO_gets() before using BIO_read_ex()
24 * 2 : Read the entire file using BIO_gets() before using BIO_read_ex().
26 static int test_readbuffer_file_bio(int tstid)
28 int ret = 0, len, partial;
29 BIO *in = NULL, *in_bio = NULL, *readbuf_bio = NULL;
32 size_t readbytes = 0, bytes = 0, count = 0;
34 /* Open a file BIO and read all the data */
35 if (!TEST_ptr(in = BIO_new_file(filename, "r"))
36 || !TEST_int_eq(BIO_read_ex(in, expected, sizeof(expected),
38 || !TEST_int_lt(readbytes, sizeof(expected)))
43 /* Create a new file bio that sits under a readbuffer BIO */
44 if (!TEST_ptr(readbuf_bio = BIO_new(BIO_f_readbuffer()))
45 || !TEST_ptr(in_bio = BIO_new_file(filename, "r")))
48 in_bio = BIO_push(readbuf_bio, in_bio);
51 if (!TEST_int_eq(BIO_tell(in_bio), 0))
56 while (!BIO_eof(in_bio)) {
57 len = BIO_gets(in_bio, buf, sizeof(buf));
59 if (!TEST_true(BIO_eof(in_bio)))
62 if (!TEST_int_gt(len, 0)
63 || !TEST_int_le(len, (int)sizeof(buf) - 1))
65 if (!TEST_true(buf[len] == 0))
69 && len != ((int)sizeof(buf) - 1)
70 && !TEST_true(buf[len - 1] == '\n'))
73 if (tstid == 1 && --partial == 0)
77 if (!TEST_int_eq(BIO_seek(in_bio, 0), 1))
80 len = 8; /* Do a small partial read to start with */
81 while (!BIO_eof(in_bio)) {
82 if (!TEST_int_eq(BIO_read_ex(in_bio, buf, len, &bytes), 1))
84 if (!TEST_mem_eq(buf, bytes, expected + count, bytes))
87 len = sizeof(buf); /* fill the buffer on subsequent reads */
89 if (!TEST_int_eq(count, readbytes))
95 BIO_free(readbuf_bio);
99 typedef enum OPTION_choice {
105 const OPTIONS *test_get_options(void)
107 static const OPTIONS test_options[] = {
108 OPT_TEST_OPTIONS_WITH_EXTRA_USAGE("file\n"),
109 { OPT_HELP_STR, 1, '-', "file\tFile to run tests on.\n" },
115 int setup_tests(void)
119 while ((o = opt_next()) != OPT_EOF) {
127 filename = test_get_argument(0);
129 ADD_ALL_TESTS(test_readbuffer_file_bio, 3);