VpnPlugin.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. #include "pch.h"
  2. #include "VpnPlugin.h"
  3. #include "winrt/Windows.Storage.h"
  4. #include "winrt/Windows.Storage.Streams.h"
  5. #include "winrt/Windows.Storage.AccessCache.h"
  6. extern "C" void* lwip_strerr(uint8_t) {
  7. return (void*)(const char*)"";
  8. }
  9. namespace winrt::Maple_Task::implementation
  10. {
  11. using Windows::Networking::HostName;
  12. using Windows::Networking::Sockets::DatagramSocket;
  13. using Windows::Storage::Streams::IOutputStream;
  14. using namespace Windows::Networking::Vpn;
  15. using namespace Windows::Storage;
  16. using namespace Windows::Storage::AccessCache;
  17. extern "C" {
  18. typedef void(__cdecl* netstack_cb)(uint8_t*, size_t, void*);
  19. void cb(uint8_t* data, size_t size, void* outputStreamAbi) {
  20. bool needSendDummyBuffer = false;
  21. {
  22. std::lock_guard _guard{ VpnPluginInstance->m_decapQueueLock };
  23. auto& q = VpnPluginInstance->m_decapQueue;
  24. {
  25. std::vector<uint8_t> buf(size);
  26. if (memcpy_s(buf.data(), buf.capacity(), data, size)) {
  27. return;
  28. }
  29. needSendDummyBuffer = q.empty();
  30. q.emplace(buf);
  31. }
  32. }
  33. if (!needSendDummyBuffer) {
  34. return;
  35. }
  36. IOutputStream outputStream{ nullptr };
  37. winrt::attach_abi(outputStream, outputStreamAbi);
  38. try {
  39. const auto _ = outputStream.WriteAsync(dummyBuffer);
  40. }
  41. catch (...) {}
  42. winrt::detach_abi(outputStream);
  43. }
  44. }
  45. void VpnPlugin::Connect(VpnChannel const& channel)
  46. {
  47. try
  48. {
  49. ConnectCore(channel);
  50. }
  51. catch (std::exception const& ex)
  52. {
  53. channel.TerminateConnection(to_hstring(ex.what()));
  54. }
  55. }
  56. void VpnPlugin::ConnectCore(VpnChannel const& channel)
  57. {
  58. const auto localhost = HostName{ L"127.0.0.1" };
  59. DatagramSocket transport{}, backTransport{};
  60. channel.AssociateTransport(transport, nullptr);
  61. transport.BindEndpointAsync(localhost, L"").get();
  62. backTransport.BindEndpointAsync(localhost, L"").get();
  63. transport.ConnectAsync(localhost, backTransport.Information().LocalPort()).get();
  64. backTransport.ConnectAsync(localhost, transport.Information().LocalPort()).get();
  65. VpnRouteAssignment routeScope{};
  66. routeScope.ExcludeLocalSubnets(true);
  67. routeScope.Ipv4InclusionRoutes(std::vector<VpnRoute>{
  68. // 直接写 0.0.0.0/0 哪怕绑了接口也会绕回环
  69. // VpnRoute(HostName{ L"0.0.0.0" }, 0)
  70. VpnRoute(HostName{ L"0.0.0.0" }, 1),
  71. VpnRoute(HostName{ L"128.0.0.0" }, 1),
  72. });
  73. // 排除代理服务器的话就会 os 10023 以一种访问权限不允许的方式做了一个访问套接字的尝试
  74. // routeScope.Ipv4ExclusionRoutes(std::vector<VpnRoute>{
  75. // VpnRoute(HostName{ L"172.25.0.0" }, 16)
  76. // });
  77. const auto outputStreamAbi = winrt::detach_abi(backTransport.OutputStream());
  78. StopLeaf();
  79. {
  80. std::lock_guard _guard{ m_decapQueueLock };
  81. while (!m_decapQueue.empty()) {
  82. m_decapQueue.pop();
  83. }
  84. }
  85. m_backTransport = backTransport;
  86. m_netStackHandle = netstack_register(cb, outputStreamAbi);
  87. if (m_netStackHandle == nullptr) {
  88. channel.TerminateConnection(L"Error initializing Leaf netstack.");
  89. return;
  90. }
  91. const auto& appData = ApplicationData::Current();
  92. const auto& configFolderPath = appData.LocalFolder().CreateFolderAsync(L"config", CreationCollisionOption::OpenIfExists).get().Path();
  93. const auto& localProperties = appData.LocalSettings().Values();
  94. const auto& outNetif = localProperties.TryLookup(NETIF_SETTING_KEY).try_as<hstring>().value_or(L"");
  95. const auto& cacheDir = appData.LocalCacheFolder().Path();
  96. if (
  97. !SetEnvironmentVariable(L"ASSET_LOCATION", configFolderPath.data())
  98. || !SetEnvironmentVariable(L"LOG_NO_COLOR", L"true")
  99. || !SetEnvironmentVariable(L"OUTBOUND_INTERFACE", outNetif.data())
  100. || !SetEnvironmentVariable(L"CACHE_LOCATION", cacheDir.data())
  101. || !SetEnvironmentVariable(L"ENABLE_IPV6", L"true")
  102. ) {
  103. channel.TerminateConnection(L"Failed to set environment variables: " + winrt::to_hstring((uint32_t)GetLastError()));
  104. return;
  105. }
  106. const auto confPathW = localProperties.TryLookup(CONFIG_PATH_SETTING_KEY).try_as<hstring>().value_or(L"");
  107. const auto confPath = winrt::to_string(confPathW);
  108. StorageFolder folder{ nullptr };
  109. try {
  110. folder = StorageApplicationPermissions::FutureAccessList().GetFolderAsync(ConfigFolderAccessListKey).get();
  111. }
  112. catch (hresult_invalid_argument const&) {}
  113. thread_local std::vector<HostName> dnsHosts{};
  114. if (folder)
  115. {
  116. if (auto const pos = confPath.rfind('\\'); pos != std::string::npos)
  117. {
  118. auto const file = folder.GetFileAsync(to_hstring(confPath.substr(pos + 1))).get();
  119. auto const text = FileIO::ReadBufferAsync(file).get();
  120. auto const len = text.Length();
  121. uint8_t* textPtr{};
  122. check_hresult(text.as<IBufferByteAccess>()->Buffer(&textPtr));
  123. m_leaf = uwp_run_leaf_with_config_content(reinterpret_cast<const char*>(textPtr), len,
  124. [](const char* dns) {
  125. dnsHosts.push_back(HostName{ to_hstring(dns) });
  126. });
  127. }
  128. else
  129. {
  130. channel.TerminateConnection(L"Config folder has been changed. Please reset the default configuration file.");
  131. return;
  132. }
  133. }
  134. else
  135. {
  136. m_leaf = uwp_run_leaf(confPath.data(), [](const char* dns) {
  137. dnsHosts.push_back(HostName{ to_hstring(dns) });
  138. });
  139. }
  140. if (m_leaf == nullptr) {
  141. channel.TerminateConnection(L"Error initializing Leaf runtime.\r\nPlease check your configuration file and default interface.\r\nPlease make sure all associated files (.dat, .mmdb, .cer) exist.");
  142. StopLeaf();
  143. return;
  144. }
  145. VpnDomainNameAssignment dnsAssignment{};
  146. dnsAssignment.DomainNameList().Append(VpnDomainNameInfo(
  147. L".",
  148. VpnDomainNameType::Suffix,
  149. single_threaded_vector(std::move(dnsHosts)),
  150. single_threaded_vector(std::vector<HostName>())));
  151. channel.StartWithMainTransport(
  152. std::vector<HostName> { HostName{ L"192.168.3.1" } },
  153. nullptr,
  154. nullptr,
  155. routeScope,
  156. dnsAssignment,
  157. 1500,
  158. 1512,
  159. false,
  160. transport
  161. );
  162. }
  163. void VpnPlugin::StopLeaf() {
  164. m_backTransport = nullptr;
  165. auto leafHandle = m_leaf;
  166. if (leafHandle != nullptr) {
  167. uwp_stop_leaf(leafHandle);
  168. m_leaf = nullptr;
  169. }
  170. auto netStackHandle = m_netStackHandle;
  171. if (netStackHandle != nullptr) {
  172. const auto context = netstack_release(netStackHandle);
  173. m_netStackHandle = nullptr;
  174. // Release context, which is an ABI of IOutputStream
  175. IInspectable obj{};
  176. winrt::attach_abi(obj, context);
  177. m_netStackHandle = nullptr;
  178. }
  179. }
  180. void VpnPlugin::Disconnect(VpnChannel const& channel)
  181. {
  182. try {
  183. channel.Stop();
  184. }
  185. catch (...) {}
  186. StopLeaf();
  187. }
  188. void VpnPlugin::GetKeepAlivePayload(VpnChannel const&, VpnPacketBuffer&)
  189. {
  190. }
  191. void VpnPlugin::Encapsulate([[maybe_unused]] VpnChannel const& channel, VpnPacketBufferList const& packets, VpnPacketBufferList const&)
  192. {
  193. auto packetCount = packets.Size();
  194. while (packetCount-- > 0) {
  195. const auto packet = packets.RemoveAtBegin();
  196. const auto buffer = packet.Buffer();
  197. netstack_send(m_netStackHandle, buffer.data(), static_cast<size_t>(buffer.Length()));
  198. packets.Append(packet);
  199. }
  200. }
  201. void VpnPlugin::Decapsulate(VpnChannel const& channel, [[maybe_unused]] VpnPacketBuffer const& encapBuffer, VpnPacketBufferList const& decapsulatedPackets, VpnPacketBufferList const&)
  202. {
  203. std::lock_guard _guard{ VpnPluginInstance->m_decapQueueLock };
  204. auto& q = VpnPluginInstance->m_decapQueue;
  205. while (!q.empty()) {
  206. auto&& incomingBuffer = q.front();
  207. const auto outBuffer = channel.GetVpnReceivePacketBuffer();
  208. decapsulatedPackets.Append(outBuffer);
  209. const auto outBuf = outBuffer.Buffer();
  210. const auto size = incomingBuffer.size();
  211. if (memcpy_s(outBuf.data(), outBuf.Capacity(), incomingBuffer.data(), size)) {
  212. return;
  213. }
  214. outBuf.Length(static_cast<uint32_t>(size));
  215. q.pop();
  216. }
  217. }
  218. }