IClient.cs 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. using Ryujinx.Common;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl;
  4. using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types;
  5. using Ryujinx.Memory;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Numerics;
  11. using System.Runtime.CompilerServices;
  12. using System.Text;
  13. namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
  14. {
  15. [Service("bsd:s", true)]
  16. [Service("bsd:u", false)]
  17. class IClient : IpcService
  18. {
  19. private static readonly List<IPollManager> _pollManagers = new List<IPollManager>
  20. {
  21. EventFileDescriptorPollManager.Instance,
  22. ManagedSocketPollManager.Instance
  23. };
  24. private BsdContext _context;
  25. private bool _isPrivileged;
  26. public IClient(ServiceCtx context, bool isPrivileged) : base(context.Device.System.BsdServer)
  27. {
  28. _isPrivileged = isPrivileged;
  29. }
  30. private ResultCode WriteBsdResult(ServiceCtx context, int result, LinuxError errorCode = LinuxError.SUCCESS)
  31. {
  32. if (errorCode != LinuxError.SUCCESS)
  33. {
  34. result = -1;
  35. }
  36. context.ResponseData.Write(result);
  37. context.ResponseData.Write((int)errorCode);
  38. return ResultCode.Success;
  39. }
  40. private static AddressFamily ConvertBsdAddressFamily(BsdAddressFamily family)
  41. {
  42. switch (family)
  43. {
  44. case BsdAddressFamily.Unspecified:
  45. return AddressFamily.Unspecified;
  46. case BsdAddressFamily.InterNetwork:
  47. return AddressFamily.InterNetwork;
  48. case BsdAddressFamily.InterNetworkV6:
  49. return AddressFamily.InterNetworkV6;
  50. case BsdAddressFamily.Unknown:
  51. return AddressFamily.Unknown;
  52. default:
  53. throw new NotImplementedException(family.ToString());
  54. }
  55. }
  56. private LinuxError SetResultErrno(IFileDescriptor socket, int result)
  57. {
  58. return result == 0 && !socket.Blocking ? LinuxError.EWOULDBLOCK : LinuxError.SUCCESS;
  59. }
  60. private ResultCode SocketInternal(ServiceCtx context, bool exempt)
  61. {
  62. BsdAddressFamily domain = (BsdAddressFamily)context.RequestData.ReadInt32();
  63. BsdSocketType type = (BsdSocketType)context.RequestData.ReadInt32();
  64. ProtocolType protocol = (ProtocolType)context.RequestData.ReadInt32();
  65. BsdSocketCreationFlags creationFlags = (BsdSocketCreationFlags)((int)type >> (int)BsdSocketCreationFlags.FlagsShift);
  66. type &= BsdSocketType.TypeMask;
  67. if (domain == BsdAddressFamily.Unknown)
  68. {
  69. return WriteBsdResult(context, -1, LinuxError.EPROTONOSUPPORT);
  70. }
  71. else if ((type == BsdSocketType.Seqpacket || type == BsdSocketType.Raw) && !_isPrivileged)
  72. {
  73. if (domain != BsdAddressFamily.InterNetwork || type != BsdSocketType.Raw || protocol != ProtocolType.Icmp)
  74. {
  75. return WriteBsdResult(context, -1, LinuxError.ENOENT);
  76. }
  77. }
  78. AddressFamily netDomain = ConvertBsdAddressFamily(domain);
  79. if (protocol == ProtocolType.IP)
  80. {
  81. if (type == BsdSocketType.Stream)
  82. {
  83. protocol = ProtocolType.Tcp;
  84. }
  85. else if (type == BsdSocketType.Dgram)
  86. {
  87. protocol = ProtocolType.Udp;
  88. }
  89. }
  90. ISocket newBsdSocket = new ManagedSocket(netDomain, (SocketType)type, protocol);
  91. newBsdSocket.Blocking = !creationFlags.HasFlag(BsdSocketCreationFlags.NonBlocking);
  92. LinuxError errno = LinuxError.SUCCESS;
  93. int newSockFd = _context.RegisterFileDescriptor(newBsdSocket);
  94. if (newSockFd == -1)
  95. {
  96. errno = LinuxError.EBADF;
  97. }
  98. if (exempt)
  99. {
  100. newBsdSocket.Disconnect();
  101. }
  102. return WriteBsdResult(context, newSockFd, errno);
  103. }
  104. private void WriteSockAddr(ServiceCtx context, ulong bufferPosition, ISocket socket, bool isRemote)
  105. {
  106. IPEndPoint endPoint = isRemote ? socket.RemoteEndPoint : socket.LocalEndPoint;
  107. context.Memory.Write(bufferPosition, BsdSockAddr.FromIPEndPoint(endPoint));
  108. }
  109. [CommandHipc(0)]
  110. // Initialize(nn::socket::BsdBufferConfig config, u64 pid, u64 transferMemorySize, KObject<copy, transfer_memory>, pid) -> u32 bsd_errno
  111. public ResultCode RegisterClient(ServiceCtx context)
  112. {
  113. _context = BsdContext.GetOrRegister(context.Request.HandleDesc.PId);
  114. /*
  115. typedef struct {
  116. u32 version; // Observed 1 on 2.0 LibAppletWeb, 2 on 3.0.
  117. u32 tcp_tx_buf_size; // Size of the TCP transfer (send) buffer (initial or fixed).
  118. u32 tcp_rx_buf_size; // Size of the TCP recieve buffer (initial or fixed).
  119. u32 tcp_tx_buf_max_size; // Maximum size of the TCP transfer (send) buffer. If it is 0, the size of the buffer is fixed to its initial value.
  120. u32 tcp_rx_buf_max_size; // Maximum size of the TCP receive buffer. If it is 0, the size of the buffer is fixed to its initial value.
  121. u32 udp_tx_buf_size; // Size of the UDP transfer (send) buffer (typically 0x2400 bytes).
  122. u32 udp_rx_buf_size; // Size of the UDP receive buffer (typically 0xA500 bytes).
  123. u32 sb_efficiency; // Number of buffers for each socket (standard values range from 1 to 8).
  124. } BsdBufferConfig;
  125. */
  126. // bsd_error
  127. context.ResponseData.Write(0);
  128. Logger.Stub?.PrintStub(LogClass.ServiceBsd);
  129. // Close transfer memory immediately as we don't use it.
  130. context.Device.System.KernelContext.Syscall.CloseHandle(context.Request.HandleDesc.ToCopy[0]);
  131. return ResultCode.Success;
  132. }
  133. [CommandHipc(1)]
  134. // StartMonitoring(u64, pid)
  135. public ResultCode StartMonitoring(ServiceCtx context)
  136. {
  137. ulong unknown0 = context.RequestData.ReadUInt64();
  138. Logger.Stub?.PrintStub(LogClass.ServiceBsd, new { unknown0 });
  139. return ResultCode.Success;
  140. }
  141. [CommandHipc(2)]
  142. // Socket(u32 domain, u32 type, u32 protocol) -> (i32 ret, u32 bsd_errno)
  143. public ResultCode Socket(ServiceCtx context)
  144. {
  145. return SocketInternal(context, false);
  146. }
  147. [CommandHipc(3)]
  148. // SocketExempt(u32 domain, u32 type, u32 protocol) -> (i32 ret, u32 bsd_errno)
  149. public ResultCode SocketExempt(ServiceCtx context)
  150. {
  151. return SocketInternal(context, true);
  152. }
  153. [CommandHipc(4)]
  154. // Open(u32 flags, array<unknown, 0x21> path) -> (i32 ret, u32 bsd_errno)
  155. public ResultCode Open(ServiceCtx context)
  156. {
  157. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x21();
  158. int flags = context.RequestData.ReadInt32();
  159. byte[] rawPath = new byte[bufferSize];
  160. context.Memory.Read(bufferPosition, rawPath);
  161. string path = Encoding.ASCII.GetString(rawPath);
  162. WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP);
  163. Logger.Stub?.PrintStub(LogClass.ServiceBsd, new { path, flags });
  164. return ResultCode.Success;
  165. }
  166. [CommandHipc(5)]
  167. // Select(u32 nfds, nn::socket::timeval timeout, buffer<nn::socket::fd_set, 0x21, 0> readfds_in, buffer<nn::socket::fd_set, 0x21, 0> writefds_in, buffer<nn::socket::fd_set, 0x21, 0> errorfds_in)
  168. // -> (i32 ret, u32 bsd_errno, buffer<nn::socket::fd_set, 0x22, 0> readfds_out, buffer<nn::socket::fd_set, 0x22, 0> writefds_out, buffer<nn::socket::fd_set, 0x22, 0> errorfds_out)
  169. public ResultCode Select(ServiceCtx context)
  170. {
  171. int fdsCount = context.RequestData.ReadInt32();
  172. int timeout = context.RequestData.ReadInt32();
  173. (ulong readFdsInBufferPosition, ulong readFdsInBufferSize) = context.Request.GetBufferType0x21(0);
  174. (ulong writeFdsInBufferPosition, ulong writeFdsInBufferSize) = context.Request.GetBufferType0x21(1);
  175. (ulong errorFdsInBufferPosition, ulong errorFdsInBufferSize) = context.Request.GetBufferType0x21(2);
  176. (ulong readFdsOutBufferPosition, ulong readFdsOutBufferSize) = context.Request.GetBufferType0x22(0);
  177. (ulong writeFdsOutBufferPosition, ulong writeFdsOutBufferSize) = context.Request.GetBufferType0x22(1);
  178. (ulong errorFdsOutBufferPosition, ulong errorFdsOutBufferSize) = context.Request.GetBufferType0x22(2);
  179. List<IFileDescriptor> readFds = _context.RetrieveFileDescriptorsFromMask(context.Memory.GetSpan(readFdsInBufferPosition, (int)readFdsInBufferSize));
  180. List<IFileDescriptor> writeFds = _context.RetrieveFileDescriptorsFromMask(context.Memory.GetSpan(writeFdsInBufferPosition, (int)writeFdsInBufferSize));
  181. List<IFileDescriptor> errorFds = _context.RetrieveFileDescriptorsFromMask(context.Memory.GetSpan(errorFdsInBufferPosition, (int)errorFdsInBufferSize));
  182. int actualFdsCount = readFds.Count + writeFds.Count + errorFds.Count;
  183. if (fdsCount == 0 || actualFdsCount == 0)
  184. {
  185. WriteBsdResult(context, 0);
  186. return ResultCode.Success;
  187. }
  188. PollEvent[] events = new PollEvent[actualFdsCount];
  189. int index = 0;
  190. foreach (IFileDescriptor fd in readFds)
  191. {
  192. events[index] = new PollEvent(new PollEventData { InputEvents = PollEventTypeMask.Input }, fd);
  193. index++;
  194. }
  195. foreach (IFileDescriptor fd in writeFds)
  196. {
  197. events[index] = new PollEvent(new PollEventData { InputEvents = PollEventTypeMask.Output }, fd);
  198. index++;
  199. }
  200. foreach (IFileDescriptor fd in errorFds)
  201. {
  202. events[index] = new PollEvent(new PollEventData { InputEvents = PollEventTypeMask.Error }, fd);
  203. index++;
  204. }
  205. List<PollEvent>[] eventsByPollManager = new List<PollEvent>[_pollManagers.Count];
  206. for (int i = 0; i < eventsByPollManager.Length; i++)
  207. {
  208. eventsByPollManager[i] = new List<PollEvent>();
  209. foreach (PollEvent evnt in events)
  210. {
  211. if (_pollManagers[i].IsCompatible(evnt))
  212. {
  213. eventsByPollManager[i].Add(evnt);
  214. }
  215. }
  216. }
  217. int updatedCount = 0;
  218. for (int i = 0; i < _pollManagers.Count; i++)
  219. {
  220. if (eventsByPollManager[i].Count > 0)
  221. {
  222. _pollManagers[i].Select(eventsByPollManager[i], timeout, out int updatedPollCount);
  223. updatedCount += updatedPollCount;
  224. }
  225. }
  226. readFds.Clear();
  227. writeFds.Clear();
  228. errorFds.Clear();
  229. foreach (PollEvent pollEvent in events)
  230. {
  231. for (int i = 0; i < _pollManagers.Count; i++)
  232. {
  233. if (eventsByPollManager[i].Contains(pollEvent))
  234. {
  235. if (pollEvent.Data.OutputEvents.HasFlag(PollEventTypeMask.Input))
  236. {
  237. readFds.Add(pollEvent.FileDescriptor);
  238. }
  239. if (pollEvent.Data.OutputEvents.HasFlag(PollEventTypeMask.Output))
  240. {
  241. writeFds.Add(pollEvent.FileDescriptor);
  242. }
  243. if (pollEvent.Data.OutputEvents.HasFlag(PollEventTypeMask.Error))
  244. {
  245. errorFds.Add(pollEvent.FileDescriptor);
  246. }
  247. }
  248. }
  249. }
  250. using var readFdsOut = context.Memory.GetWritableRegion(readFdsOutBufferPosition, (int)readFdsOutBufferSize);
  251. using var writeFdsOut = context.Memory.GetWritableRegion(writeFdsOutBufferPosition, (int)writeFdsOutBufferSize);
  252. using var errorFdsOut = context.Memory.GetWritableRegion(errorFdsOutBufferPosition, (int)errorFdsOutBufferSize);
  253. _context.BuildMask(readFds, readFdsOut.Memory.Span);
  254. _context.BuildMask(writeFds, writeFdsOut.Memory.Span);
  255. _context.BuildMask(errorFds, errorFdsOut.Memory.Span);
  256. WriteBsdResult(context, updatedCount);
  257. return ResultCode.Success;
  258. }
  259. [CommandHipc(6)]
  260. // Poll(u32 nfds, u32 timeout, buffer<unknown, 0x21, 0> fds) -> (i32 ret, u32 bsd_errno, buffer<unknown, 0x22, 0>)
  261. public ResultCode Poll(ServiceCtx context)
  262. {
  263. int fdsCount = context.RequestData.ReadInt32();
  264. int timeout = context.RequestData.ReadInt32();
  265. (ulong inputBufferPosition, ulong inputBufferSize) = context.Request.GetBufferType0x21();
  266. (ulong outputBufferPosition, ulong outputBufferSize) = context.Request.GetBufferType0x22();
  267. if (timeout < -1 || fdsCount < 0 || (ulong)(fdsCount * 8) > inputBufferSize)
  268. {
  269. return WriteBsdResult(context, -1, LinuxError.EINVAL);
  270. }
  271. PollEvent[] events = new PollEvent[fdsCount];
  272. for (int i = 0; i < fdsCount; i++)
  273. {
  274. PollEventData pollEventData = context.Memory.Read<PollEventData>(inputBufferPosition + (ulong)(i * Unsafe.SizeOf<PollEventData>()));
  275. IFileDescriptor fileDescriptor = _context.RetrieveFileDescriptor(pollEventData.SocketFd);
  276. if (fileDescriptor == null)
  277. {
  278. return WriteBsdResult(context, -1, LinuxError.EBADF);
  279. }
  280. events[i] = new PollEvent(pollEventData, fileDescriptor);
  281. }
  282. List<PollEvent> discoveredEvents = new List<PollEvent>();
  283. List<PollEvent>[] eventsByPollManager = new List<PollEvent>[_pollManagers.Count];
  284. for (int i = 0; i < eventsByPollManager.Length; i++)
  285. {
  286. eventsByPollManager[i] = new List<PollEvent>();
  287. foreach (PollEvent evnt in events)
  288. {
  289. if (_pollManagers[i].IsCompatible(evnt))
  290. {
  291. eventsByPollManager[i].Add(evnt);
  292. discoveredEvents.Add(evnt);
  293. }
  294. }
  295. }
  296. foreach (PollEvent evnt in events)
  297. {
  298. if (!discoveredEvents.Contains(evnt))
  299. {
  300. Logger.Error?.Print(LogClass.ServiceBsd, $"Poll operation is not supported for {evnt.FileDescriptor.GetType().Name}!");
  301. return WriteBsdResult(context, -1, LinuxError.EBADF);
  302. }
  303. }
  304. int updateCount = 0;
  305. LinuxError errno = LinuxError.SUCCESS;
  306. if (fdsCount != 0)
  307. {
  308. bool IsUnexpectedLinuxError(LinuxError error)
  309. {
  310. return error != LinuxError.SUCCESS && error != LinuxError.ETIMEDOUT;
  311. }
  312. // Hybrid approach
  313. long budgetLeftMilliseconds;
  314. if (timeout == -1)
  315. {
  316. budgetLeftMilliseconds = PerformanceCounter.ElapsedMilliseconds + uint.MaxValue;
  317. }
  318. else
  319. {
  320. budgetLeftMilliseconds = PerformanceCounter.ElapsedMilliseconds + timeout;
  321. }
  322. do
  323. {
  324. for (int i = 0; i < eventsByPollManager.Length; i++)
  325. {
  326. if (eventsByPollManager[i].Count == 0)
  327. {
  328. continue;
  329. }
  330. errno = _pollManagers[i].Poll(eventsByPollManager[i], 0, out updateCount);
  331. if (IsUnexpectedLinuxError(errno))
  332. {
  333. break;
  334. }
  335. if (updateCount > 0)
  336. {
  337. break;
  338. }
  339. }
  340. if (updateCount > 0)
  341. {
  342. break;
  343. }
  344. // If we are here, that mean nothing was available, sleep for 50ms
  345. context.Device.System.KernelContext.Syscall.SleepThread(50 * 1000000);
  346. }
  347. while (PerformanceCounter.ElapsedMilliseconds < budgetLeftMilliseconds);
  348. }
  349. else if (timeout == -1)
  350. {
  351. // FIXME: If we get a timeout of -1 and there is no fds to wait on, this should kill the KProcess. (need to check that with re)
  352. throw new InvalidOperationException();
  353. }
  354. else
  355. {
  356. context.Device.System.KernelContext.Syscall.SleepThread(timeout);
  357. }
  358. // TODO: Spanify
  359. for (int i = 0; i < fdsCount; i++)
  360. {
  361. context.Memory.Write(outputBufferPosition + (ulong)(i * Unsafe.SizeOf<PollEventData>()), events[i].Data);
  362. }
  363. // In case of non blocking call timeout should not be returned.
  364. if (timeout == 0 && errno == LinuxError.ETIMEDOUT)
  365. {
  366. errno = LinuxError.SUCCESS;
  367. }
  368. return WriteBsdResult(context, updateCount, errno);
  369. }
  370. [CommandHipc(7)]
  371. // Sysctl(buffer<unknown, 0x21, 0>, buffer<unknown, 0x21, 0>) -> (i32 ret, u32 bsd_errno, u32, buffer<unknown, 0x22, 0>)
  372. public ResultCode Sysctl(ServiceCtx context)
  373. {
  374. WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP);
  375. Logger.Stub?.PrintStub(LogClass.ServiceBsd);
  376. return ResultCode.Success;
  377. }
  378. [CommandHipc(8)]
  379. // Recv(u32 socket, u32 flags) -> (i32 ret, u32 bsd_errno, array<i8, 0x22> message)
  380. public ResultCode Recv(ServiceCtx context)
  381. {
  382. int socketFd = context.RequestData.ReadInt32();
  383. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  384. (ulong receivePosition, ulong receiveLength) = context.Request.GetBufferType0x22();
  385. WritableRegion receiveRegion = context.Memory.GetWritableRegion(receivePosition, (int)receiveLength);
  386. LinuxError errno = LinuxError.EBADF;
  387. ISocket socket = _context.RetrieveSocket(socketFd);
  388. int result = -1;
  389. if (socket != null)
  390. {
  391. errno = socket.Receive(out result, receiveRegion.Memory.Span, socketFlags);
  392. if (errno == LinuxError.SUCCESS)
  393. {
  394. SetResultErrno(socket, result);
  395. receiveRegion.Dispose();
  396. }
  397. }
  398. return WriteBsdResult(context, result, errno);
  399. }
  400. [CommandHipc(9)]
  401. // RecvFrom(u32 sock, u32 flags) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<i8, 0x22, 0> message, buffer<nn::socket::sockaddr_in, 0x22, 0x10>)
  402. public ResultCode RecvFrom(ServiceCtx context)
  403. {
  404. int socketFd = context.RequestData.ReadInt32();
  405. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  406. (ulong receivePosition, ulong receiveLength) = context.Request.GetBufferType0x22(0);
  407. (ulong sockAddrOutPosition, ulong sockAddrOutSize) = context.Request.GetBufferType0x22(1);
  408. WritableRegion receiveRegion = context.Memory.GetWritableRegion(receivePosition, (int)receiveLength);
  409. LinuxError errno = LinuxError.EBADF;
  410. ISocket socket = _context.RetrieveSocket(socketFd);
  411. int result = -1;
  412. if (socket != null)
  413. {
  414. errno = socket.ReceiveFrom(out result, receiveRegion.Memory.Span, receiveRegion.Memory.Span.Length, socketFlags, out IPEndPoint endPoint);
  415. if (errno == LinuxError.SUCCESS)
  416. {
  417. SetResultErrno(socket, result);
  418. receiveRegion.Dispose();
  419. context.Memory.Write(sockAddrOutPosition, BsdSockAddr.FromIPEndPoint(endPoint));
  420. }
  421. }
  422. return WriteBsdResult(context, result, errno);
  423. }
  424. [CommandHipc(10)]
  425. // Send(u32 socket, u32 flags, buffer<i8, 0x21, 0>) -> (i32 ret, u32 bsd_errno)
  426. public ResultCode Send(ServiceCtx context)
  427. {
  428. int socketFd = context.RequestData.ReadInt32();
  429. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  430. (ulong sendPosition, ulong sendSize) = context.Request.GetBufferType0x21();
  431. ReadOnlySpan<byte> sendBuffer = context.Memory.GetSpan(sendPosition, (int)sendSize);
  432. LinuxError errno = LinuxError.EBADF;
  433. ISocket socket = _context.RetrieveSocket(socketFd);
  434. int result = -1;
  435. if (socket != null)
  436. {
  437. errno = socket.Send(out result, sendBuffer, socketFlags);
  438. if (errno == LinuxError.SUCCESS)
  439. {
  440. SetResultErrno(socket, result);
  441. }
  442. }
  443. return WriteBsdResult(context, result, errno);
  444. }
  445. [CommandHipc(11)]
  446. // SendTo(u32 socket, u32 flags, buffer<i8, 0x21, 0>, buffer<nn::socket::sockaddr_in, 0x21, 0x10>) -> (i32 ret, u32 bsd_errno)
  447. public ResultCode SendTo(ServiceCtx context)
  448. {
  449. int socketFd = context.RequestData.ReadInt32();
  450. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  451. (ulong sendPosition, ulong sendSize) = context.Request.GetBufferType0x21(0);
  452. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x21(1);
  453. ReadOnlySpan<byte> sendBuffer = context.Memory.GetSpan(sendPosition, (int)sendSize);
  454. LinuxError errno = LinuxError.EBADF;
  455. ISocket socket = _context.RetrieveSocket(socketFd);
  456. int result = -1;
  457. if (socket != null)
  458. {
  459. IPEndPoint endPoint = context.Memory.Read<BsdSockAddr>(bufferPosition).ToIPEndPoint();
  460. errno = socket.SendTo(out result, sendBuffer, sendBuffer.Length, socketFlags, endPoint);
  461. if (errno == LinuxError.SUCCESS)
  462. {
  463. SetResultErrno(socket, result);
  464. }
  465. }
  466. return WriteBsdResult(context, result, errno);
  467. }
  468. [CommandHipc(12)]
  469. // Accept(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<nn::socket::sockaddr_in, 0x22, 0x10> addr)
  470. public ResultCode Accept(ServiceCtx context)
  471. {
  472. int socketFd = context.RequestData.ReadInt32();
  473. (ulong bufferPos, ulong bufferSize) = context.Request.GetBufferType0x22();
  474. LinuxError errno = LinuxError.EBADF;
  475. ISocket socket = _context.RetrieveSocket(socketFd);
  476. if (socket != null)
  477. {
  478. errno = socket.Accept(out ISocket newSocket);
  479. if (newSocket == null && errno == LinuxError.SUCCESS)
  480. {
  481. errno = LinuxError.EWOULDBLOCK;
  482. }
  483. else if (errno == LinuxError.SUCCESS)
  484. {
  485. int newSockFd = _context.RegisterFileDescriptor(newSocket);
  486. if (newSockFd == -1)
  487. {
  488. errno = LinuxError.EBADF;
  489. }
  490. else
  491. {
  492. WriteSockAddr(context, bufferPos, newSocket, true);
  493. }
  494. WriteBsdResult(context, newSockFd, errno);
  495. context.ResponseData.Write(0x10);
  496. return ResultCode.Success;
  497. }
  498. }
  499. return WriteBsdResult(context, -1, errno);
  500. }
  501. [CommandHipc(13)]
  502. // Bind(u32 socket, buffer<nn::socket::sockaddr_in, 0x21, 0x10> addr) -> (i32 ret, u32 bsd_errno)
  503. public ResultCode Bind(ServiceCtx context)
  504. {
  505. int socketFd = context.RequestData.ReadInt32();
  506. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x21();
  507. LinuxError errno = LinuxError.EBADF;
  508. ISocket socket = _context.RetrieveSocket(socketFd);
  509. if (socket != null)
  510. {
  511. IPEndPoint endPoint = context.Memory.Read<BsdSockAddr>(bufferPosition).ToIPEndPoint();
  512. errno = socket.Bind(endPoint);
  513. }
  514. return WriteBsdResult(context, 0, errno);
  515. }
  516. [CommandHipc(14)]
  517. // Connect(u32 socket, buffer<nn::socket::sockaddr_in, 0x21, 0x10>) -> (i32 ret, u32 bsd_errno)
  518. public ResultCode Connect(ServiceCtx context)
  519. {
  520. int socketFd = context.RequestData.ReadInt32();
  521. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x21();
  522. LinuxError errno = LinuxError.EBADF;
  523. ISocket socket = _context.RetrieveSocket(socketFd);
  524. if (socket != null)
  525. {
  526. IPEndPoint endPoint = context.Memory.Read<BsdSockAddr>(bufferPosition).ToIPEndPoint();
  527. errno = socket.Connect(endPoint);
  528. }
  529. return WriteBsdResult(context, 0, errno);
  530. }
  531. [CommandHipc(15)]
  532. // GetPeerName(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<nn::socket::sockaddr_in, 0x22, 0x10> addr)
  533. public ResultCode GetPeerName(ServiceCtx context)
  534. {
  535. int socketFd = context.RequestData.ReadInt32();
  536. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x22();
  537. LinuxError errno = LinuxError.EBADF;
  538. ISocket socket = _context.RetrieveSocket(socketFd);
  539. if (socket != null)
  540. {
  541. errno = LinuxError.ENOTCONN;
  542. if (socket.RemoteEndPoint != null)
  543. {
  544. errno = LinuxError.SUCCESS;
  545. WriteSockAddr(context, bufferPosition, socket, true);
  546. WriteBsdResult(context, 0, errno);
  547. context.ResponseData.Write(Unsafe.SizeOf<BsdSockAddr>());
  548. }
  549. }
  550. return WriteBsdResult(context, 0, errno);
  551. }
  552. [CommandHipc(16)]
  553. // GetSockName(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<nn::socket::sockaddr_in, 0x22, 0x10> addr)
  554. public ResultCode GetSockName(ServiceCtx context)
  555. {
  556. int socketFd = context.RequestData.ReadInt32();
  557. (ulong bufferPos, ulong bufferSize) = context.Request.GetBufferType0x22();
  558. LinuxError errno = LinuxError.EBADF;
  559. ISocket socket = _context.RetrieveSocket(socketFd);
  560. if (socket != null)
  561. {
  562. errno = LinuxError.SUCCESS;
  563. WriteSockAddr(context, bufferPos, socket, false);
  564. WriteBsdResult(context, 0, errno);
  565. context.ResponseData.Write(Unsafe.SizeOf<BsdSockAddr>());
  566. }
  567. return WriteBsdResult(context, 0, errno);
  568. }
  569. [CommandHipc(17)]
  570. // GetSockOpt(u32 socket, u32 level, u32 option_name) -> (i32 ret, u32 bsd_errno, u32, buffer<unknown, 0x22, 0>)
  571. public ResultCode GetSockOpt(ServiceCtx context)
  572. {
  573. int socketFd = context.RequestData.ReadInt32();
  574. SocketOptionLevel level = (SocketOptionLevel)context.RequestData.ReadInt32();
  575. BsdSocketOption option = (BsdSocketOption)context.RequestData.ReadInt32();
  576. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x22();
  577. WritableRegion optionValue = context.Memory.GetWritableRegion(bufferPosition, (int)bufferSize);
  578. LinuxError errno = LinuxError.EBADF;
  579. ISocket socket = _context.RetrieveSocket(socketFd);
  580. if (socket != null)
  581. {
  582. errno = socket.GetSocketOption(option, level, optionValue.Memory.Span);
  583. if (errno == LinuxError.SUCCESS)
  584. {
  585. optionValue.Dispose();
  586. }
  587. }
  588. return WriteBsdResult(context, 0, errno);
  589. }
  590. [CommandHipc(18)]
  591. // Listen(u32 socket, u32 backlog) -> (i32 ret, u32 bsd_errno)
  592. public ResultCode Listen(ServiceCtx context)
  593. {
  594. int socketFd = context.RequestData.ReadInt32();
  595. int backlog = context.RequestData.ReadInt32();
  596. LinuxError errno = LinuxError.EBADF;
  597. ISocket socket = _context.RetrieveSocket(socketFd);
  598. if (socket != null)
  599. {
  600. errno = socket.Listen(backlog);
  601. }
  602. return WriteBsdResult(context, 0, errno);
  603. }
  604. [CommandHipc(19)]
  605. // Ioctl(u32 fd, u32 request, u32 bufcount, buffer<unknown, 0x21, 0>, buffer<unknown, 0x21, 0>, buffer<unknown, 0x21, 0>, buffer<unknown, 0x21, 0>) -> (i32 ret, u32 bsd_errno, buffer<unknown, 0x22, 0>, buffer<unknown, 0x22, 0>, buffer<unknown, 0x22, 0>, buffer<unknown, 0x22, 0>)
  606. public ResultCode Ioctl(ServiceCtx context)
  607. {
  608. int socketFd = context.RequestData.ReadInt32();
  609. BsdIoctl cmd = (BsdIoctl)context.RequestData.ReadInt32();
  610. int bufferCount = context.RequestData.ReadInt32();
  611. LinuxError errno = LinuxError.EBADF;
  612. ISocket socket = _context.RetrieveSocket(socketFd);
  613. if (socket != null)
  614. {
  615. switch (cmd)
  616. {
  617. case BsdIoctl.AtMark:
  618. errno = LinuxError.SUCCESS;
  619. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x22();
  620. // FIXME: OOB not implemented.
  621. context.Memory.Write(bufferPosition, 0);
  622. break;
  623. default:
  624. errno = LinuxError.EOPNOTSUPP;
  625. Logger.Warning?.Print(LogClass.ServiceBsd, $"Unsupported Ioctl Cmd: {cmd}");
  626. break;
  627. }
  628. }
  629. return WriteBsdResult(context, 0, errno);
  630. }
  631. [CommandHipc(20)]
  632. // Fcntl(u32 socket, u32 cmd, u32 arg) -> (i32 ret, u32 bsd_errno)
  633. public ResultCode Fcntl(ServiceCtx context)
  634. {
  635. int socketFd = context.RequestData.ReadInt32();
  636. int cmd = context.RequestData.ReadInt32();
  637. int arg = context.RequestData.ReadInt32();
  638. int result = 0;
  639. LinuxError errno = LinuxError.EBADF;
  640. ISocket socket = _context.RetrieveSocket(socketFd);
  641. if (socket != null)
  642. {
  643. errno = LinuxError.SUCCESS;
  644. if (cmd == 0x3)
  645. {
  646. result = !socket.Blocking ? 0x800 : 0;
  647. }
  648. else if (cmd == 0x4 && arg == 0x800)
  649. {
  650. socket.Blocking = false;
  651. result = 0;
  652. }
  653. else
  654. {
  655. errno = LinuxError.EOPNOTSUPP;
  656. }
  657. }
  658. return WriteBsdResult(context, result, errno);
  659. }
  660. [CommandHipc(21)]
  661. // SetSockOpt(u32 socket, u32 level, u32 option_name, buffer<unknown, 0x21, 0> option_value) -> (i32 ret, u32 bsd_errno)
  662. public ResultCode SetSockOpt(ServiceCtx context)
  663. {
  664. int socketFd = context.RequestData.ReadInt32();
  665. SocketOptionLevel level = (SocketOptionLevel)context.RequestData.ReadInt32();
  666. BsdSocketOption option = (BsdSocketOption)context.RequestData.ReadInt32();
  667. (ulong bufferPos, ulong bufferSize) = context.Request.GetBufferType0x21();
  668. ReadOnlySpan<byte> optionValue = context.Memory.GetSpan(bufferPos, (int)bufferSize);
  669. LinuxError errno = LinuxError.EBADF;
  670. ISocket socket = _context.RetrieveSocket(socketFd);
  671. if (socket != null)
  672. {
  673. errno = socket.SetSocketOption(option, level, optionValue);
  674. }
  675. return WriteBsdResult(context, 0, errno);
  676. }
  677. [CommandHipc(22)]
  678. // Shutdown(u32 socket, u32 how) -> (i32 ret, u32 bsd_errno)
  679. public ResultCode Shutdown(ServiceCtx context)
  680. {
  681. int socketFd = context.RequestData.ReadInt32();
  682. int how = context.RequestData.ReadInt32();
  683. LinuxError errno = LinuxError.EBADF;
  684. ISocket socket = _context.RetrieveSocket(socketFd);
  685. if (socket != null)
  686. {
  687. errno = LinuxError.EINVAL;
  688. if (how >= 0 && how <= 2)
  689. {
  690. errno = socket.Shutdown((BsdSocketShutdownFlags)how);
  691. }
  692. }
  693. return WriteBsdResult(context, 0, errno);
  694. }
  695. [CommandHipc(23)]
  696. // ShutdownAllSockets(u32 how) -> (i32 ret, u32 bsd_errno)
  697. public ResultCode ShutdownAllSockets(ServiceCtx context)
  698. {
  699. int how = context.RequestData.ReadInt32();
  700. LinuxError errno = LinuxError.EINVAL;
  701. if (how >= 0 && how <= 2)
  702. {
  703. errno = _context.ShutdownAllSockets((BsdSocketShutdownFlags)how);
  704. }
  705. return WriteBsdResult(context, 0, errno);
  706. }
  707. [CommandHipc(24)]
  708. // Write(u32 fd, buffer<i8, 0x21, 0> message) -> (i32 ret, u32 bsd_errno)
  709. public ResultCode Write(ServiceCtx context)
  710. {
  711. int fd = context.RequestData.ReadInt32();
  712. (ulong sendPosition, ulong sendSize) = context.Request.GetBufferType0x21();
  713. ReadOnlySpan<byte> sendBuffer = context.Memory.GetSpan(sendPosition, (int)sendSize);
  714. LinuxError errno = LinuxError.EBADF;
  715. IFileDescriptor file = _context.RetrieveFileDescriptor(fd);
  716. int result = -1;
  717. if (file != null)
  718. {
  719. errno = file.Write(out result, sendBuffer);
  720. if (errno == LinuxError.SUCCESS)
  721. {
  722. SetResultErrno(file, result);
  723. }
  724. }
  725. return WriteBsdResult(context, result, errno);
  726. }
  727. [CommandHipc(25)]
  728. // Read(u32 fd) -> (i32 ret, u32 bsd_errno, buffer<i8, 0x22, 0> message)
  729. public ResultCode Read(ServiceCtx context)
  730. {
  731. int fd = context.RequestData.ReadInt32();
  732. (ulong receivePosition, ulong receiveLength) = context.Request.GetBufferType0x22();
  733. WritableRegion receiveRegion = context.Memory.GetWritableRegion(receivePosition, (int)receiveLength);
  734. LinuxError errno = LinuxError.EBADF;
  735. IFileDescriptor file = _context.RetrieveFileDescriptor(fd);
  736. int result = -1;
  737. if (file != null)
  738. {
  739. errno = file.Read(out result, receiveRegion.Memory.Span);
  740. if (errno == LinuxError.SUCCESS)
  741. {
  742. SetResultErrno(file, result);
  743. receiveRegion.Dispose();
  744. }
  745. }
  746. return WriteBsdResult(context, result, errno);
  747. }
  748. [CommandHipc(26)]
  749. // Close(u32 fd) -> (i32 ret, u32 bsd_errno)
  750. public ResultCode Close(ServiceCtx context)
  751. {
  752. int fd = context.RequestData.ReadInt32();
  753. LinuxError errno = LinuxError.EBADF;
  754. if (_context.CloseFileDescriptor(fd))
  755. {
  756. errno = LinuxError.SUCCESS;
  757. }
  758. return WriteBsdResult(context, 0, errno);
  759. }
  760. [CommandHipc(27)]
  761. // DuplicateSocket(u32 fd, u64 reserved) -> (i32 ret, u32 bsd_errno)
  762. public ResultCode DuplicateSocket(ServiceCtx context)
  763. {
  764. int fd = context.RequestData.ReadInt32();
  765. ulong reserved = context.RequestData.ReadUInt64();
  766. LinuxError errno = LinuxError.ENOENT;
  767. int newSockFd = -1;
  768. if (_isPrivileged)
  769. {
  770. errno = LinuxError.SUCCESS;
  771. newSockFd = _context.DuplicateFileDescriptor(fd);
  772. if (newSockFd == -1)
  773. {
  774. errno = LinuxError.EBADF;
  775. }
  776. }
  777. return WriteBsdResult(context, newSockFd, errno);
  778. }
  779. [CommandHipc(29)] // 7.0.0+
  780. // RecvMMsg(u32 fd, u32 vlen, u32 flags, u32 reserved, nn::socket::TimeVal timeout) -> (i32 ret, u32 bsd_errno, buffer<bytes, 6> message);
  781. public ResultCode RecvMMsg(ServiceCtx context)
  782. {
  783. int socketFd = context.RequestData.ReadInt32();
  784. int vlen = context.RequestData.ReadInt32();
  785. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  786. uint reserved = context.RequestData.ReadUInt32();
  787. TimeVal timeout = context.RequestData.ReadStruct<TimeVal>();
  788. ulong receivePosition = context.Request.ReceiveBuff[0].Position;
  789. ulong receiveLength = context.Request.ReceiveBuff[0].Size;
  790. WritableRegion receiveRegion = context.Memory.GetWritableRegion(receivePosition, (int)receiveLength);
  791. LinuxError errno = LinuxError.EBADF;
  792. ISocket socket = _context.RetrieveSocket(socketFd);
  793. int result = -1;
  794. if (socket != null)
  795. {
  796. errno = BsdMMsgHdr.Deserialize(out BsdMMsgHdr message, receiveRegion.Memory.Span, vlen);
  797. if (errno == LinuxError.SUCCESS)
  798. {
  799. errno = socket.RecvMMsg(out result, message, socketFlags, timeout);
  800. if (errno == LinuxError.SUCCESS)
  801. {
  802. errno = BsdMMsgHdr.Serialize(receiveRegion.Memory.Span, message);
  803. }
  804. }
  805. }
  806. if (errno == LinuxError.SUCCESS)
  807. {
  808. SetResultErrno(socket, result);
  809. receiveRegion.Dispose();
  810. }
  811. return WriteBsdResult(context, result, errno);
  812. }
  813. [CommandHipc(30)] // 7.0.0+
  814. // SendMMsg(u32 fd, u32 vlen, u32 flags) -> (i32 ret, u32 bsd_errno, buffer<bytes, 6> message);
  815. public ResultCode SendMMsg(ServiceCtx context)
  816. {
  817. int socketFd = context.RequestData.ReadInt32();
  818. int vlen = context.RequestData.ReadInt32();
  819. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  820. ulong receivePosition = context.Request.ReceiveBuff[0].Position;
  821. ulong receiveLength = context.Request.ReceiveBuff[0].Size;
  822. WritableRegion receiveRegion = context.Memory.GetWritableRegion(receivePosition, (int)receiveLength);
  823. LinuxError errno = LinuxError.EBADF;
  824. ISocket socket = _context.RetrieveSocket(socketFd);
  825. int result = -1;
  826. if (socket != null)
  827. {
  828. errno = BsdMMsgHdr.Deserialize(out BsdMMsgHdr message, receiveRegion.Memory.Span, vlen);
  829. if (errno == LinuxError.SUCCESS)
  830. {
  831. errno = socket.SendMMsg(out result, message, socketFlags);
  832. if (errno == LinuxError.SUCCESS)
  833. {
  834. errno = BsdMMsgHdr.Serialize(receiveRegion.Memory.Span, message);
  835. }
  836. }
  837. }
  838. if (errno == LinuxError.SUCCESS)
  839. {
  840. SetResultErrno(socket, result);
  841. receiveRegion.Dispose();
  842. }
  843. return WriteBsdResult(context, result, errno);
  844. }
  845. [CommandHipc(31)] // 7.0.0+
  846. // EventFd(nn::socket::EventFdFlags flags, u64 initval) -> (i32 ret, u32 bsd_errno)
  847. public ResultCode EventFd(ServiceCtx context)
  848. {
  849. EventFdFlags flags = (EventFdFlags)context.RequestData.ReadUInt32();
  850. context.RequestData.BaseStream.Position += 4; // Padding
  851. ulong initialValue = context.RequestData.ReadUInt64();
  852. EventFileDescriptor newEventFile = new EventFileDescriptor(initialValue, flags);
  853. LinuxError errno = LinuxError.SUCCESS;
  854. int newSockFd = _context.RegisterFileDescriptor(newEventFile);
  855. if (newSockFd == -1)
  856. {
  857. errno = LinuxError.EBADF;
  858. }
  859. return WriteBsdResult(context, newSockFd, errno);
  860. }
  861. }
  862. }