From 7e7a7df7bff73f2051e30f782380d32e2728723c Mon Sep 17 00:00:00 2001
From: Christopher Dykes <cdykes@fb.com>
Date: Wed, 17 Aug 2016 14:42:29 -0700
Subject: [PATCH] Add a pair of util functions for getting and setting the BIO
 fd

Summary: Because we need to translate them between sockets and file descriptors when we're on Windows.

Reviewed By: yfeldblum

Differential Revision: D3724802

fbshipit-source-id: 07fff6e1bec7b9b90e0d39fd98441466a746b7f7
---
 folly/io/async/AsyncSSLSocket.cpp   |  6 +++---
 folly/io/async/ssl/OpenSSLUtils.cpp | 21 +++++++++++++++++++++
 folly/io/async/ssl/OpenSSLUtils.h   |  2 ++
 3 files changed, 26 insertions(+), 3 deletions(-)

diff --git a/folly/io/async/AsyncSSLSocket.cpp b/folly/io/async/AsyncSSLSocket.cpp
index c16e6fb6..5efa402e 100644
--- a/folly/io/async/AsyncSSLSocket.cpp
+++ b/folly/io/async/AsyncSSLSocket.cpp
@@ -699,7 +699,7 @@ bool AsyncSSLSocket::setupSSLBio() {
   }
 
   OpenSSLUtils::setBioAppData(wb, this);
-  BIO_set_fd(wb, fd_, BIO_NOCLOSE);
+  OpenSSLUtils::setBioFd(wb, fd_, BIO_NOCLOSE);
   SSL_set_bio(ssl_, wb, wb);
   return true;
 }
@@ -1590,8 +1590,8 @@ int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) {
   flags |= MSG_NOSIGNAL;
 #endif
 
-  auto result =
-      tsslSock->sendSocketMessage(BIO_get_fd(b, nullptr), &msg, flags);
+  auto result = tsslSock->sendSocketMessage(
+      OpenSSLUtils::getBioFd(b, nullptr), &msg, flags);
   BIO_clear_retry_flags(b);
   if (!result.exception && result.writeReturn <= 0) {
     if (OpenSSLUtils::getBioShouldRetryWrite(result.writeReturn)) {
diff --git a/folly/io/async/ssl/OpenSSLUtils.cpp b/folly/io/async/ssl/OpenSSLUtils.cpp
index 01aa8548..57558320 100644
--- a/folly/io/async/ssl/OpenSSLUtils.cpp
+++ b/folly/io/async/ssl/OpenSSLUtils.cpp
@@ -180,6 +180,27 @@ void OpenSSLUtils::setCustomBioMethod(BIO* b, BIO_METHOD* meth) {
 #endif
 }
 
+int OpenSSLUtils::getBioFd(BIO* b, int* fd) {
+#ifdef _WIN32
+  int ret = portability::sockets::socket_to_fd((SOCKET)BIO_get_fd(b, fd));
+  if (fd != nullptr) {
+    *fd = ret;
+  }
+  return ret;
+#else
+  return BIO_get_fd(b, fd);
+#endif
+}
+
+void OpenSSLUtils::setBioFd(BIO* b, int fd, int flags) {
+#ifdef _WIN32
+  SOCKET sock = portability::sockets::fd_to_socket(fd);
+#else
+  int sock = fd;
+#endif
+  BIO_set_fd(b, sock, flags);
+}
+
 } // ssl
 } // folly
 
diff --git a/folly/io/async/ssl/OpenSSLUtils.h b/folly/io/async/ssl/OpenSSLUtils.h
index 252785e3..204cb431 100644
--- a/folly/io/async/ssl/OpenSSLUtils.h
+++ b/folly/io/async/ssl/OpenSSLUtils.h
@@ -69,6 +69,8 @@ class OpenSSLUtils {
   static void setBioAppData(BIO* b, void* ptr);
   static void* getBioAppData(BIO* b);
   static void setCustomBioMethod(BIO*, BIO_METHOD*);
+  static int getBioFd(BIO* b, int* fd);
+  static void setBioFd(BIO* b, int fd, int flags);
 };
 
 } // ssl
-- 
2.34.1