From 3d99eb64c455101fcbf8c19b6726bd6e981a42e0 Mon Sep 17 00:00:00 2001
From: Bensong Liu <bensl@microsoft.com>
Date: Thu, 30 Jul 2020 17:11:33 +0800
Subject: [PATCH] bug fix

---
 src/common.hpp                 | 8 +++++++-
 src/filters/base.hpp           | 2 +-
 src/filters/xor_encryption.hpp | 2 +-
 src/utils.hpp                  | 6 ++++--
 4 files changed, 13 insertions(+), 5 deletions(-)

diff --git a/src/common.hpp b/src/common.hpp
index 91077cc..a6739ec 100644
--- a/src/common.hpp
+++ b/src/common.hpp
@@ -16,8 +16,14 @@ constexpr size_t DGRAM_BUFFER_SIZE = 20480;
 //   to the real openvpn server.
 constexpr size_t SERVER_ENCRYPT_CONNECTION_TIMEOUT_SECONDS = 60;
 
+#include <random> 
 // MAGIC PORT NUMBER! Warning! Used for Inbound - Outbound IPC talking. Windows wepoll doesn't support PIPE, so I have to use this. 
-constexpr uint16_t TCP_TMP_PORT_NUMBER = 50999;
+uint16_t get_tmp_tcp_port_number() {
+	std::random_device rd;
+    std::mt19937 mt(rd());
+    std::uniform_int_distribution<int> dist(40000, 60000);
+    return dist(mt);
+}
 
 #endif
 
diff --git a/src/filters/base.hpp b/src/filters/base.hpp
index e5b519f..fbf5d8d 100644
--- a/src/filters/base.hpp
+++ b/src/filters/base.hpp
@@ -44,7 +44,7 @@ namespace Filters {
 		// Usually the decrypt/decode/de-obfs function.
 		virtual string convertBackward(string binaryDatagram) override {
 			for (auto iter = chainedFilters.rbegin(); iter != chainedFilters.rend(); ++iter) {
-				binaryDatagram = (*iter)->convertForward(binaryDatagram);
+				binaryDatagram = (*iter)->convertBackward(binaryDatagram);
 			}
 			return binaryDatagram;
 		}
diff --git a/src/filters/xor_encryption.hpp b/src/filters/xor_encryption.hpp
index 639acdd..2ab5661 100644
--- a/src/filters/xor_encryption.hpp
+++ b/src/filters/xor_encryption.hpp
@@ -21,7 +21,7 @@ namespace Filters {
 		virtual string convertForward(string datagram) override {
 			auto curr_key_digit = 0;
 			for (auto offset = 0; offset < datagram.size(); ++offset) {
-				datagram[0] ^= key[curr_key_digit++];
+				datagram[offset] ^= key[curr_key_digit++];
 			}
 			return datagram;
 		}
diff --git a/src/utils.hpp b/src/utils.hpp
index 89967f4..d2f133d 100644
--- a/src/utils.hpp
+++ b/src/utils.hpp
@@ -79,12 +79,14 @@ inline auto mkpipe() {
 
 inline auto mk_tcp_pipe() {
     sockfd_t connfd_cli_side, connfd_srv_side;
-    auto listenfd = rlib::quick_listen("::1", TCP_TMP_PORT_NUMBER);
+    auto tmp_port = get_tmp_tcp_port_number();
+    auto listenfd = rlib::quick_listen("::1", tmp_port); // We have no UnixSocket on Windows.
     auto serverThread = std::thread([&] {
         connfd_srv_side = rlib::quick_accept(listenfd);
     });
-    connfd_cli_side = rlib::quick_connect("::1", TCP_TMP_PORT_NUMBER);
+    connfd_cli_side = rlib::quick_connect("::1", tmp_port);
     serverThread.join();
+    rlib::sockIO::close_ex(listenfd);
     return std::make_pair(connfd_cli_side, connfd_srv_side);
 }
 
-- 
GitLab