IResolver.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. using Ryujinx.Common.Logging;
  2. using Ryujinx.Common.Memory;
  3. using Ryujinx.Cpu;
  4. using Ryujinx.HLE.HOS.Services.Sockets.Nsd.Manager;
  5. using Ryujinx.HLE.HOS.Services.Sockets.Sfdnsres.Proxy;
  6. using Ryujinx.HLE.HOS.Services.Sockets.Sfdnsres.Types;
  7. using Ryujinx.Memory;
  8. using System;
  9. using System.Buffers.Binary;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Net;
  13. using System.Net.Sockets;
  14. using System.Runtime.CompilerServices;
  15. using System.Runtime.InteropServices;
  16. using System.Text;
  17. namespace Ryujinx.HLE.HOS.Services.Sockets.Sfdnsres
  18. {
  19. [Service("sfdnsres")]
  20. class IResolver : IpcService
  21. {
  22. public IResolver(ServiceCtx context) { }
  23. [CommandHipc(0)]
  24. // SetDnsAddressesPrivateRequest(u32, buffer<unknown, 5, 0>)
  25. public ResultCode SetDnsAddressesPrivateRequest(ServiceCtx context)
  26. {
  27. uint cancelHandleRequest = context.RequestData.ReadUInt32();
  28. ulong bufferPosition = context.Request.SendBuff[0].Position;
  29. ulong bufferSize = context.Request.SendBuff[0].Size;
  30. // TODO: This is stubbed in 2.0.0+, reverse 1.0.0 version for the sake of completeness.
  31. Logger.Stub?.PrintStub(LogClass.ServiceSfdnsres, new { cancelHandleRequest });
  32. return ResultCode.NotAllocated;
  33. }
  34. [CommandHipc(1)]
  35. // GetDnsAddressPrivateRequest(u32) -> buffer<unknown, 6, 0>
  36. public ResultCode GetDnsAddressPrivateRequest(ServiceCtx context)
  37. {
  38. uint cancelHandleRequest = context.RequestData.ReadUInt32();
  39. ulong bufferPosition = context.Request.ReceiveBuff[0].Position;
  40. ulong bufferSize = context.Request.ReceiveBuff[0].Size;
  41. // TODO: This is stubbed in 2.0.0+, reverse 1.0.0 version for the sake of completeness.
  42. Logger.Stub?.PrintStub(LogClass.ServiceSfdnsres, new { cancelHandleRequest });
  43. return ResultCode.NotAllocated;
  44. }
  45. [CommandHipc(2)]
  46. // GetHostByNameRequest(u8, u32, u64, pid, buffer<unknown, 5, 0>) -> (u32, u32, u32, buffer<unknown, 6, 0>)
  47. public ResultCode GetHostByNameRequest(ServiceCtx context)
  48. {
  49. ulong inputBufferPosition = context.Request.SendBuff[0].Position;
  50. ulong inputBufferSize = context.Request.SendBuff[0].Size;
  51. ulong outputBufferPosition = context.Request.ReceiveBuff[0].Position;
  52. ulong outputBufferSize = context.Request.ReceiveBuff[0].Size;
  53. return GetHostByNameRequestImpl(context, inputBufferPosition, inputBufferSize, outputBufferPosition, outputBufferSize, false, 0, 0);
  54. }
  55. [CommandHipc(3)]
  56. // GetHostByAddrRequest(u32, u32, u32, u64, pid, buffer<unknown, 5, 0>) -> (u32, u32, u32, buffer<unknown, 6, 0>)
  57. public ResultCode GetHostByAddrRequest(ServiceCtx context)
  58. {
  59. ulong inputBufferPosition = context.Request.SendBuff[0].Position;
  60. ulong inputBufferSize = context.Request.SendBuff[0].Size;
  61. ulong outputBufferPosition = context.Request.ReceiveBuff[0].Position;
  62. ulong outputBufferSize = context.Request.ReceiveBuff[0].Size;
  63. return GetHostByAddrRequestImpl(context, inputBufferPosition, inputBufferSize, outputBufferPosition, outputBufferSize, false, 0, 0);
  64. }
  65. [CommandHipc(4)]
  66. // GetHostStringErrorRequest(u32) -> buffer<unknown, 6, 0>
  67. public ResultCode GetHostStringErrorRequest(ServiceCtx context)
  68. {
  69. ResultCode resultCode = ResultCode.NotAllocated;
  70. NetDbError errorCode = (NetDbError)context.RequestData.ReadInt32();
  71. string errorString = errorCode switch
  72. {
  73. NetDbError.Success => "Resolver Error 0 (no error)",
  74. NetDbError.HostNotFound => "Unknown host",
  75. NetDbError.TryAgain => "Host name lookup failure",
  76. NetDbError.NoRecovery => "Unknown server error",
  77. NetDbError.NoData => "No address associated with name",
  78. _ => (errorCode <= NetDbError.Internal) ? "Resolver internal error" : "Unknown resolver error"
  79. };
  80. ulong bufferPosition = context.Request.ReceiveBuff[0].Position;
  81. ulong bufferSize = context.Request.ReceiveBuff[0].Size;
  82. if ((ulong)(errorString.Length + 1) <= bufferSize)
  83. {
  84. context.Memory.Write(bufferPosition, Encoding.ASCII.GetBytes(errorString + '\0'));
  85. resultCode = ResultCode.Success;
  86. }
  87. return resultCode;
  88. }
  89. [CommandHipc(5)]
  90. // GetGaiStringErrorRequest(u32) -> buffer<byte, 6, 0>
  91. public ResultCode GetGaiStringErrorRequest(ServiceCtx context)
  92. {
  93. ResultCode resultCode = ResultCode.NotAllocated;
  94. GaiError errorCode = (GaiError)context.RequestData.ReadInt32();
  95. if (errorCode > GaiError.Max)
  96. {
  97. errorCode = GaiError.Max;
  98. }
  99. string errorString = errorCode switch
  100. {
  101. GaiError.AddressFamily => "Address family for hostname not supported",
  102. GaiError.Again => "Temporary failure in name resolution",
  103. GaiError.BadFlags => "Invalid value for ai_flags",
  104. GaiError.Fail => "Non-recoverable failure in name resolution",
  105. GaiError.Family => "ai_family not supported",
  106. GaiError.Memory => "Memory allocation failure",
  107. GaiError.NoData => "No address associated with hostname",
  108. GaiError.NoName => "hostname nor servname provided, or not known",
  109. GaiError.Service => "servname not supported for ai_socktype",
  110. GaiError.SocketType => "ai_socktype not supported",
  111. GaiError.System => "System error returned in errno",
  112. GaiError.BadHints => "Invalid value for hints",
  113. GaiError.Protocol => "Resolved protocol is unknown",
  114. GaiError.Overflow => "Argument buffer overflow",
  115. GaiError.Max => "Unknown error",
  116. _ => "Success"
  117. };
  118. ulong bufferPosition = context.Request.ReceiveBuff[0].Position;
  119. ulong bufferSize = context.Request.ReceiveBuff[0].Size;
  120. if ((ulong)(errorString.Length + 1) <= bufferSize)
  121. {
  122. context.Memory.Write(bufferPosition, Encoding.ASCII.GetBytes(errorString + '\0'));
  123. resultCode = ResultCode.Success;
  124. }
  125. return resultCode;
  126. }
  127. [CommandHipc(6)]
  128. // GetAddrInfoRequest(bool enable_nsd_resolve, u32, u64 pid_placeholder, pid, buffer<i8, 5, 0> host, buffer<i8, 5, 0> service, buffer<packed_addrinfo, 5, 0> hints) -> (i32 ret, u32 bsd_errno, u32 packed_addrinfo_size, buffer<packed_addrinfo, 6, 0> response)
  129. public ResultCode GetAddrInfoRequest(ServiceCtx context)
  130. {
  131. ulong responseBufferPosition = context.Request.ReceiveBuff[0].Position;
  132. ulong responseBufferSize = context.Request.ReceiveBuff[0].Size;
  133. return GetAddrInfoRequestImpl(context, responseBufferPosition, responseBufferSize, false, 0, 0);
  134. }
  135. [CommandHipc(8)]
  136. // GetCancelHandleRequest(u64, pid) -> u32
  137. public ResultCode GetCancelHandleRequest(ServiceCtx context)
  138. {
  139. ulong pidPlaceHolder = context.RequestData.ReadUInt64();
  140. uint cancelHandleRequest = 0;
  141. context.ResponseData.Write(cancelHandleRequest);
  142. Logger.Stub?.PrintStub(LogClass.ServiceSfdnsres, new { cancelHandleRequest });
  143. return ResultCode.Success;
  144. }
  145. [CommandHipc(9)]
  146. // CancelRequest(u32, u64, pid)
  147. public ResultCode CancelRequest(ServiceCtx context)
  148. {
  149. uint cancelHandleRequest = context.RequestData.ReadUInt32();
  150. ulong pidPlaceHolder = context.RequestData.ReadUInt64();
  151. Logger.Stub?.PrintStub(LogClass.ServiceSfdnsres, new { cancelHandleRequest });
  152. return ResultCode.Success;
  153. }
  154. [CommandHipc(10)] // 5.0.0+
  155. // GetHostByNameRequestWithOptions(u8, u32, u64, pid, buffer<unknown, 21, 0>, buffer<unknown, 21, 0>) -> (u32, u32, u32, buffer<unknown, 22, 0>)
  156. public ResultCode GetHostByNameRequestWithOptions(ServiceCtx context)
  157. {
  158. (ulong inputBufferPosition, ulong inputBufferSize) = context.Request.GetBufferType0x21();
  159. (ulong outputBufferPosition, ulong outputBufferSize) = context.Request.GetBufferType0x22();
  160. (ulong optionsBufferPosition, ulong optionsBufferSize) = context.Request.GetBufferType0x21();
  161. return GetHostByNameRequestImpl(
  162. context,
  163. inputBufferPosition,
  164. inputBufferSize,
  165. outputBufferPosition,
  166. outputBufferSize,
  167. true,
  168. optionsBufferPosition,
  169. optionsBufferSize);
  170. }
  171. [CommandHipc(11)] // 5.0.0+
  172. // GetHostByAddrRequestWithOptions(u32, u32, u32, u64, pid, buffer<unknown, 21, 0>, buffer<unknown, 21, 0>) -> (u32, u32, u32, buffer<unknown, 22, 0>)
  173. public ResultCode GetHostByAddrRequestWithOptions(ServiceCtx context)
  174. {
  175. (ulong inputBufferPosition, ulong inputBufferSize) = context.Request.GetBufferType0x21();
  176. (ulong outputBufferPosition, ulong outputBufferSize) = context.Request.GetBufferType0x22();
  177. (ulong optionsBufferPosition, ulong optionsBufferSize) = context.Request.GetBufferType0x21();
  178. return GetHostByAddrRequestImpl(
  179. context,
  180. inputBufferPosition,
  181. inputBufferSize,
  182. outputBufferPosition,
  183. outputBufferSize,
  184. true,
  185. optionsBufferPosition,
  186. optionsBufferSize);
  187. }
  188. [CommandHipc(12)] // 5.0.0+
  189. // GetAddrInfoRequestWithOptions(bool enable_nsd_resolve, u32, u64 pid_placeholder, pid, buffer<i8, 5, 0> host, buffer<i8, 5, 0> service, buffer<packed_addrinfo, 5, 0> hints, buffer<unknown, 21, 0>) -> (i32 ret, u32 bsd_errno, u32 unknown, u32 packed_addrinfo_size, buffer<packed_addrinfo, 22, 0> response)
  190. public ResultCode GetAddrInfoRequestWithOptions(ServiceCtx context)
  191. {
  192. (ulong outputBufferPosition, ulong outputBufferSize) = context.Request.GetBufferType0x22();
  193. (ulong optionsBufferPosition, ulong optionsBufferSize) = context.Request.GetBufferType0x21();
  194. return GetAddrInfoRequestImpl(context, outputBufferPosition, outputBufferSize, true, optionsBufferPosition, optionsBufferSize);
  195. }
  196. private static ResultCode GetHostByNameRequestImpl(
  197. ServiceCtx context,
  198. ulong inputBufferPosition,
  199. ulong inputBufferSize,
  200. ulong outputBufferPosition,
  201. ulong outputBufferSize,
  202. bool withOptions,
  203. ulong optionsBufferPosition,
  204. ulong optionsBufferSize)
  205. {
  206. string host = MemoryHelper.ReadAsciiString(context.Memory, inputBufferPosition, (int)inputBufferSize);
  207. if (!context.Device.Configuration.EnableInternetAccess)
  208. {
  209. Logger.Info?.Print(LogClass.ServiceSfdnsres, $"Guest network access disabled, DNS Blocked: {host}");
  210. WriteResponse(context, withOptions, 0, GaiError.NoData, NetDbError.HostNotFound);
  211. return ResultCode.Success;
  212. }
  213. // TODO: Use params.
  214. bool enableNsdResolve = (context.RequestData.ReadInt32() & 1) != 0;
  215. int timeOut = context.RequestData.ReadInt32();
  216. ulong pidPlaceholder = context.RequestData.ReadUInt64();
  217. if (withOptions)
  218. {
  219. // TODO: Parse and use options.
  220. }
  221. IPHostEntry hostEntry = null;
  222. NetDbError netDbErrorCode = NetDbError.Success;
  223. GaiError errno = GaiError.Overflow;
  224. int serializedSize = 0;
  225. if (host.Length <= byte.MaxValue)
  226. {
  227. if (enableNsdResolve)
  228. {
  229. if (FqdnResolver.Resolve(host, out string newAddress) == Nsd.ResultCode.Success)
  230. {
  231. host = newAddress;
  232. }
  233. }
  234. string targetHost = host;
  235. if (DnsBlacklist.IsHostBlocked(host))
  236. {
  237. Logger.Info?.Print(LogClass.ServiceSfdnsres, $"DNS Blocked: {host}");
  238. netDbErrorCode = NetDbError.HostNotFound;
  239. errno = GaiError.NoData;
  240. }
  241. else
  242. {
  243. Logger.Info?.Print(LogClass.ServiceSfdnsres, $"Trying to resolve: {host}");
  244. try
  245. {
  246. hostEntry = Dns.GetHostEntry(targetHost);
  247. }
  248. catch (SocketException exception)
  249. {
  250. netDbErrorCode = ConvertSocketErrorCodeToNetDbError(exception.ErrorCode);
  251. errno = ConvertSocketErrorCodeToGaiError(exception.ErrorCode, errno);
  252. }
  253. }
  254. }
  255. else
  256. {
  257. netDbErrorCode = NetDbError.HostNotFound;
  258. }
  259. if (hostEntry != null)
  260. {
  261. IEnumerable<IPAddress> addresses = GetIpv4Addresses(hostEntry);
  262. if (!addresses.Any())
  263. {
  264. errno = GaiError.NoData;
  265. netDbErrorCode = NetDbError.NoAddress;
  266. }
  267. else
  268. {
  269. errno = GaiError.Success;
  270. serializedSize = SerializeHostEntries(context, outputBufferPosition, outputBufferSize, hostEntry, addresses);
  271. }
  272. }
  273. WriteResponse(context, withOptions, serializedSize, errno, netDbErrorCode);
  274. return ResultCode.Success;
  275. }
  276. private static ResultCode GetHostByAddrRequestImpl(
  277. ServiceCtx context,
  278. ulong inputBufferPosition,
  279. ulong inputBufferSize,
  280. ulong outputBufferPosition,
  281. ulong outputBufferSize,
  282. bool withOptions,
  283. ulong optionsBufferPosition,
  284. ulong optionsBufferSize)
  285. {
  286. if (!context.Device.Configuration.EnableInternetAccess)
  287. {
  288. Logger.Info?.Print(LogClass.ServiceSfdnsres, $"Guest network access disabled, DNS Blocked.");
  289. WriteResponse(context, withOptions, 0, GaiError.NoData, NetDbError.HostNotFound);
  290. return ResultCode.Success;
  291. }
  292. byte[] rawIp = new byte[inputBufferSize];
  293. context.Memory.Read(inputBufferPosition, rawIp);
  294. // TODO: Use params.
  295. uint socketLength = context.RequestData.ReadUInt32();
  296. uint type = context.RequestData.ReadUInt32();
  297. int timeOut = context.RequestData.ReadInt32();
  298. ulong pidPlaceholder = context.RequestData.ReadUInt64();
  299. if (withOptions)
  300. {
  301. // TODO: Parse and use options.
  302. }
  303. IPHostEntry hostEntry = null;
  304. NetDbError netDbErrorCode = NetDbError.Success;
  305. GaiError errno = GaiError.AddressFamily;
  306. int serializedSize = 0;
  307. if (rawIp.Length == 4)
  308. {
  309. try
  310. {
  311. IPAddress address = new IPAddress(rawIp);
  312. hostEntry = Dns.GetHostEntry(address);
  313. }
  314. catch (SocketException exception)
  315. {
  316. netDbErrorCode = ConvertSocketErrorCodeToNetDbError(exception.ErrorCode);
  317. errno = ConvertSocketErrorCodeToGaiError(exception.ErrorCode, errno);
  318. }
  319. }
  320. else
  321. {
  322. netDbErrorCode = NetDbError.NoAddress;
  323. }
  324. if (hostEntry != null)
  325. {
  326. errno = GaiError.Success;
  327. serializedSize = SerializeHostEntries(context, outputBufferPosition, outputBufferSize, hostEntry, GetIpv4Addresses(hostEntry));
  328. }
  329. WriteResponse(context, withOptions, serializedSize, errno, netDbErrorCode);
  330. return ResultCode.Success;
  331. }
  332. private static int SerializeHostEntries(ServiceCtx context, ulong outputBufferPosition, ulong outputBufferSize, IPHostEntry hostEntry, IEnumerable<IPAddress> addresses = null)
  333. {
  334. ulong originalBufferPosition = outputBufferPosition;
  335. ulong bufferPosition = originalBufferPosition;
  336. string hostName = hostEntry.HostName + '\0';
  337. // h_name
  338. context.Memory.Write(bufferPosition, Encoding.ASCII.GetBytes(hostName));
  339. bufferPosition += (ulong)hostName.Length;
  340. // h_aliases list size
  341. context.Memory.Write(bufferPosition, BinaryPrimitives.ReverseEndianness(hostEntry.Aliases.Length));
  342. bufferPosition += sizeof(int);
  343. // Actual aliases
  344. foreach (string alias in hostEntry.Aliases)
  345. {
  346. context.Memory.Write(bufferPosition, Encoding.ASCII.GetBytes(alias + '\0'));
  347. bufferPosition += (ulong)(alias.Length + 1);
  348. }
  349. // h_addrtype but it's a short (also only support IPv4)
  350. context.Memory.Write(bufferPosition, BinaryPrimitives.ReverseEndianness((short)AddressFamily.InterNetwork));
  351. bufferPosition += sizeof(short);
  352. // h_length but it's a short
  353. context.Memory.Write(bufferPosition, BinaryPrimitives.ReverseEndianness((short)4));
  354. bufferPosition += sizeof(short);
  355. // Ip address count, we can only support ipv4 (blame Nintendo)
  356. context.Memory.Write(bufferPosition, addresses != null ? BinaryPrimitives.ReverseEndianness(addresses.Count()) : 0);
  357. bufferPosition += sizeof(int);
  358. if (addresses != null)
  359. {
  360. foreach (IPAddress ip in addresses)
  361. {
  362. context.Memory.Write(bufferPosition, BinaryPrimitives.ReverseEndianness(BitConverter.ToInt32(ip.GetAddressBytes(), 0)));
  363. bufferPosition += sizeof(int);
  364. }
  365. }
  366. return (int)(bufferPosition - originalBufferPosition);
  367. }
  368. private static ResultCode GetAddrInfoRequestImpl(
  369. ServiceCtx context,
  370. ulong responseBufferPosition,
  371. ulong responseBufferSize,
  372. bool withOptions,
  373. ulong optionsBufferPosition,
  374. ulong optionsBufferSize)
  375. {
  376. bool enableNsdResolve = (context.RequestData.ReadInt32() & 1) != 0;
  377. uint cancelHandle = context.RequestData.ReadUInt32();
  378. string host = MemoryHelper.ReadAsciiString(context.Memory, context.Request.SendBuff[0].Position, (long)context.Request.SendBuff[0].Size);
  379. string service = MemoryHelper.ReadAsciiString(context.Memory, context.Request.SendBuff[1].Position, (long)context.Request.SendBuff[1].Size);
  380. if (!context.Device.Configuration.EnableInternetAccess)
  381. {
  382. Logger.Info?.Print(LogClass.ServiceSfdnsres, $"Guest network access disabled, DNS Blocked: {host}");
  383. WriteResponse(context, withOptions, 0, GaiError.NoData, NetDbError.HostNotFound);
  384. return ResultCode.Success;
  385. }
  386. // NOTE: We ignore hints for now.
  387. List<AddrInfoSerialized> hints = DeserializeAddrInfos(context.Memory, context.Request.SendBuff[2].Position, context.Request.SendBuff[2].Size);
  388. if (withOptions)
  389. {
  390. // TODO: Find unknown, Parse and use options.
  391. uint unknown = context.RequestData.ReadUInt32();
  392. }
  393. ulong pidPlaceHolder = context.RequestData.ReadUInt64();
  394. IPHostEntry hostEntry = null;
  395. NetDbError netDbErrorCode = NetDbError.Success;
  396. GaiError errno = GaiError.AddressFamily;
  397. int serializedSize = 0;
  398. if (host.Length <= byte.MaxValue)
  399. {
  400. if (enableNsdResolve)
  401. {
  402. if (FqdnResolver.Resolve(host, out string newAddress) == Nsd.ResultCode.Success)
  403. {
  404. host = newAddress;
  405. }
  406. }
  407. string targetHost = host;
  408. if (DnsBlacklist.IsHostBlocked(host))
  409. {
  410. Logger.Info?.Print(LogClass.ServiceSfdnsres, $"DNS Blocked: {host}");
  411. netDbErrorCode = NetDbError.HostNotFound;
  412. errno = GaiError.NoData;
  413. }
  414. else
  415. {
  416. Logger.Info?.Print(LogClass.ServiceSfdnsres, $"Trying to resolve: {host}");
  417. try
  418. {
  419. hostEntry = Dns.GetHostEntry(targetHost);
  420. }
  421. catch (SocketException exception)
  422. {
  423. netDbErrorCode = ConvertSocketErrorCodeToNetDbError(exception.ErrorCode);
  424. errno = ConvertSocketErrorCodeToGaiError(exception.ErrorCode, errno);
  425. }
  426. }
  427. }
  428. else
  429. {
  430. netDbErrorCode = NetDbError.NoAddress;
  431. }
  432. if (hostEntry != null)
  433. {
  434. int.TryParse(service, out int port);
  435. errno = GaiError.Success;
  436. serializedSize = SerializeAddrInfos(context, responseBufferPosition, responseBufferSize, hostEntry, port);
  437. }
  438. WriteResponse(context, withOptions, serializedSize, errno, netDbErrorCode);
  439. return ResultCode.Success;
  440. }
  441. private static List<AddrInfoSerialized> DeserializeAddrInfos(IVirtualMemoryManager memory, ulong address, ulong size)
  442. {
  443. List<AddrInfoSerialized> result = new List<AddrInfoSerialized>();
  444. ReadOnlySpan<byte> data = memory.GetSpan(address, (int)size);
  445. while (!data.IsEmpty)
  446. {
  447. AddrInfoSerialized info = AddrInfoSerialized.Read(data, out data);
  448. if (info == null)
  449. {
  450. break;
  451. }
  452. result.Add(info);
  453. }
  454. return result;
  455. }
  456. private static int SerializeAddrInfos(ServiceCtx context, ulong responseBufferPosition, ulong responseBufferSize, IPHostEntry hostEntry, int port)
  457. {
  458. ulong originalBufferPosition = responseBufferPosition;
  459. ulong bufferPosition = originalBufferPosition;
  460. byte[] hostName = Encoding.ASCII.GetBytes(hostEntry.HostName + '\0');
  461. using (WritableRegion region = context.Memory.GetWritableRegion(responseBufferPosition, (int)responseBufferSize))
  462. {
  463. Span<byte> data = region.Memory.Span;
  464. for (int i = 0; i < hostEntry.AddressList.Length; i++)
  465. {
  466. IPAddress ip = hostEntry.AddressList[i];
  467. if (ip.AddressFamily != AddressFamily.InterNetwork)
  468. {
  469. continue;
  470. }
  471. // NOTE: 0 = Any
  472. AddrInfoSerializedHeader header = new AddrInfoSerializedHeader(ip, 0);
  473. AddrInfo4 addr = new AddrInfo4(ip, (short)port);
  474. AddrInfoSerialized info = new AddrInfoSerialized(header, addr, null, hostEntry.HostName);
  475. data = info.Write(data);
  476. }
  477. uint sentinel = 0;
  478. MemoryMarshal.Write(data, ref sentinel);
  479. data = data[sizeof(uint)..];
  480. return region.Memory.Span.Length - data.Length;
  481. }
  482. }
  483. private static void WriteResponse(
  484. ServiceCtx context,
  485. bool withOptions,
  486. int serializedSize,
  487. GaiError errno,
  488. NetDbError netDbErrorCode)
  489. {
  490. if (withOptions)
  491. {
  492. context.ResponseData.Write(serializedSize);
  493. context.ResponseData.Write((int)errno);
  494. context.ResponseData.Write((int)netDbErrorCode);
  495. context.ResponseData.Write(0);
  496. }
  497. else
  498. {
  499. context.ResponseData.Write((int)netDbErrorCode);
  500. context.ResponseData.Write((int)errno);
  501. context.ResponseData.Write((int)serializedSize);
  502. }
  503. }
  504. private static IEnumerable<IPAddress> GetIpv4Addresses(IPHostEntry hostEntry)
  505. {
  506. return hostEntry.AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetwork);
  507. }
  508. private static NetDbError ConvertSocketErrorCodeToNetDbError(int errorCode)
  509. {
  510. return errorCode switch
  511. {
  512. 11001 => NetDbError.HostNotFound,
  513. 11002 => NetDbError.TryAgain,
  514. 11003 => NetDbError.NoRecovery,
  515. 11004 => NetDbError.NoData,
  516. _ => NetDbError.Internal
  517. };
  518. }
  519. private static GaiError ConvertSocketErrorCodeToGaiError(int errorCode, GaiError errno)
  520. {
  521. return errorCode switch
  522. {
  523. 11001 => GaiError.NoData,
  524. 10060 => GaiError.Again,
  525. _ => errno
  526. };
  527. }
  528. }
  529. }