IResolver.cs 25 KB

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