VpnPlugin.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. ) {
  102. channel.TerminateConnection(L"Failed to set environment variables: " + winrt::to_hstring((uint32_t)GetLastError()));
  103. return;
  104. }
  105. const auto confPathW = localProperties.TryLookup(CONFIG_PATH_SETTING_KEY).try_as<hstring>().value_or(L"");
  106. const auto confPath = winrt::to_string(confPathW);
  107. StorageFolder folder{ nullptr };
  108. try {
  109. folder = StorageApplicationPermissions::FutureAccessList().GetFolderAsync(ConfigFolderAccessListKey).get();
  110. }
  111. catch (hresult_invalid_argument const&) {}
  112. thread_local std::vector<HostName> dnsHosts{};
  113. if (folder)
  114. {
  115. if (auto const pos = confPath.rfind('\\'); pos != std::string::npos)
  116. {
  117. auto const file = folder.GetFileAsync(to_hstring(confPath.substr(pos + 1))).get();
  118. auto const text = FileIO::ReadBufferAsync(file).get();
  119. auto const len = text.Length();
  120. uint8_t* textPtr{};
  121. check_hresult(text.as<IBufferByteAccess>()->Buffer(&textPtr));
  122. m_leaf = uwp_run_leaf_with_config_content(reinterpret_cast<const char*>(textPtr), len,
  123. [](const char* dns) {
  124. dnsHosts.push_back(HostName{ to_hstring(dns) });
  125. });
  126. }
  127. else
  128. {
  129. channel.TerminateConnection(L"Config folder has been changed. Please reset the default configuration file.");
  130. return;
  131. }
  132. }
  133. else
  134. {
  135. m_leaf = uwp_run_leaf(confPath.data(), [](const char* dns) {
  136. dnsHosts.push_back(HostName{ to_hstring(dns) });
  137. });
  138. }
  139. if (m_leaf == nullptr) {
  140. 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.");
  141. StopLeaf();
  142. return;
  143. }
  144. VpnDomainNameAssignment dnsAssignment{};
  145. dnsAssignment.DomainNameList().Append(VpnDomainNameInfo(
  146. L".",
  147. VpnDomainNameType::Suffix,
  148. single_threaded_vector(std::move(dnsHosts)),
  149. single_threaded_vector(std::vector<HostName>())));
  150. channel.StartWithMainTransport(
  151. std::vector<HostName> { HostName{ L"192.168.3.1" } },
  152. nullptr,
  153. nullptr,
  154. routeScope,
  155. dnsAssignment,
  156. 1500,
  157. 1512,
  158. false,
  159. transport
  160. );
  161. }
  162. void VpnPlugin::StopLeaf() {
  163. m_backTransport = nullptr;
  164. auto leafHandle = m_leaf;
  165. if (leafHandle != nullptr) {
  166. uwp_stop_leaf(leafHandle);
  167. m_leaf = nullptr;
  168. }
  169. auto netStackHandle = m_netStackHandle;
  170. if (netStackHandle != nullptr) {
  171. const auto context = netstack_release(netStackHandle);
  172. m_netStackHandle = nullptr;
  173. // Release context, which is an ABI of IOutputStream
  174. IInspectable obj{};
  175. winrt::attach_abi(obj, context);
  176. m_netStackHandle = nullptr;
  177. }
  178. }
  179. void VpnPlugin::Disconnect(VpnChannel const& channel)
  180. {
  181. try {
  182. channel.Stop();
  183. }
  184. catch (...) {}
  185. StopLeaf();
  186. }
  187. void VpnPlugin::GetKeepAlivePayload(VpnChannel const&, VpnPacketBuffer&)
  188. {
  189. }
  190. void VpnPlugin::Encapsulate([[maybe_unused]] VpnChannel const& channel, VpnPacketBufferList const& packets, VpnPacketBufferList const&)
  191. {
  192. auto packetCount = packets.Size();
  193. while (packetCount-- > 0) {
  194. const auto packet = packets.RemoveAtBegin();
  195. const auto buffer = packet.Buffer();
  196. netstack_send(m_netStackHandle, buffer.data(), static_cast<size_t>(buffer.Length()));
  197. packets.Append(packet);
  198. }
  199. }
  200. void VpnPlugin::Decapsulate(VpnChannel const& channel, [[maybe_unused]] VpnPacketBuffer const& encapBuffer, VpnPacketBufferList const& decapsulatedPackets, VpnPacketBufferList const&)
  201. {
  202. std::lock_guard _guard{ VpnPluginInstance->m_decapQueueLock };
  203. auto& q = VpnPluginInstance->m_decapQueue;
  204. while (!q.empty()) {
  205. auto&& incomingBuffer = q.front();
  206. const auto outBuffer = channel.GetVpnReceivePacketBuffer();
  207. decapsulatedPackets.Append(outBuffer);
  208. const auto outBuf = outBuffer.Buffer();
  209. const auto size = incomingBuffer.size();
  210. if (memcpy_s(outBuf.data(), outBuf.Capacity(), incomingBuffer.data(), size)) {
  211. return;
  212. }
  213. outBuf.Length(static_cast<uint32_t>(size));
  214. q.pop();
  215. }
  216. }
  217. }