VpnPlugin.cpp 7.1 KB

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