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