1 /* Copyright (c) 2014, Google Inc.
2 *
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.
6 *
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. */
14
15 #include <algorithm>
16 #include <string>
17 #include <utility>
18
19 #include <gtest/gtest.h>
20
21 #include <openssl/bio.h>
22 #include <openssl/crypto.h>
23 #include <openssl/err.h>
24 #include <openssl/mem.h>
25
26 #include "../internal.h"
27 #include "../test/test_util.h"
28
29 #if !defined(OPENSSL_WINDOWS)
30 #include <arpa/inet.h>
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <netinet/in.h>
34 #include <poll.h>
35 #include <string.h>
36 #include <sys/socket.h>
37 #include <unistd.h>
38 #else
39 #include <io.h>
40 OPENSSL_MSVC_PRAGMA(warning(push, 3))
41 #include <winsock2.h>
42 #include <ws2tcpip.h>
43 OPENSSL_MSVC_PRAGMA(warning(pop))
44 #endif
45
46 #if !defined(OPENSSL_WINDOWS)
47 using Socket = int;
48 #define INVALID_SOCKET (-1)
closesocket(int sock)49 static int closesocket(int sock) { return close(sock); }
LastSocketError()50 static std::string LastSocketError() { return strerror(errno); }
51 #else
52 using Socket = SOCKET;
53 static std::string LastSocketError() {
54 char buf[DECIMAL_SIZE(int) + 1];
55 snprintf(buf, sizeof(buf), "%d", WSAGetLastError());
56 return buf;
57 }
58 #endif
59
60 class OwnedSocket {
61 public:
62 OwnedSocket() = default;
OwnedSocket(Socket sock)63 explicit OwnedSocket(Socket sock) : sock_(sock) {}
OwnedSocket(OwnedSocket && other)64 OwnedSocket(OwnedSocket &&other) { *this = std::move(other); }
~OwnedSocket()65 ~OwnedSocket() { reset(); }
operator =(OwnedSocket && other)66 OwnedSocket &operator=(OwnedSocket &&other) {
67 reset(other.release());
68 return *this;
69 }
70
is_valid() const71 bool is_valid() const { return sock_ != INVALID_SOCKET; }
get() const72 Socket get() const { return sock_; }
release()73 Socket release() { return std::exchange(sock_, INVALID_SOCKET); }
74
reset(Socket sock=INVALID_SOCKET)75 void reset(Socket sock = INVALID_SOCKET) {
76 if (is_valid()) {
77 closesocket(sock_);
78 }
79
80 sock_ = sock;
81 }
82
83 private:
84 Socket sock_ = INVALID_SOCKET;
85 };
86
87 struct SockaddrStorage {
familySockaddrStorage88 int family() const { return storage.ss_family; }
89
addr_mutSockaddrStorage90 sockaddr *addr_mut() { return reinterpret_cast<sockaddr *>(&storage); }
addrSockaddrStorage91 const sockaddr *addr() const {
92 return reinterpret_cast<const sockaddr *>(&storage);
93 }
94
ToIPv4SockaddrStorage95 sockaddr_in ToIPv4() const {
96 if (family() != AF_INET || len != sizeof(sockaddr_in)) {
97 abort();
98 }
99 // These APIs were seemingly designed before C's strict aliasing rule, and
100 // C++'s strict union handling. Make a copy so the compiler does not read
101 // this as an aliasing violation.
102 sockaddr_in ret;
103 OPENSSL_memcpy(&ret, &storage, sizeof(ret));
104 return ret;
105 }
106
ToIPv6SockaddrStorage107 sockaddr_in6 ToIPv6() const {
108 if (family() != AF_INET6 || len != sizeof(sockaddr_in6)) {
109 abort();
110 }
111 // These APIs were seemingly designed before C's strict aliasing rule, and
112 // C++'s strict union handling. Make a copy so the compiler does not read
113 // this as an aliasing violation.
114 sockaddr_in6 ret;
115 OPENSSL_memcpy(&ret, &storage, sizeof(ret));
116 return ret;
117 }
118
119 sockaddr_storage storage = {};
120 socklen_t len = sizeof(storage);
121 };
122
Bind(int family,const sockaddr * addr,socklen_t addr_len)123 static OwnedSocket Bind(int family, const sockaddr *addr, socklen_t addr_len) {
124 OwnedSocket sock(socket(family, SOCK_STREAM, 0));
125 if (!sock.is_valid()) {
126 return OwnedSocket();
127 }
128
129 if (bind(sock.get(), addr, addr_len) != 0) {
130 return OwnedSocket();
131 }
132
133 return sock;
134 }
135
ListenLoopback(int backlog)136 static OwnedSocket ListenLoopback(int backlog) {
137 // Try binding to IPv6.
138 sockaddr_in6 sin6;
139 OPENSSL_memset(&sin6, 0, sizeof(sin6));
140 sin6.sin6_family = AF_INET6;
141 if (inet_pton(AF_INET6, "::1", &sin6.sin6_addr) != 1) {
142 return OwnedSocket();
143 }
144 OwnedSocket sock =
145 Bind(AF_INET6, reinterpret_cast<const sockaddr *>(&sin6), sizeof(sin6));
146 if (!sock.is_valid()) {
147 // Try binding to IPv4.
148 sockaddr_in sin;
149 OPENSSL_memset(&sin, 0, sizeof(sin));
150 sin.sin_family = AF_INET;
151 if (inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr) != 1) {
152 return OwnedSocket();
153 }
154 sock = Bind(AF_INET, reinterpret_cast<const sockaddr *>(&sin), sizeof(sin));
155 }
156 if (!sock.is_valid()) {
157 return OwnedSocket();
158 }
159
160 if (listen(sock.get(), backlog) != 0) {
161 return OwnedSocket();
162 }
163
164 return sock;
165 }
166
SocketSetNonBlocking(Socket sock)167 static bool SocketSetNonBlocking(Socket sock) {
168 #if defined(OPENSSL_WINDOWS)
169 u_long arg = 1;
170 return ioctlsocket(sock, FIONBIO, &arg) == 0;
171 #else
172 int flags = fcntl(sock, F_GETFL, 0);
173 if (flags < 0) {
174 return false;
175 }
176 flags |= O_NONBLOCK;
177 return fcntl(sock, F_SETFL, flags) == 0;
178 #endif
179 }
180
181 enum class WaitType { kRead, kWrite };
182
WaitForSocket(Socket sock,WaitType wait_type)183 static bool WaitForSocket(Socket sock, WaitType wait_type) {
184 // Use an arbitrary 5 second timeout, so the test doesn't hang indefinitely if
185 // there's an issue.
186 static const int kTimeoutSeconds = 5;
187 #if defined(OPENSSL_WINDOWS)
188 fd_set read_set, write_set;
189 FD_ZERO(&read_set);
190 FD_ZERO(&write_set);
191 fd_set *wait_set = wait_type == WaitType::kRead ? &read_set : &write_set;
192 FD_SET(sock, wait_set);
193 timeval timeout;
194 timeout.tv_sec = kTimeoutSeconds;
195 timeout.tv_usec = 0;
196 if (select(0 /* unused on Windows */, &read_set, &write_set, nullptr,
197 &timeout) <= 0) {
198 return false;
199 }
200 return FD_ISSET(sock, wait_set);
201 #else
202 short events = wait_type == WaitType::kRead ? POLLIN : POLLOUT;
203 pollfd fd = {/*fd=*/sock, events, /*revents=*/0};
204 return poll(&fd, 1, kTimeoutSeconds * 1000) == 1 && (fd.revents & events);
205 #endif
206 }
207
TEST(BIOTest,SocketConnect)208 TEST(BIOTest, SocketConnect) {
209 static const char kTestMessage[] = "test";
210 OwnedSocket listening_sock = ListenLoopback(/*backlog=*/1);
211 ASSERT_TRUE(listening_sock.is_valid()) << LastSocketError();
212
213 SockaddrStorage addr;
214 ASSERT_EQ(getsockname(listening_sock.get(), addr.addr_mut(), &addr.len), 0)
215 << LastSocketError();
216
217 char hostname[80];
218 if (addr.family() == AF_INET6) {
219 snprintf(hostname, sizeof(hostname), "[::1]:%d",
220 ntohs(addr.ToIPv6().sin6_port));
221 } else {
222 snprintf(hostname, sizeof(hostname), "127.0.0.1:%d",
223 ntohs(addr.ToIPv4().sin_port));
224 }
225
226 // Connect to it with a connect BIO.
227 bssl::UniquePtr<BIO> bio(BIO_new_connect(hostname));
228 ASSERT_TRUE(bio);
229
230 // Write a test message to the BIO. This is assumed to be smaller than the
231 // transport buffer.
232 ASSERT_EQ(static_cast<int>(sizeof(kTestMessage)),
233 BIO_write(bio.get(), kTestMessage, sizeof(kTestMessage)))
234 << LastSocketError();
235
236 // Accept the socket.
237 OwnedSocket sock(accept(listening_sock.get(), addr.addr_mut(), &addr.len));
238 ASSERT_TRUE(sock.is_valid()) << LastSocketError();
239
240 // Check the same message is read back out.
241 char buf[sizeof(kTestMessage)];
242 ASSERT_EQ(static_cast<int>(sizeof(kTestMessage)),
243 recv(sock.get(), buf, sizeof(buf), 0))
244 << LastSocketError();
245 EXPECT_EQ(Bytes(kTestMessage, sizeof(kTestMessage)), Bytes(buf, sizeof(buf)));
246 }
247
TEST(BIOTest,SocketNonBlocking)248 TEST(BIOTest, SocketNonBlocking) {
249 OwnedSocket listening_sock = ListenLoopback(/*backlog=*/1);
250 ASSERT_TRUE(listening_sock.is_valid()) << LastSocketError();
251
252 // Connect to |listening_sock|.
253 SockaddrStorage addr;
254 ASSERT_EQ(getsockname(listening_sock.get(), addr.addr_mut(), &addr.len), 0)
255 << LastSocketError();
256 OwnedSocket connect_sock(socket(addr.family(), SOCK_STREAM, 0));
257 ASSERT_TRUE(connect_sock.is_valid()) << LastSocketError();
258 ASSERT_EQ(connect(connect_sock.get(), addr.addr(), addr.len), 0)
259 << LastSocketError();
260 ASSERT_TRUE(SocketSetNonBlocking(connect_sock.get())) << LastSocketError();
261 bssl::UniquePtr<BIO> connect_bio(
262 BIO_new_socket(connect_sock.get(), BIO_NOCLOSE));
263 ASSERT_TRUE(connect_bio);
264
265 // Make a corresponding accepting socket.
266 OwnedSocket accept_sock(
267 accept(listening_sock.get(), addr.addr_mut(), &addr.len));
268 ASSERT_TRUE(accept_sock.is_valid()) << LastSocketError();
269 ASSERT_TRUE(SocketSetNonBlocking(accept_sock.get())) << LastSocketError();
270 bssl::UniquePtr<BIO> accept_bio(
271 BIO_new_socket(accept_sock.get(), BIO_NOCLOSE));
272 ASSERT_TRUE(accept_bio);
273
274 // Exchange data through the socket.
275 static const char kTestMessage[] = "hello, world";
276
277 // Reading from |accept_bio| should not block.
278 char buf[sizeof(kTestMessage)];
279 int ret = BIO_read(accept_bio.get(), buf, sizeof(buf));
280 EXPECT_EQ(ret, -1);
281 EXPECT_TRUE(BIO_should_read(accept_bio.get())) << LastSocketError();
282
283 // Writing to |connect_bio| should eventually overflow the transport buffers
284 // and also give a retryable error.
285 int bytes_written = 0;
286 for (;;) {
287 ret = BIO_write(connect_bio.get(), kTestMessage, sizeof(kTestMessage));
288 if (ret <= 0) {
289 EXPECT_EQ(ret, -1);
290 EXPECT_TRUE(BIO_should_write(connect_bio.get())) << LastSocketError();
291 break;
292 }
293 bytes_written += ret;
294 }
295 EXPECT_GT(bytes_written, 0);
296
297 // |accept_bio| should readable. Drain it. Note data is not always available
298 // from loopback immediately, notably on macOS, so wait for the socket first.
299 int bytes_read = 0;
300 while (bytes_read < bytes_written) {
301 ASSERT_TRUE(WaitForSocket(accept_sock.get(), WaitType::kRead))
302 << LastSocketError();
303 ret = BIO_read(accept_bio.get(), buf, sizeof(buf));
304 ASSERT_GT(ret, 0);
305 bytes_read += ret;
306 }
307
308 // |connect_bio| should become writeable again.
309 ASSERT_TRUE(WaitForSocket(accept_sock.get(), WaitType::kWrite))
310 << LastSocketError();
311 ret = BIO_write(connect_bio.get(), kTestMessage, sizeof(kTestMessage));
312 EXPECT_EQ(static_cast<int>(sizeof(kTestMessage)), ret);
313
314 ASSERT_TRUE(WaitForSocket(accept_sock.get(), WaitType::kRead))
315 << LastSocketError();
316 ret = BIO_read(accept_bio.get(), buf, sizeof(buf));
317 EXPECT_EQ(static_cast<int>(sizeof(kTestMessage)), ret);
318 EXPECT_EQ(Bytes(buf), Bytes(kTestMessage));
319
320 // Close one socket. We should get an EOF out the other.
321 connect_bio.reset();
322 connect_sock.reset();
323
324 ASSERT_TRUE(WaitForSocket(accept_sock.get(), WaitType::kRead))
325 << LastSocketError();
326 ret = BIO_read(accept_bio.get(), buf, sizeof(buf));
327 EXPECT_EQ(ret, 0) << LastSocketError();
328 EXPECT_FALSE(BIO_should_read(accept_bio.get()));
329 }
330
TEST(BIOTest,Printf)331 TEST(BIOTest, Printf) {
332 // Test a short output, a very long one, and various sizes around
333 // 256 (the size of the buffer) to ensure edge cases are correct.
334 static const size_t kLengths[] = {5, 250, 251, 252, 253, 254, 1023};
335
336 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
337 ASSERT_TRUE(bio);
338
339 for (size_t length : kLengths) {
340 SCOPED_TRACE(length);
341
342 std::string in(length, 'a');
343
344 int ret = BIO_printf(bio.get(), "test %s", in.c_str());
345 ASSERT_GE(ret, 0);
346 EXPECT_EQ(5 + length, static_cast<size_t>(ret));
347
348 const uint8_t *contents;
349 size_t len;
350 ASSERT_TRUE(BIO_mem_contents(bio.get(), &contents, &len));
351 EXPECT_EQ("test " + in,
352 std::string(reinterpret_cast<const char *>(contents), len));
353
354 ASSERT_TRUE(BIO_reset(bio.get()));
355 }
356 }
357
TEST(BIOTest,ReadASN1)358 TEST(BIOTest, ReadASN1) {
359 static const size_t kLargeASN1PayloadLen = 8000;
360
361 struct ASN1Test {
362 bool should_succeed;
363 std::vector<uint8_t> input;
364 // suffix_len is the number of zeros to append to |input|.
365 size_t suffix_len;
366 // expected_len, if |should_succeed| is true, is the expected length of the
367 // ASN.1 element.
368 size_t expected_len;
369 size_t max_len;
370 } kASN1Tests[] = {
371 {true, {0x30, 2, 1, 2, 0, 0}, 0, 4, 100},
372 {false /* truncated */, {0x30, 3, 1, 2}, 0, 0, 100},
373 {false /* should be short len */, {0x30, 0x81, 1, 1}, 0, 0, 100},
374 {false /* zero padded */, {0x30, 0x82, 0, 1, 1}, 0, 0, 100},
375
376 // Test a large payload.
377 {true,
378 {0x30, 0x82, kLargeASN1PayloadLen >> 8, kLargeASN1PayloadLen & 0xff},
379 kLargeASN1PayloadLen,
380 4 + kLargeASN1PayloadLen,
381 kLargeASN1PayloadLen * 2},
382 {false /* max_len too short */,
383 {0x30, 0x82, kLargeASN1PayloadLen >> 8, kLargeASN1PayloadLen & 0xff},
384 kLargeASN1PayloadLen,
385 4 + kLargeASN1PayloadLen,
386 3 + kLargeASN1PayloadLen},
387
388 // Test an indefinite-length input.
389 {true,
390 {0x30, 0x80},
391 kLargeASN1PayloadLen + 2,
392 2 + kLargeASN1PayloadLen + 2,
393 kLargeASN1PayloadLen * 2},
394 {false /* max_len too short */,
395 {0x30, 0x80},
396 kLargeASN1PayloadLen + 2,
397 2 + kLargeASN1PayloadLen + 2,
398 2 + kLargeASN1PayloadLen + 1},
399 };
400
401 for (const auto &t : kASN1Tests) {
402 std::vector<uint8_t> input = t.input;
403 input.resize(input.size() + t.suffix_len, 0);
404
405 bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(input.data(), input.size()));
406 ASSERT_TRUE(bio);
407
408 uint8_t *out;
409 size_t out_len;
410 int ok = BIO_read_asn1(bio.get(), &out, &out_len, t.max_len);
411 if (!ok) {
412 out = nullptr;
413 }
414 bssl::UniquePtr<uint8_t> out_storage(out);
415
416 ASSERT_EQ(t.should_succeed, (ok == 1));
417 if (t.should_succeed) {
418 EXPECT_EQ(Bytes(input.data(), t.expected_len), Bytes(out, out_len));
419 }
420 }
421 }
422
TEST(BIOTest,MemReadOnly)423 TEST(BIOTest, MemReadOnly) {
424 // A memory BIO created from |BIO_new_mem_buf| is a read-only buffer.
425 static const char kData[] = "abcdefghijklmno";
426 bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(kData, strlen(kData)));
427 ASSERT_TRUE(bio);
428
429 // Writing to read-only buffers should fail.
430 EXPECT_EQ(BIO_write(bio.get(), kData, strlen(kData)), -1);
431
432 const uint8_t *contents;
433 size_t len;
434 ASSERT_TRUE(BIO_mem_contents(bio.get(), &contents, &len));
435 EXPECT_EQ(Bytes(contents, len), Bytes(kData));
436 EXPECT_EQ(BIO_eof(bio.get()), 0);
437
438 // Read less than the whole buffer.
439 char buf[6];
440 int ret = BIO_read(bio.get(), buf, sizeof(buf));
441 ASSERT_GT(ret, 0);
442 EXPECT_EQ(Bytes(buf, ret), Bytes("abcdef"));
443
444 ASSERT_TRUE(BIO_mem_contents(bio.get(), &contents, &len));
445 EXPECT_EQ(Bytes(contents, len), Bytes("ghijklmno"));
446 EXPECT_EQ(BIO_eof(bio.get()), 0);
447
448 ret = BIO_read(bio.get(), buf, sizeof(buf));
449 ASSERT_GT(ret, 0);
450 EXPECT_EQ(Bytes(buf, ret), Bytes("ghijkl"));
451
452 ASSERT_TRUE(BIO_mem_contents(bio.get(), &contents, &len));
453 EXPECT_EQ(Bytes(contents, len), Bytes("mno"));
454 EXPECT_EQ(BIO_eof(bio.get()), 0);
455
456 // Read the remainder of the buffer.
457 ret = BIO_read(bio.get(), buf, sizeof(buf));
458 ASSERT_GT(ret, 0);
459 EXPECT_EQ(Bytes(buf, ret), Bytes("mno"));
460
461 ASSERT_TRUE(BIO_mem_contents(bio.get(), &contents, &len));
462 EXPECT_EQ(Bytes(contents, len), Bytes(""));
463 EXPECT_EQ(BIO_eof(bio.get()), 1);
464
465 // By default, reading from a consumed read-only buffer returns EOF.
466 EXPECT_EQ(BIO_read(bio.get(), buf, sizeof(buf)), 0);
467 EXPECT_FALSE(BIO_should_read(bio.get()));
468
469 // A memory BIO can be configured to return an error instead of EOF. This is
470 // error is returned as retryable. (This is not especially useful here. It
471 // makes more sense for a writable BIO.)
472 EXPECT_EQ(BIO_set_mem_eof_return(bio.get(), -1), 1);
473 EXPECT_EQ(BIO_read(bio.get(), buf, sizeof(buf)), -1);
474 EXPECT_TRUE(BIO_should_read(bio.get()));
475
476 // Read exactly the right number of bytes, to test the boundary condition is
477 // correct.
478 bio.reset(BIO_new_mem_buf("abc", 3));
479 ASSERT_TRUE(bio);
480 ret = BIO_read(bio.get(), buf, 3);
481 ASSERT_GT(ret, 0);
482 EXPECT_EQ(Bytes(buf, ret), Bytes("abc"));
483 EXPECT_EQ(BIO_eof(bio.get()), 1);
484 }
485
TEST(BIOTest,MemWritable)486 TEST(BIOTest, MemWritable) {
487 // A memory BIO created from |BIO_new| is writable.
488 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
489 ASSERT_TRUE(bio);
490
491 auto check_bio_contents = [&](Bytes b) {
492 const uint8_t *contents;
493 size_t len;
494 ASSERT_TRUE(BIO_mem_contents(bio.get(), &contents, &len));
495 EXPECT_EQ(Bytes(contents, len), b);
496
497 char *contents_c;
498 long len_l = BIO_get_mem_data(bio.get(), &contents_c);
499 ASSERT_GE(len_l, 0);
500 EXPECT_EQ(Bytes(contents_c, len_l), b);
501
502 BUF_MEM *buf;
503 ASSERT_EQ(BIO_get_mem_ptr(bio.get(), &buf), 1);
504 EXPECT_EQ(Bytes(buf->data, buf->length), b);
505 };
506
507 // It is initially empty.
508 check_bio_contents(Bytes(""));
509 EXPECT_EQ(BIO_eof(bio.get()), 1);
510
511 // Reading from it should default to returning a retryable error.
512 char buf[32];
513 EXPECT_EQ(BIO_read(bio.get(), buf, sizeof(buf)), -1);
514 EXPECT_TRUE(BIO_should_read(bio.get()));
515
516 // This can be configured to return an EOF.
517 EXPECT_EQ(BIO_set_mem_eof_return(bio.get(), 0), 1);
518 EXPECT_EQ(BIO_read(bio.get(), buf, sizeof(buf)), 0);
519 EXPECT_FALSE(BIO_should_read(bio.get()));
520
521 // Restore the default. A writable memory |BIO| is typically used in this mode
522 // so additional data can be written when exhausted.
523 EXPECT_EQ(BIO_set_mem_eof_return(bio.get(), -1), 1);
524
525 // Writes append to the buffer.
526 ASSERT_EQ(BIO_write(bio.get(), "abcdef", 6), 6);
527 check_bio_contents(Bytes("abcdef"));
528 EXPECT_EQ(BIO_eof(bio.get()), 0);
529
530 // Writes can include embedded NULs.
531 ASSERT_EQ(BIO_write(bio.get(), "\0ghijk", 6), 6);
532 check_bio_contents(Bytes("abcdef\0ghijk", 12));
533 EXPECT_EQ(BIO_eof(bio.get()), 0);
534
535 // Do a partial read.
536 int ret = BIO_read(bio.get(), buf, 4);
537 ASSERT_GT(ret, 0);
538 EXPECT_EQ(Bytes(buf, ret), Bytes("abcd"));
539 check_bio_contents(Bytes("ef\0ghijk", 8));
540 EXPECT_EQ(BIO_eof(bio.get()), 0);
541
542 // Reads and writes may alternate.
543 ASSERT_EQ(BIO_write(bio.get(), "lmnopq", 6), 6);
544 check_bio_contents(Bytes("ef\0ghijklmnopq", 14));
545 EXPECT_EQ(BIO_eof(bio.get()), 0);
546
547 // Reads may consume embedded NULs.
548 ret = BIO_read(bio.get(), buf, 4);
549 ASSERT_GT(ret, 0);
550 EXPECT_EQ(Bytes(buf, ret), Bytes("ef\0g", 4));
551 check_bio_contents(Bytes("hijklmnopq"));
552 EXPECT_EQ(BIO_eof(bio.get()), 0);
553
554 // The read buffer exceeds the |BIO|, so we consume everything.
555 ret = BIO_read(bio.get(), buf, sizeof(buf));
556 ASSERT_GT(ret, 0);
557 EXPECT_EQ(Bytes(buf, ret), Bytes("hijklmnopq"));
558 check_bio_contents(Bytes(""));
559 EXPECT_EQ(BIO_eof(bio.get()), 1);
560
561 // The |BIO| is now empty.
562 EXPECT_EQ(BIO_read(bio.get(), buf, sizeof(buf)), -1);
563 EXPECT_TRUE(BIO_should_read(bio.get()));
564
565 // Repeat the above, reading exactly the right number of bytes, to test the
566 // boundary condition is correct.
567 ASSERT_EQ(BIO_write(bio.get(), "abc", 3), 3);
568 ret = BIO_read(bio.get(), buf, 3);
569 EXPECT_EQ(Bytes(buf, ret), Bytes("abc"));
570 EXPECT_EQ(BIO_read(bio.get(), buf, sizeof(buf)), -1);
571 EXPECT_TRUE(BIO_should_read(bio.get()));
572 EXPECT_EQ(BIO_eof(bio.get()), 1);
573 }
574
TEST(BIOTest,Gets)575 TEST(BIOTest, Gets) {
576 const struct {
577 std::string bio;
578 int gets_len;
579 std::string gets_result;
580 } kGetsTests[] = {
581 // BIO_gets should stop at the first newline. If the buffer is too small,
582 // stop there instead. Note the buffer size
583 // includes a trailing NUL.
584 {"123456789\n123456789", 5, "1234"},
585 {"123456789\n123456789", 9, "12345678"},
586 {"123456789\n123456789", 10, "123456789"},
587 {"123456789\n123456789", 11, "123456789\n"},
588 {"123456789\n123456789", 12, "123456789\n"},
589 {"123456789\n123456789", 256, "123456789\n"},
590
591 // If we run out of buffer, read the whole buffer.
592 {"12345", 5, "1234"},
593 {"12345", 6, "12345"},
594 {"12345", 10, "12345"},
595
596 // NUL bytes do not terminate gets.
597 {std::string("abc\0def\nghi", 11), 256, std::string("abc\0def\n", 8)},
598
599 // An output size of one means we cannot read any bytes. Only the trailing
600 // NUL is included.
601 {"12345", 1, ""},
602
603 // Empty line.
604 {"\nabcdef", 256, "\n"},
605 // Empty BIO.
606 {"", 256, ""},
607 };
608 for (const auto& t : kGetsTests) {
609 SCOPED_TRACE(t.bio);
610 SCOPED_TRACE(t.gets_len);
611
612 auto check_bio_gets = [&](BIO *bio) {
613 std::vector<char> buf(t.gets_len, 'a');
614 int ret = BIO_gets(bio, buf.data(), t.gets_len);
615 ASSERT_GE(ret, 0);
616 // |BIO_gets| should write a NUL terminator, not counted in the return
617 // value.
618 EXPECT_EQ(Bytes(buf.data(), ret + 1),
619 Bytes(t.gets_result.data(), t.gets_result.size() + 1));
620
621 // The remaining data should still be in the BIO.
622 buf.resize(t.bio.size() + 1);
623 ret = BIO_read(bio, buf.data(), static_cast<int>(buf.size()));
624 ASSERT_GE(ret, 0);
625 EXPECT_EQ(Bytes(buf.data(), ret),
626 Bytes(t.bio.substr(t.gets_result.size())));
627 };
628
629 {
630 SCOPED_TRACE("memory");
631 bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(t.bio.data(), t.bio.size()));
632 ASSERT_TRUE(bio);
633 check_bio_gets(bio.get());
634 }
635
636 struct FileCloser {
637 void operator()(FILE *f) const { fclose(f); }
638 };
639 using ScopedFILE = std::unique_ptr<FILE, FileCloser>;
640 ScopedFILE file(tmpfile());
641 #if defined(OPENSSL_ANDROID)
642 // On Android, when running from an APK, |tmpfile| does not work. See
643 // b/36991167#comment8.
644 if (!file) {
645 fprintf(stderr, "tmpfile failed: %s (%d). Skipping file-based tests.\n",
646 strerror(errno), errno);
647 continue;
648 }
649 #else
650 ASSERT_TRUE(file);
651 #endif
652
653 if (!t.bio.empty()) {
654 ASSERT_EQ(1u,
655 fwrite(t.bio.data(), t.bio.size(), /*nitems=*/1, file.get()));
656 ASSERT_EQ(0, fseek(file.get(), 0, SEEK_SET));
657 }
658
659 // TODO(crbug.com/boringssl/585): If the line has an embedded NUL, file
660 // BIOs do not currently report the answer correctly.
661 if (t.bio.find('\0') == std::string::npos) {
662 SCOPED_TRACE("file");
663 bssl::UniquePtr<BIO> bio(BIO_new_fp(file.get(), BIO_NOCLOSE));
664 ASSERT_TRUE(bio);
665 check_bio_gets(bio.get());
666 }
667
668 ASSERT_EQ(0, fseek(file.get(), 0, SEEK_SET));
669
670 {
671 SCOPED_TRACE("fd");
672 #if defined(OPENSSL_WINDOWS)
673 int fd = _fileno(file.get());
674 #else
675 int fd = fileno(file.get());
676 #endif
677 bssl::UniquePtr<BIO> bio(BIO_new_fd(fd, BIO_NOCLOSE));
678 ASSERT_TRUE(bio);
679 check_bio_gets(bio.get());
680 }
681 }
682
683 // Negative and zero lengths should not output anything, even a trailing NUL.
684 bssl::UniquePtr<BIO> bio(BIO_new_mem_buf("12345", -1));
685 ASSERT_TRUE(bio);
686 char c = 'a';
687 EXPECT_EQ(0, BIO_gets(bio.get(), &c, -1));
688 EXPECT_EQ(0, BIO_gets(bio.get(), &c, 0));
689 EXPECT_EQ(c, 'a');
690 }
691
692 // Run through the tests twice, swapping |bio1| and |bio2|, for symmetry.
693 class BIOPairTest : public testing::TestWithParam<bool> {};
694
TEST_P(BIOPairTest,TestPair)695 TEST_P(BIOPairTest, TestPair) {
696 BIO *bio1, *bio2;
697 ASSERT_TRUE(BIO_new_bio_pair(&bio1, 10, &bio2, 10));
698 bssl::UniquePtr<BIO> free_bio1(bio1), free_bio2(bio2);
699
700 if (GetParam()) {
701 std::swap(bio1, bio2);
702 }
703
704 // Check initial states.
705 EXPECT_EQ(10u, BIO_ctrl_get_write_guarantee(bio1));
706 EXPECT_EQ(0u, BIO_ctrl_get_read_request(bio1));
707
708 // Data written in one end may be read out the other.
709 uint8_t buf[20];
710 EXPECT_EQ(5, BIO_write(bio1, "12345", 5));
711 EXPECT_EQ(5u, BIO_ctrl_get_write_guarantee(bio1));
712 ASSERT_EQ(5, BIO_read(bio2, buf, sizeof(buf)));
713 EXPECT_EQ(Bytes("12345"), Bytes(buf, 5));
714 EXPECT_EQ(10u, BIO_ctrl_get_write_guarantee(bio1));
715
716 // Attempting to write more than 10 bytes will write partially.
717 EXPECT_EQ(10, BIO_write(bio1, "1234567890___", 13));
718 EXPECT_EQ(0u, BIO_ctrl_get_write_guarantee(bio1));
719 EXPECT_EQ(-1, BIO_write(bio1, "z", 1));
720 EXPECT_TRUE(BIO_should_write(bio1));
721 ASSERT_EQ(10, BIO_read(bio2, buf, sizeof(buf)));
722 EXPECT_EQ(Bytes("1234567890"), Bytes(buf, 10));
723 EXPECT_EQ(10u, BIO_ctrl_get_write_guarantee(bio1));
724
725 // Unsuccessful reads update the read request.
726 EXPECT_EQ(-1, BIO_read(bio2, buf, 5));
727 EXPECT_TRUE(BIO_should_read(bio2));
728 EXPECT_EQ(5u, BIO_ctrl_get_read_request(bio1));
729
730 // The read request is clamped to the size of the buffer.
731 EXPECT_EQ(-1, BIO_read(bio2, buf, 20));
732 EXPECT_TRUE(BIO_should_read(bio2));
733 EXPECT_EQ(10u, BIO_ctrl_get_read_request(bio1));
734
735 // Data may be written and read in chunks.
736 EXPECT_EQ(5, BIO_write(bio1, "12345", 5));
737 EXPECT_EQ(5u, BIO_ctrl_get_write_guarantee(bio1));
738 EXPECT_EQ(5, BIO_write(bio1, "67890___", 8));
739 EXPECT_EQ(0u, BIO_ctrl_get_write_guarantee(bio1));
740 ASSERT_EQ(3, BIO_read(bio2, buf, 3));
741 EXPECT_EQ(Bytes("123"), Bytes(buf, 3));
742 EXPECT_EQ(3u, BIO_ctrl_get_write_guarantee(bio1));
743 ASSERT_EQ(7, BIO_read(bio2, buf, sizeof(buf)));
744 EXPECT_EQ(Bytes("4567890"), Bytes(buf, 7));
745 EXPECT_EQ(10u, BIO_ctrl_get_write_guarantee(bio1));
746
747 // Successful reads reset the read request.
748 EXPECT_EQ(0u, BIO_ctrl_get_read_request(bio1));
749
750 // Test writes and reads starting in the middle of the ring buffer and
751 // wrapping to front.
752 EXPECT_EQ(8, BIO_write(bio1, "abcdefgh", 8));
753 EXPECT_EQ(2u, BIO_ctrl_get_write_guarantee(bio1));
754 ASSERT_EQ(3, BIO_read(bio2, buf, 3));
755 EXPECT_EQ(Bytes("abc"), Bytes(buf, 3));
756 EXPECT_EQ(5u, BIO_ctrl_get_write_guarantee(bio1));
757 EXPECT_EQ(5, BIO_write(bio1, "ijklm___", 8));
758 EXPECT_EQ(0u, BIO_ctrl_get_write_guarantee(bio1));
759 ASSERT_EQ(10, BIO_read(bio2, buf, sizeof(buf)));
760 EXPECT_EQ(Bytes("defghijklm"), Bytes(buf, 10));
761 EXPECT_EQ(10u, BIO_ctrl_get_write_guarantee(bio1));
762
763 // Data may flow from both ends in parallel.
764 EXPECT_EQ(5, BIO_write(bio1, "12345", 5));
765 EXPECT_EQ(5, BIO_write(bio2, "67890", 5));
766 ASSERT_EQ(5, BIO_read(bio2, buf, sizeof(buf)));
767 EXPECT_EQ(Bytes("12345"), Bytes(buf, 5));
768 ASSERT_EQ(5, BIO_read(bio1, buf, sizeof(buf)));
769 EXPECT_EQ(Bytes("67890"), Bytes(buf, 5));
770
771 // Closing the write end causes an EOF on the read half, after draining.
772 EXPECT_EQ(5, BIO_write(bio1, "12345", 5));
773 EXPECT_TRUE(BIO_shutdown_wr(bio1));
774 ASSERT_EQ(5, BIO_read(bio2, buf, sizeof(buf)));
775 EXPECT_EQ(Bytes("12345"), Bytes(buf, 5));
776 EXPECT_EQ(0, BIO_read(bio2, buf, sizeof(buf)));
777
778 // A closed write end may not be written to.
779 EXPECT_EQ(0u, BIO_ctrl_get_write_guarantee(bio1));
780 EXPECT_EQ(-1, BIO_write(bio1, "_____", 5));
781
782 uint32_t err = ERR_get_error();
783 EXPECT_EQ(ERR_LIB_BIO, ERR_GET_LIB(err));
784 EXPECT_EQ(BIO_R_BROKEN_PIPE, ERR_GET_REASON(err));
785
786 // The other end is still functional.
787 EXPECT_EQ(5, BIO_write(bio2, "12345", 5));
788 ASSERT_EQ(5, BIO_read(bio1, buf, sizeof(buf)));
789 EXPECT_EQ(Bytes("12345"), Bytes(buf, 5));
790 }
791
792 INSTANTIATE_TEST_SUITE_P(All, BIOPairTest, testing::Values(false, true));
793