IResolver.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. if (!context.Device.Configuration.EnableInternetAccess)
  206. {
  207. Logger.Info?.Print(LogClass.ServiceSfdnsres, $"Guest network access disabled, DNS Blocked: {host}");
  208. WriteResponse(context, withOptions, 0, GaiError.NoData, NetDbError.HostNotFound);
  209. return ResultCode.Success;
  210. }
  211. // TODO: Use params.
  212. bool enableNsdResolve = (context.RequestData.ReadInt32() & 1) != 0;
  213. int timeOut = context.RequestData.ReadInt32();
  214. ulong pidPlaceholder = context.RequestData.ReadUInt64();
  215. if (withOptions)
  216. {
  217. // TODO: Parse and use options.
  218. }
  219. IPHostEntry hostEntry = null;
  220. NetDbError netDbErrorCode = NetDbError.Success;
  221. GaiError errno = GaiError.Overflow;
  222. ulong serializedSize = 0;
  223. if (host.Length <= byte.MaxValue)
  224. {
  225. if (enableNsdResolve)
  226. {
  227. if (FqdnResolver.Resolve(host, out string newAddress) == Nsd.ResultCode.Success)
  228. {
  229. host = newAddress;
  230. }
  231. }
  232. string targetHost = host;
  233. if (DnsBlacklist.IsHostBlocked(host))
  234. {
  235. Logger.Info?.Print(LogClass.ServiceSfdnsres, $"DNS Blocked: {host}");
  236. netDbErrorCode = NetDbError.HostNotFound;
  237. errno = GaiError.NoData;
  238. }
  239. else
  240. {
  241. Logger.Info?.Print(LogClass.ServiceSfdnsres, $"Trying to resolve: {host}");
  242. try
  243. {
  244. hostEntry = Dns.GetHostEntry(targetHost);
  245. }
  246. catch (SocketException exception)
  247. {
  248. netDbErrorCode = ConvertSocketErrorCodeToNetDbError(exception.ErrorCode);
  249. errno = ConvertSocketErrorCodeToGaiError(exception.ErrorCode, errno);
  250. }
  251. }
  252. }
  253. else
  254. {
  255. netDbErrorCode = NetDbError.HostNotFound;
  256. }
  257. if (hostEntry != null)
  258. {
  259. IEnumerable<IPAddress> addresses = GetIpv4Addresses(hostEntry);
  260. if (!addresses.Any())
  261. {
  262. errno = GaiError.NoData;
  263. netDbErrorCode = NetDbError.NoAddress;
  264. }
  265. else
  266. {
  267. errno = GaiError.Success;
  268. serializedSize = SerializeHostEntries(context, outputBufferPosition, outputBufferSize, hostEntry, addresses);
  269. }
  270. }
  271. WriteResponse(context, withOptions, serializedSize, errno, netDbErrorCode);
  272. return ResultCode.Success;
  273. }
  274. private static ResultCode GetHostByAddrRequestImpl(
  275. ServiceCtx context,
  276. ulong inputBufferPosition,
  277. ulong inputBufferSize,
  278. ulong outputBufferPosition,
  279. ulong outputBufferSize,
  280. bool withOptions,
  281. ulong optionsBufferPosition,
  282. ulong optionsBufferSize)
  283. {
  284. if (!context.Device.Configuration.EnableInternetAccess)
  285. {
  286. Logger.Info?.Print(LogClass.ServiceSfdnsres, $"Guest network access disabled, DNS Blocked.");
  287. WriteResponse(context, withOptions, 0, GaiError.NoData, NetDbError.HostNotFound);
  288. return ResultCode.Success;
  289. }
  290. byte[] rawIp = new byte[inputBufferSize];
  291. context.Memory.Read(inputBufferPosition, rawIp);
  292. // TODO: Use params.
  293. uint socketLength = context.RequestData.ReadUInt32();
  294. uint type = context.RequestData.ReadUInt32();
  295. int timeOut = context.RequestData.ReadInt32();
  296. ulong pidPlaceholder = context.RequestData.ReadUInt64();
  297. if (withOptions)
  298. {
  299. // TODO: Parse and use options.
  300. }
  301. IPHostEntry hostEntry = null;
  302. NetDbError netDbErrorCode = NetDbError.Success;
  303. GaiError errno = GaiError.AddressFamily;
  304. ulong serializedSize = 0;
  305. if (rawIp.Length == 4)
  306. {
  307. try
  308. {
  309. IPAddress address = new IPAddress(rawIp);
  310. hostEntry = Dns.GetHostEntry(address);
  311. }
  312. catch (SocketException exception)
  313. {
  314. netDbErrorCode = ConvertSocketErrorCodeToNetDbError(exception.ErrorCode);
  315. errno = ConvertSocketErrorCodeToGaiError(exception.ErrorCode, errno);
  316. }
  317. }
  318. else
  319. {
  320. netDbErrorCode = NetDbError.NoAddress;
  321. }
  322. if (hostEntry != null)
  323. {
  324. errno = GaiError.Success;
  325. serializedSize = SerializeHostEntries(context, outputBufferPosition, outputBufferSize, hostEntry, GetIpv4Addresses(hostEntry));
  326. }
  327. WriteResponse(context, withOptions, serializedSize, errno, netDbErrorCode);
  328. return ResultCode.Success;
  329. }
  330. private static ulong SerializeHostEntries(ServiceCtx context, ulong outputBufferPosition, ulong outputBufferSize, IPHostEntry hostEntry, IEnumerable<IPAddress> addresses = null)
  331. {
  332. ulong originalBufferPosition = outputBufferPosition;
  333. ulong bufferPosition = originalBufferPosition;
  334. string hostName = hostEntry.HostName + '\0';
  335. // h_name
  336. context.Memory.Write(bufferPosition, Encoding.ASCII.GetBytes(hostName));
  337. bufferPosition += (ulong)hostName.Length;
  338. // h_aliases list size
  339. context.Memory.Write(bufferPosition, BinaryPrimitives.ReverseEndianness(hostEntry.Aliases.Length));
  340. bufferPosition += sizeof(int);
  341. // Actual aliases
  342. foreach (string alias in hostEntry.Aliases)
  343. {
  344. context.Memory.Write(bufferPosition, Encoding.ASCII.GetBytes(alias + '\0'));
  345. bufferPosition += (ulong)(alias.Length + 1);
  346. }
  347. // h_addrtype but it's a short (also only support IPv4)
  348. context.Memory.Write(bufferPosition, BinaryPrimitives.ReverseEndianness((short)AddressFamily.InterNetwork));
  349. bufferPosition += sizeof(short);
  350. // h_length but it's a short
  351. context.Memory.Write(bufferPosition, BinaryPrimitives.ReverseEndianness((short)4));
  352. bufferPosition += sizeof(short);
  353. // Ip address count, we can only support ipv4 (blame Nintendo)
  354. context.Memory.Write(bufferPosition, addresses != null ? BinaryPrimitives.ReverseEndianness(addresses.Count()) : 0);
  355. bufferPosition += sizeof(int);
  356. if (addresses != null)
  357. {
  358. foreach (IPAddress ip in addresses)
  359. {
  360. context.Memory.Write(bufferPosition, BinaryPrimitives.ReverseEndianness(BitConverter.ToInt32(ip.GetAddressBytes(), 0)));
  361. bufferPosition += sizeof(int);
  362. }
  363. }
  364. return bufferPosition - originalBufferPosition;
  365. }
  366. private static ResultCode GetAddrInfoRequestImpl(
  367. ServiceCtx context,
  368. ulong responseBufferPosition,
  369. ulong responseBufferSize,
  370. bool withOptions,
  371. ulong optionsBufferPosition,
  372. ulong optionsBufferSize)
  373. {
  374. bool enableNsdResolve = (context.RequestData.ReadInt32() & 1) != 0;
  375. uint cancelHandle = context.RequestData.ReadUInt32();
  376. string host = MemoryHelper.ReadAsciiString(context.Memory, context.Request.SendBuff[0].Position, (long)context.Request.SendBuff[0].Size);
  377. string service = MemoryHelper.ReadAsciiString(context.Memory, context.Request.SendBuff[1].Position, (long)context.Request.SendBuff[1].Size);
  378. if (!context.Device.Configuration.EnableInternetAccess)
  379. {
  380. Logger.Info?.Print(LogClass.ServiceSfdnsres, $"Guest network access disabled, DNS Blocked: {host}");
  381. WriteResponse(context, withOptions, 0, GaiError.NoData, NetDbError.HostNotFound);
  382. return ResultCode.Success;
  383. }
  384. // NOTE: We ignore hints for now.
  385. DeserializeAddrInfos(context.Memory, (ulong)context.Request.SendBuff[2].Position, (ulong)context.Request.SendBuff[2].Size);
  386. if (withOptions)
  387. {
  388. // TODO: Find unknown, Parse and use options.
  389. uint unknown = context.RequestData.ReadUInt32();
  390. }
  391. ulong pidPlaceHolder = context.RequestData.ReadUInt64();
  392. IPHostEntry hostEntry = null;
  393. NetDbError netDbErrorCode = NetDbError.Success;
  394. GaiError errno = GaiError.AddressFamily;
  395. ulong serializedSize = 0;
  396. if (host.Length <= byte.MaxValue)
  397. {
  398. if (enableNsdResolve)
  399. {
  400. if (FqdnResolver.Resolve(host, out string newAddress) == Nsd.ResultCode.Success)
  401. {
  402. host = newAddress;
  403. }
  404. }
  405. string targetHost = host;
  406. if (DnsBlacklist.IsHostBlocked(host))
  407. {
  408. Logger.Info?.Print(LogClass.ServiceSfdnsres, $"DNS Blocked: {host}");
  409. netDbErrorCode = NetDbError.HostNotFound;
  410. errno = GaiError.NoData;
  411. }
  412. else
  413. {
  414. Logger.Info?.Print(LogClass.ServiceSfdnsres, $"Trying to resolve: {host}");
  415. try
  416. {
  417. hostEntry = Dns.GetHostEntry(targetHost);
  418. }
  419. catch (SocketException exception)
  420. {
  421. netDbErrorCode = ConvertSocketErrorCodeToNetDbError(exception.ErrorCode);
  422. errno = ConvertSocketErrorCodeToGaiError(exception.ErrorCode, errno);
  423. }
  424. }
  425. }
  426. else
  427. {
  428. netDbErrorCode = NetDbError.NoAddress;
  429. }
  430. if (hostEntry != null)
  431. {
  432. int.TryParse(service, out int port);
  433. errno = GaiError.Success;
  434. serializedSize = SerializeAddrInfos(context, responseBufferPosition, responseBufferSize, hostEntry, port);
  435. }
  436. WriteResponse(context, withOptions, serializedSize, errno, netDbErrorCode);
  437. return ResultCode.Success;
  438. }
  439. private static void DeserializeAddrInfos(IVirtualMemoryManager memory, ulong address, ulong size)
  440. {
  441. ulong endAddress = address + size;
  442. while (address < endAddress)
  443. {
  444. AddrInfoSerializedHeader header = memory.Read<AddrInfoSerializedHeader>(address);
  445. if (header.Magic != SfdnsresContants.AddrInfoMagic)
  446. {
  447. break;
  448. }
  449. address += (ulong)Unsafe.SizeOf<AddrInfoSerializedHeader>() + header.AddressLength;
  450. // ai_canonname
  451. string canonname = MemoryHelper.ReadAsciiString(memory, address);
  452. }
  453. }
  454. private static ulong SerializeAddrInfos(ServiceCtx context, ulong responseBufferPosition, ulong responseBufferSize, IPHostEntry hostEntry, int port)
  455. {
  456. ulong originalBufferPosition = (ulong)responseBufferPosition;
  457. ulong bufferPosition = originalBufferPosition;
  458. string hostName = hostEntry.HostName + '\0';
  459. for (int i = 0; i < hostEntry.AddressList.Length; i++)
  460. {
  461. IPAddress ip = hostEntry.AddressList[i];
  462. if (ip.AddressFamily != AddressFamily.InterNetwork)
  463. {
  464. continue;
  465. }
  466. AddrInfoSerializedHeader header = new AddrInfoSerializedHeader(ip, 0);
  467. // NOTE: 0 = Any
  468. context.Memory.Write(bufferPosition, header);
  469. bufferPosition += (ulong)Unsafe.SizeOf<AddrInfoSerializedHeader>();
  470. // addrinfo_in
  471. context.Memory.Write(bufferPosition, new AddrInfo4(ip, (short)port));
  472. bufferPosition += header.AddressLength;
  473. // ai_canonname
  474. context.Memory.Write(bufferPosition, Encoding.ASCII.GetBytes(hostName));
  475. bufferPosition += (ulong)hostName.Length;
  476. }
  477. // Termination zero value.
  478. context.Memory.Write(bufferPosition, 0);
  479. bufferPosition += sizeof(int);
  480. return bufferPosition - originalBufferPosition;
  481. }
  482. private static void WriteResponse(
  483. ServiceCtx context,
  484. bool withOptions,
  485. ulong serializedSize,
  486. GaiError errno,
  487. NetDbError netDbErrorCode)
  488. {
  489. if (withOptions)
  490. {
  491. context.ResponseData.Write((int)serializedSize);
  492. context.ResponseData.Write((int)errno);
  493. context.ResponseData.Write((int)netDbErrorCode);
  494. context.ResponseData.Write(0);
  495. }
  496. else
  497. {
  498. context.ResponseData.Write((int)netDbErrorCode);
  499. context.ResponseData.Write((int)errno);
  500. context.ResponseData.Write((int)serializedSize);
  501. }
  502. }
  503. private static IEnumerable<IPAddress> GetIpv4Addresses(IPHostEntry hostEntry)
  504. {
  505. return hostEntry.AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetwork);
  506. }
  507. private static NetDbError ConvertSocketErrorCodeToNetDbError(int errorCode)
  508. {
  509. return errorCode switch
  510. {
  511. 11001 => NetDbError.HostNotFound,
  512. 11002 => NetDbError.TryAgain,
  513. 11003 => NetDbError.NoRecovery,
  514. 11004 => NetDbError.NoData,
  515. _ => NetDbError.Internal
  516. };
  517. }
  518. private static GaiError ConvertSocketErrorCodeToGaiError(int errorCode, GaiError errno)
  519. {
  520. return errorCode switch
  521. {
  522. 11001 => GaiError.NoData,
  523. 10060 => GaiError.Again,
  524. _ => errno
  525. };
  526. }
  527. }
  528. }