socket_bio_adapter.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. // Copyright 2016 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "net/socket/socket_bio_adapter.h"
  5. #include <string.h>
  6. #include <algorithm>
  7. #include "base/bind.h"
  8. #include "base/check_op.h"
  9. #include "base/location.h"
  10. #include "base/notreached.h"
  11. #include "base/threading/thread_task_runner_handle.h"
  12. #include "net/base/io_buffer.h"
  13. #include "net/base/net_errors.h"
  14. #include "net/socket/socket.h"
  15. #include "net/socket/stream_socket.h"
  16. #include "net/ssl/openssl_ssl_util.h"
  17. #include "net/traffic_annotation/network_traffic_annotation.h"
  18. #include "third_party/boringssl/src/include/openssl/bio.h"
  19. namespace {
  20. const net::NetworkTrafficAnnotationTag kTrafficAnnotation =
  21. net::DefineNetworkTrafficAnnotation("socket_bio_adapter", R"(
  22. semantics {
  23. sender: "Socket BIO Adapter"
  24. description:
  25. "SocketBIOAdapter is used only internal to //net code as an internal "
  26. "detail to implement a TLS connection for a Socket class, and is not "
  27. "being called directly outside of this abstraction."
  28. trigger:
  29. "Establishing a TLS connection to a remote endpoint. There are many "
  30. "different ways in which a TLS connection may be triggered, such as "
  31. "loading an HTTPS URL."
  32. data:
  33. "All data sent or received over a TLS connection. This traffic may "
  34. "either be the handshake or application data. During the handshake, "
  35. "the target host name, user's IP, data related to previous "
  36. "handshake, client certificates, and channel ID, may be sent. When "
  37. "the connection is used to load an HTTPS URL, the application data "
  38. "includes cookies, request headers, and the response body."
  39. destination: OTHER
  40. destination_other:
  41. "Any destination the implementing socket is connected to."
  42. }
  43. policy {
  44. cookies_allowed: NO
  45. setting: "This feature cannot be disabled."
  46. policy_exception_justification: "Essential for navigation."
  47. })");
  48. } // namespace
  49. namespace net {
  50. SocketBIOAdapter::SocketBIOAdapter(StreamSocket* socket,
  51. int read_buffer_capacity,
  52. int write_buffer_capacity,
  53. Delegate* delegate)
  54. : socket_(socket),
  55. read_buffer_capacity_(read_buffer_capacity),
  56. write_buffer_capacity_(write_buffer_capacity),
  57. delegate_(delegate) {
  58. bio_.reset(BIO_new(&kBIOMethod));
  59. bio_->ptr = this;
  60. bio_->init = 1;
  61. read_callback_ = base::BindRepeating(&SocketBIOAdapter::OnSocketReadComplete,
  62. weak_factory_.GetWeakPtr());
  63. write_callback_ = base::BindRepeating(
  64. &SocketBIOAdapter::OnSocketWriteComplete, weak_factory_.GetWeakPtr());
  65. }
  66. SocketBIOAdapter::~SocketBIOAdapter() {
  67. // BIOs are reference-counted and may outlive the adapter. Clear the pointer
  68. // so future operations fail.
  69. bio_->ptr = nullptr;
  70. }
  71. bool SocketBIOAdapter::HasPendingReadData() {
  72. return read_result_ > 0;
  73. }
  74. size_t SocketBIOAdapter::GetAllocationSize() const {
  75. size_t buffer_size = 0;
  76. if (read_buffer_)
  77. buffer_size += read_buffer_capacity_;
  78. if (write_buffer_)
  79. buffer_size += write_buffer_capacity_;
  80. return buffer_size;
  81. }
  82. int SocketBIOAdapter::BIORead(char* out, int len) {
  83. if (len <= 0)
  84. return len;
  85. // If there is no result available synchronously, report any Write() errors
  86. // that were observed. Otherwise the application may have encountered a socket
  87. // error while writing that would otherwise not be reported until the
  88. // application attempted to write again - which it may never do. See
  89. // https://crbug.com/249848.
  90. if (write_error_ != OK && write_error_ != ERR_IO_PENDING &&
  91. (read_result_ == 0 || read_result_ == ERR_IO_PENDING)) {
  92. OpenSSLPutNetError(FROM_HERE, write_error_);
  93. return -1;
  94. }
  95. if (read_result_ == 0) {
  96. // Instantiate the read buffer and read from the socket. Although only |len|
  97. // bytes were requested, intentionally read to the full buffer size. The SSL
  98. // layer reads the record header and body in separate reads to avoid
  99. // overreading, but issuing one is more efficient. SSL sockets are not
  100. // reused after shutdown for non-SSL traffic, so overreading is fine.
  101. DCHECK(!read_buffer_);
  102. DCHECK_EQ(0, read_offset_);
  103. read_buffer_ = base::MakeRefCounted<IOBuffer>(read_buffer_capacity_);
  104. int result = socket_->ReadIfReady(
  105. read_buffer_.get(), read_buffer_capacity_,
  106. base::BindOnce(&SocketBIOAdapter::OnSocketReadIfReadyComplete,
  107. weak_factory_.GetWeakPtr()));
  108. if (result == ERR_IO_PENDING)
  109. read_buffer_ = nullptr;
  110. if (result == ERR_READ_IF_READY_NOT_IMPLEMENTED) {
  111. result = socket_->Read(read_buffer_.get(), read_buffer_capacity_,
  112. read_callback_);
  113. }
  114. if (result == ERR_IO_PENDING) {
  115. read_result_ = ERR_IO_PENDING;
  116. } else {
  117. HandleSocketReadResult(result);
  118. }
  119. }
  120. // There is a pending Read(). Inform the caller to retry when it completes.
  121. if (read_result_ == ERR_IO_PENDING) {
  122. BIO_set_retry_read(bio());
  123. return -1;
  124. }
  125. // If the last Read() failed, report the error.
  126. if (read_result_ < 0) {
  127. OpenSSLPutNetError(FROM_HERE, read_result_);
  128. return -1;
  129. }
  130. // Report the result of the last Read() if non-empty.
  131. CHECK_LT(read_offset_, read_result_);
  132. len = std::min(len, read_result_ - read_offset_);
  133. memcpy(out, read_buffer_->data() + read_offset_, len);
  134. read_offset_ += len;
  135. // Release the buffer when empty.
  136. if (read_offset_ == read_result_) {
  137. read_buffer_ = nullptr;
  138. read_offset_ = 0;
  139. read_result_ = 0;
  140. }
  141. return len;
  142. }
  143. void SocketBIOAdapter::HandleSocketReadResult(int result) {
  144. DCHECK_NE(ERR_IO_PENDING, result);
  145. // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here, so that higher
  146. // levels don't report success.
  147. if (result == 0)
  148. result = ERR_CONNECTION_CLOSED;
  149. read_result_ = result;
  150. // The read buffer is no longer needed.
  151. if (read_result_ <= 0)
  152. read_buffer_ = nullptr;
  153. }
  154. void SocketBIOAdapter::OnSocketReadComplete(int result) {
  155. DCHECK_EQ(ERR_IO_PENDING, read_result_);
  156. HandleSocketReadResult(result);
  157. delegate_->OnReadReady();
  158. }
  159. void SocketBIOAdapter::OnSocketReadIfReadyComplete(int result) {
  160. DCHECK_EQ(ERR_IO_PENDING, read_result_);
  161. DCHECK_GE(OK, result);
  162. // Do not use HandleSocketReadResult() because result == OK doesn't mean EOF.
  163. read_result_ = result;
  164. delegate_->OnReadReady();
  165. }
  166. int SocketBIOAdapter::BIOWrite(const char* in, int len) {
  167. if (len <= 0)
  168. return len;
  169. // If the write buffer is not empty, there must be a pending Write() to flush
  170. // it.
  171. DCHECK(write_buffer_used_ == 0 || write_error_ == ERR_IO_PENDING);
  172. // If a previous Write() failed, report the error.
  173. if (write_error_ != OK && write_error_ != ERR_IO_PENDING) {
  174. OpenSSLPutNetError(FROM_HERE, write_error_);
  175. return -1;
  176. }
  177. // Instantiate the write buffer if needed.
  178. if (!write_buffer_) {
  179. DCHECK_EQ(0, write_buffer_used_);
  180. write_buffer_ = base::MakeRefCounted<GrowableIOBuffer>();
  181. write_buffer_->SetCapacity(write_buffer_capacity_);
  182. }
  183. // If the ring buffer is full, inform the caller to try again later.
  184. if (write_buffer_used_ == write_buffer_->capacity()) {
  185. BIO_set_retry_write(bio());
  186. return -1;
  187. }
  188. int bytes_copied = 0;
  189. // If there is space after the offset, fill it.
  190. if (write_buffer_used_ < write_buffer_->RemainingCapacity()) {
  191. int chunk =
  192. std::min(write_buffer_->RemainingCapacity() - write_buffer_used_, len);
  193. memcpy(write_buffer_->data() + write_buffer_used_, in, chunk);
  194. in += chunk;
  195. len -= chunk;
  196. bytes_copied += chunk;
  197. write_buffer_used_ += chunk;
  198. }
  199. // If there is still space for remaining data, try to wrap around.
  200. if (len > 0 && write_buffer_used_ < write_buffer_->capacity()) {
  201. // If there were any room after the offset, the previous branch would have
  202. // filled it.
  203. CHECK_LE(write_buffer_->RemainingCapacity(), write_buffer_used_);
  204. int write_offset = write_buffer_used_ - write_buffer_->RemainingCapacity();
  205. int chunk = std::min(len, write_buffer_->capacity() - write_buffer_used_);
  206. memcpy(write_buffer_->StartOfBuffer() + write_offset, in, chunk);
  207. in += chunk;
  208. len -= chunk;
  209. bytes_copied += chunk;
  210. write_buffer_used_ += chunk;
  211. }
  212. // Either the buffer is now full or there is no more input.
  213. DCHECK(len == 0 || write_buffer_used_ == write_buffer_->capacity());
  214. // Schedule a socket Write() if necessary. (The ring buffer may previously
  215. // have been empty.)
  216. SocketWrite();
  217. // If a read-interrupting write error was synchronously discovered,
  218. // asynchronously notify OnReadReady. See https://crbug.com/249848. Avoid
  219. // reentrancy by deferring it to a later event loop iteration.
  220. if (write_error_ != OK && write_error_ != ERR_IO_PENDING &&
  221. read_result_ == ERR_IO_PENDING) {
  222. base::ThreadTaskRunnerHandle::Get()->PostTask(
  223. FROM_HERE, base::BindOnce(&SocketBIOAdapter::CallOnReadReady,
  224. weak_factory_.GetWeakPtr()));
  225. }
  226. return bytes_copied;
  227. }
  228. void SocketBIOAdapter::SocketWrite() {
  229. while (write_error_ == OK && write_buffer_used_ > 0) {
  230. int write_size =
  231. std::min(write_buffer_used_, write_buffer_->RemainingCapacity());
  232. int result = socket_->Write(write_buffer_.get(), write_size,
  233. write_callback_, kTrafficAnnotation);
  234. if (result == ERR_IO_PENDING) {
  235. write_error_ = ERR_IO_PENDING;
  236. return;
  237. }
  238. HandleSocketWriteResult(result);
  239. }
  240. }
  241. void SocketBIOAdapter::HandleSocketWriteResult(int result) {
  242. DCHECK_NE(ERR_IO_PENDING, result);
  243. if (result < 0) {
  244. write_error_ = result;
  245. // The write buffer is no longer needed.
  246. write_buffer_ = nullptr;
  247. write_buffer_used_ = 0;
  248. return;
  249. }
  250. // Advance the ring buffer.
  251. write_buffer_->set_offset(write_buffer_->offset() + result);
  252. write_buffer_used_ -= result;
  253. if (write_buffer_->RemainingCapacity() == 0)
  254. write_buffer_->set_offset(0);
  255. write_error_ = OK;
  256. // Release the write buffer if empty.
  257. if (write_buffer_used_ == 0)
  258. write_buffer_ = nullptr;
  259. }
  260. void SocketBIOAdapter::OnSocketWriteComplete(int result) {
  261. DCHECK_EQ(ERR_IO_PENDING, write_error_);
  262. bool was_full = write_buffer_used_ == write_buffer_->capacity();
  263. HandleSocketWriteResult(result);
  264. SocketWrite();
  265. // If transitioning from being unable to accept data to being able to, signal
  266. // OnWriteReady.
  267. if (was_full) {
  268. base::WeakPtr<SocketBIOAdapter> guard(weak_factory_.GetWeakPtr());
  269. delegate_->OnWriteReady();
  270. // OnWriteReady may delete the adapter.
  271. if (!guard)
  272. return;
  273. }
  274. // Write errors are fed back into BIO_read once the read buffer is empty. If
  275. // BIO_read is currently blocked, signal early that a read result is ready.
  276. if (result < 0 && read_result_ == ERR_IO_PENDING)
  277. delegate_->OnReadReady();
  278. }
  279. void SocketBIOAdapter::CallOnReadReady() {
  280. if (read_result_ == ERR_IO_PENDING)
  281. delegate_->OnReadReady();
  282. }
  283. SocketBIOAdapter* SocketBIOAdapter::GetAdapter(BIO* bio) {
  284. DCHECK_EQ(&kBIOMethod, bio->method);
  285. SocketBIOAdapter* adapter = reinterpret_cast<SocketBIOAdapter*>(bio->ptr);
  286. if (adapter)
  287. DCHECK_EQ(bio, adapter->bio());
  288. return adapter;
  289. }
  290. int SocketBIOAdapter::BIOWriteWrapper(BIO* bio, const char* in, int len) {
  291. BIO_clear_retry_flags(bio);
  292. SocketBIOAdapter* adapter = GetAdapter(bio);
  293. if (!adapter) {
  294. OpenSSLPutNetError(FROM_HERE, ERR_UNEXPECTED);
  295. return -1;
  296. }
  297. return adapter->BIOWrite(in, len);
  298. }
  299. int SocketBIOAdapter::BIOReadWrapper(BIO* bio, char* out, int len) {
  300. BIO_clear_retry_flags(bio);
  301. SocketBIOAdapter* adapter = GetAdapter(bio);
  302. if (!adapter) {
  303. OpenSSLPutNetError(FROM_HERE, ERR_UNEXPECTED);
  304. return -1;
  305. }
  306. return adapter->BIORead(out, len);
  307. }
  308. long SocketBIOAdapter::BIOCtrlWrapper(BIO* bio,
  309. int cmd,
  310. long larg,
  311. void* parg) {
  312. switch (cmd) {
  313. case BIO_CTRL_FLUSH:
  314. // The SSL stack requires BIOs handle BIO_flush.
  315. return 1;
  316. }
  317. NOTIMPLEMENTED();
  318. return 0;
  319. }
  320. const BIO_METHOD SocketBIOAdapter::kBIOMethod = {
  321. 0, // type (unused)
  322. nullptr, // name (unused)
  323. SocketBIOAdapter::BIOWriteWrapper,
  324. SocketBIOAdapter::BIOReadWrapper,
  325. nullptr, // puts
  326. nullptr, // gets
  327. SocketBIOAdapter::BIOCtrlWrapper,
  328. nullptr, // create
  329. nullptr, // destroy
  330. nullptr, // callback_ctrl
  331. };
  332. } // namespace net