VpnPlugin.cpp 6.6 KB

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