IClient.cs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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. if (sockAddrOutSize != 0 && sockAddrOutSize >= (ulong) Unsafe.SizeOf<BsdSockAddr>())
  420. {
  421. context.Memory.Write(sockAddrOutPosition, BsdSockAddr.FromIPEndPoint(endPoint));
  422. }
  423. else
  424. {
  425. errno = LinuxError.ENOMEM;
  426. }
  427. }
  428. }
  429. return WriteBsdResult(context, result, errno);
  430. }
  431. [CommandHipc(10)]
  432. // Send(u32 socket, u32 flags, buffer<i8, 0x21, 0>) -> (i32 ret, u32 bsd_errno)
  433. public ResultCode Send(ServiceCtx context)
  434. {
  435. int socketFd = context.RequestData.ReadInt32();
  436. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  437. (ulong sendPosition, ulong sendSize) = context.Request.GetBufferType0x21();
  438. ReadOnlySpan<byte> sendBuffer = context.Memory.GetSpan(sendPosition, (int)sendSize);
  439. LinuxError errno = LinuxError.EBADF;
  440. ISocket socket = _context.RetrieveSocket(socketFd);
  441. int result = -1;
  442. if (socket != null)
  443. {
  444. errno = socket.Send(out result, sendBuffer, socketFlags);
  445. if (errno == LinuxError.SUCCESS)
  446. {
  447. SetResultErrno(socket, result);
  448. }
  449. }
  450. return WriteBsdResult(context, result, errno);
  451. }
  452. [CommandHipc(11)]
  453. // SendTo(u32 socket, u32 flags, buffer<i8, 0x21, 0>, buffer<nn::socket::sockaddr_in, 0x21, 0x10>) -> (i32 ret, u32 bsd_errno)
  454. public ResultCode SendTo(ServiceCtx context)
  455. {
  456. int socketFd = context.RequestData.ReadInt32();
  457. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  458. (ulong sendPosition, ulong sendSize) = context.Request.GetBufferType0x21(0);
  459. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x21(1);
  460. ReadOnlySpan<byte> sendBuffer = context.Memory.GetSpan(sendPosition, (int)sendSize);
  461. LinuxError errno = LinuxError.EBADF;
  462. ISocket socket = _context.RetrieveSocket(socketFd);
  463. int result = -1;
  464. if (socket != null)
  465. {
  466. IPEndPoint endPoint = context.Memory.Read<BsdSockAddr>(bufferPosition).ToIPEndPoint();
  467. errno = socket.SendTo(out result, sendBuffer, sendBuffer.Length, socketFlags, endPoint);
  468. if (errno == LinuxError.SUCCESS)
  469. {
  470. SetResultErrno(socket, result);
  471. }
  472. }
  473. return WriteBsdResult(context, result, errno);
  474. }
  475. [CommandHipc(12)]
  476. // Accept(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<nn::socket::sockaddr_in, 0x22, 0x10> addr)
  477. public ResultCode Accept(ServiceCtx context)
  478. {
  479. int socketFd = context.RequestData.ReadInt32();
  480. (ulong bufferPos, ulong bufferSize) = context.Request.GetBufferType0x22();
  481. LinuxError errno = LinuxError.EBADF;
  482. ISocket socket = _context.RetrieveSocket(socketFd);
  483. if (socket != null)
  484. {
  485. errno = socket.Accept(out ISocket newSocket);
  486. if (newSocket == null && errno == LinuxError.SUCCESS)
  487. {
  488. errno = LinuxError.EWOULDBLOCK;
  489. }
  490. else if (errno == LinuxError.SUCCESS)
  491. {
  492. int newSockFd = _context.RegisterFileDescriptor(newSocket);
  493. if (newSockFd == -1)
  494. {
  495. errno = LinuxError.EBADF;
  496. }
  497. else
  498. {
  499. WriteSockAddr(context, bufferPos, newSocket, true);
  500. }
  501. WriteBsdResult(context, newSockFd, errno);
  502. context.ResponseData.Write(0x10);
  503. return ResultCode.Success;
  504. }
  505. }
  506. return WriteBsdResult(context, -1, errno);
  507. }
  508. [CommandHipc(13)]
  509. // Bind(u32 socket, buffer<nn::socket::sockaddr_in, 0x21, 0x10> addr) -> (i32 ret, u32 bsd_errno)
  510. public ResultCode Bind(ServiceCtx context)
  511. {
  512. int socketFd = context.RequestData.ReadInt32();
  513. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x21();
  514. LinuxError errno = LinuxError.EBADF;
  515. ISocket socket = _context.RetrieveSocket(socketFd);
  516. if (socket != null)
  517. {
  518. IPEndPoint endPoint = context.Memory.Read<BsdSockAddr>(bufferPosition).ToIPEndPoint();
  519. errno = socket.Bind(endPoint);
  520. }
  521. return WriteBsdResult(context, 0, errno);
  522. }
  523. [CommandHipc(14)]
  524. // Connect(u32 socket, buffer<nn::socket::sockaddr_in, 0x21, 0x10>) -> (i32 ret, u32 bsd_errno)
  525. public ResultCode Connect(ServiceCtx context)
  526. {
  527. int socketFd = context.RequestData.ReadInt32();
  528. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x21();
  529. LinuxError errno = LinuxError.EBADF;
  530. ISocket socket = _context.RetrieveSocket(socketFd);
  531. if (socket != null)
  532. {
  533. IPEndPoint endPoint = context.Memory.Read<BsdSockAddr>(bufferPosition).ToIPEndPoint();
  534. errno = socket.Connect(endPoint);
  535. }
  536. return WriteBsdResult(context, 0, errno);
  537. }
  538. [CommandHipc(15)]
  539. // GetPeerName(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<nn::socket::sockaddr_in, 0x22, 0x10> addr)
  540. public ResultCode GetPeerName(ServiceCtx context)
  541. {
  542. int socketFd = context.RequestData.ReadInt32();
  543. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x22();
  544. LinuxError errno = LinuxError.EBADF;
  545. ISocket socket = _context.RetrieveSocket(socketFd);
  546. if (socket != null)
  547. {
  548. errno = LinuxError.ENOTCONN;
  549. if (socket.RemoteEndPoint != null)
  550. {
  551. errno = LinuxError.SUCCESS;
  552. WriteSockAddr(context, bufferPosition, socket, true);
  553. WriteBsdResult(context, 0, errno);
  554. context.ResponseData.Write(Unsafe.SizeOf<BsdSockAddr>());
  555. }
  556. }
  557. return WriteBsdResult(context, 0, errno);
  558. }
  559. [CommandHipc(16)]
  560. // GetSockName(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<nn::socket::sockaddr_in, 0x22, 0x10> addr)
  561. public ResultCode GetSockName(ServiceCtx context)
  562. {
  563. int socketFd = context.RequestData.ReadInt32();
  564. (ulong bufferPos, ulong bufferSize) = context.Request.GetBufferType0x22();
  565. LinuxError errno = LinuxError.EBADF;
  566. ISocket socket = _context.RetrieveSocket(socketFd);
  567. if (socket != null)
  568. {
  569. errno = LinuxError.SUCCESS;
  570. WriteSockAddr(context, bufferPos, socket, false);
  571. WriteBsdResult(context, 0, errno);
  572. context.ResponseData.Write(Unsafe.SizeOf<BsdSockAddr>());
  573. }
  574. return WriteBsdResult(context, 0, errno);
  575. }
  576. [CommandHipc(17)]
  577. // GetSockOpt(u32 socket, u32 level, u32 option_name) -> (i32 ret, u32 bsd_errno, u32, buffer<unknown, 0x22, 0>)
  578. public ResultCode GetSockOpt(ServiceCtx context)
  579. {
  580. int socketFd = context.RequestData.ReadInt32();
  581. SocketOptionLevel level = (SocketOptionLevel)context.RequestData.ReadInt32();
  582. BsdSocketOption option = (BsdSocketOption)context.RequestData.ReadInt32();
  583. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x22();
  584. WritableRegion optionValue = context.Memory.GetWritableRegion(bufferPosition, (int)bufferSize);
  585. LinuxError errno = LinuxError.EBADF;
  586. ISocket socket = _context.RetrieveSocket(socketFd);
  587. if (socket != null)
  588. {
  589. errno = socket.GetSocketOption(option, level, optionValue.Memory.Span);
  590. if (errno == LinuxError.SUCCESS)
  591. {
  592. optionValue.Dispose();
  593. }
  594. }
  595. return WriteBsdResult(context, 0, errno);
  596. }
  597. [CommandHipc(18)]
  598. // Listen(u32 socket, u32 backlog) -> (i32 ret, u32 bsd_errno)
  599. public ResultCode Listen(ServiceCtx context)
  600. {
  601. int socketFd = context.RequestData.ReadInt32();
  602. int backlog = context.RequestData.ReadInt32();
  603. LinuxError errno = LinuxError.EBADF;
  604. ISocket socket = _context.RetrieveSocket(socketFd);
  605. if (socket != null)
  606. {
  607. errno = socket.Listen(backlog);
  608. }
  609. return WriteBsdResult(context, 0, errno);
  610. }
  611. [CommandHipc(19)]
  612. // 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>)
  613. public ResultCode Ioctl(ServiceCtx context)
  614. {
  615. int socketFd = context.RequestData.ReadInt32();
  616. BsdIoctl cmd = (BsdIoctl)context.RequestData.ReadInt32();
  617. int bufferCount = context.RequestData.ReadInt32();
  618. LinuxError errno = LinuxError.EBADF;
  619. ISocket socket = _context.RetrieveSocket(socketFd);
  620. if (socket != null)
  621. {
  622. switch (cmd)
  623. {
  624. case BsdIoctl.AtMark:
  625. errno = LinuxError.SUCCESS;
  626. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x22();
  627. // FIXME: OOB not implemented.
  628. context.Memory.Write(bufferPosition, 0);
  629. break;
  630. default:
  631. errno = LinuxError.EOPNOTSUPP;
  632. Logger.Warning?.Print(LogClass.ServiceBsd, $"Unsupported Ioctl Cmd: {cmd}");
  633. break;
  634. }
  635. }
  636. return WriteBsdResult(context, 0, errno);
  637. }
  638. [CommandHipc(20)]
  639. // Fcntl(u32 socket, u32 cmd, u32 arg) -> (i32 ret, u32 bsd_errno)
  640. public ResultCode Fcntl(ServiceCtx context)
  641. {
  642. int socketFd = context.RequestData.ReadInt32();
  643. int cmd = context.RequestData.ReadInt32();
  644. int arg = context.RequestData.ReadInt32();
  645. int result = 0;
  646. LinuxError errno = LinuxError.EBADF;
  647. ISocket socket = _context.RetrieveSocket(socketFd);
  648. if (socket != null)
  649. {
  650. errno = LinuxError.SUCCESS;
  651. if (cmd == 0x3)
  652. {
  653. result = !socket.Blocking ? 0x800 : 0;
  654. }
  655. else if (cmd == 0x4 && arg == 0x800)
  656. {
  657. socket.Blocking = false;
  658. result = 0;
  659. }
  660. else
  661. {
  662. errno = LinuxError.EOPNOTSUPP;
  663. }
  664. }
  665. return WriteBsdResult(context, result, errno);
  666. }
  667. [CommandHipc(21)]
  668. // SetSockOpt(u32 socket, u32 level, u32 option_name, buffer<unknown, 0x21, 0> option_value) -> (i32 ret, u32 bsd_errno)
  669. public ResultCode SetSockOpt(ServiceCtx context)
  670. {
  671. int socketFd = context.RequestData.ReadInt32();
  672. SocketOptionLevel level = (SocketOptionLevel)context.RequestData.ReadInt32();
  673. BsdSocketOption option = (BsdSocketOption)context.RequestData.ReadInt32();
  674. (ulong bufferPos, ulong bufferSize) = context.Request.GetBufferType0x21();
  675. ReadOnlySpan<byte> optionValue = context.Memory.GetSpan(bufferPos, (int)bufferSize);
  676. LinuxError errno = LinuxError.EBADF;
  677. ISocket socket = _context.RetrieveSocket(socketFd);
  678. if (socket != null)
  679. {
  680. errno = socket.SetSocketOption(option, level, optionValue);
  681. }
  682. return WriteBsdResult(context, 0, errno);
  683. }
  684. [CommandHipc(22)]
  685. // Shutdown(u32 socket, u32 how) -> (i32 ret, u32 bsd_errno)
  686. public ResultCode Shutdown(ServiceCtx context)
  687. {
  688. int socketFd = context.RequestData.ReadInt32();
  689. int how = context.RequestData.ReadInt32();
  690. LinuxError errno = LinuxError.EBADF;
  691. ISocket socket = _context.RetrieveSocket(socketFd);
  692. if (socket != null)
  693. {
  694. errno = LinuxError.EINVAL;
  695. if (how >= 0 && how <= 2)
  696. {
  697. errno = socket.Shutdown((BsdSocketShutdownFlags)how);
  698. }
  699. }
  700. return WriteBsdResult(context, 0, errno);
  701. }
  702. [CommandHipc(23)]
  703. // ShutdownAllSockets(u32 how) -> (i32 ret, u32 bsd_errno)
  704. public ResultCode ShutdownAllSockets(ServiceCtx context)
  705. {
  706. int how = context.RequestData.ReadInt32();
  707. LinuxError errno = LinuxError.EINVAL;
  708. if (how >= 0 && how <= 2)
  709. {
  710. errno = _context.ShutdownAllSockets((BsdSocketShutdownFlags)how);
  711. }
  712. return WriteBsdResult(context, 0, errno);
  713. }
  714. [CommandHipc(24)]
  715. // Write(u32 fd, buffer<i8, 0x21, 0> message) -> (i32 ret, u32 bsd_errno)
  716. public ResultCode Write(ServiceCtx context)
  717. {
  718. int fd = context.RequestData.ReadInt32();
  719. (ulong sendPosition, ulong sendSize) = context.Request.GetBufferType0x21();
  720. ReadOnlySpan<byte> sendBuffer = context.Memory.GetSpan(sendPosition, (int)sendSize);
  721. LinuxError errno = LinuxError.EBADF;
  722. IFileDescriptor file = _context.RetrieveFileDescriptor(fd);
  723. int result = -1;
  724. if (file != null)
  725. {
  726. errno = file.Write(out result, sendBuffer);
  727. if (errno == LinuxError.SUCCESS)
  728. {
  729. SetResultErrno(file, result);
  730. }
  731. }
  732. return WriteBsdResult(context, result, errno);
  733. }
  734. [CommandHipc(25)]
  735. // Read(u32 fd) -> (i32 ret, u32 bsd_errno, buffer<i8, 0x22, 0> message)
  736. public ResultCode Read(ServiceCtx context)
  737. {
  738. int fd = context.RequestData.ReadInt32();
  739. (ulong receivePosition, ulong receiveLength) = context.Request.GetBufferType0x22();
  740. WritableRegion receiveRegion = context.Memory.GetWritableRegion(receivePosition, (int)receiveLength);
  741. LinuxError errno = LinuxError.EBADF;
  742. IFileDescriptor file = _context.RetrieveFileDescriptor(fd);
  743. int result = -1;
  744. if (file != null)
  745. {
  746. errno = file.Read(out result, receiveRegion.Memory.Span);
  747. if (errno == LinuxError.SUCCESS)
  748. {
  749. SetResultErrno(file, result);
  750. receiveRegion.Dispose();
  751. }
  752. }
  753. return WriteBsdResult(context, result, errno);
  754. }
  755. [CommandHipc(26)]
  756. // Close(u32 fd) -> (i32 ret, u32 bsd_errno)
  757. public ResultCode Close(ServiceCtx context)
  758. {
  759. int fd = context.RequestData.ReadInt32();
  760. LinuxError errno = LinuxError.EBADF;
  761. if (_context.CloseFileDescriptor(fd))
  762. {
  763. errno = LinuxError.SUCCESS;
  764. }
  765. return WriteBsdResult(context, 0, errno);
  766. }
  767. [CommandHipc(27)]
  768. // DuplicateSocket(u32 fd, u64 reserved) -> (i32 ret, u32 bsd_errno)
  769. public ResultCode DuplicateSocket(ServiceCtx context)
  770. {
  771. int fd = context.RequestData.ReadInt32();
  772. ulong reserved = context.RequestData.ReadUInt64();
  773. LinuxError errno = LinuxError.ENOENT;
  774. int newSockFd = -1;
  775. if (_isPrivileged)
  776. {
  777. errno = LinuxError.SUCCESS;
  778. newSockFd = _context.DuplicateFileDescriptor(fd);
  779. if (newSockFd == -1)
  780. {
  781. errno = LinuxError.EBADF;
  782. }
  783. }
  784. return WriteBsdResult(context, newSockFd, errno);
  785. }
  786. [CommandHipc(29)] // 7.0.0+
  787. // RecvMMsg(u32 fd, u32 vlen, u32 flags, u32 reserved, nn::socket::TimeVal timeout) -> (i32 ret, u32 bsd_errno, buffer<bytes, 6> message);
  788. public ResultCode RecvMMsg(ServiceCtx context)
  789. {
  790. int socketFd = context.RequestData.ReadInt32();
  791. int vlen = context.RequestData.ReadInt32();
  792. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  793. uint reserved = context.RequestData.ReadUInt32();
  794. TimeVal timeout = context.RequestData.ReadStruct<TimeVal>();
  795. ulong receivePosition = context.Request.ReceiveBuff[0].Position;
  796. ulong receiveLength = context.Request.ReceiveBuff[0].Size;
  797. WritableRegion receiveRegion = context.Memory.GetWritableRegion(receivePosition, (int)receiveLength);
  798. LinuxError errno = LinuxError.EBADF;
  799. ISocket socket = _context.RetrieveSocket(socketFd);
  800. int result = -1;
  801. if (socket != null)
  802. {
  803. errno = BsdMMsgHdr.Deserialize(out BsdMMsgHdr message, receiveRegion.Memory.Span, vlen);
  804. if (errno == LinuxError.SUCCESS)
  805. {
  806. errno = socket.RecvMMsg(out result, message, socketFlags, timeout);
  807. if (errno == LinuxError.SUCCESS)
  808. {
  809. errno = BsdMMsgHdr.Serialize(receiveRegion.Memory.Span, message);
  810. }
  811. }
  812. }
  813. if (errno == LinuxError.SUCCESS)
  814. {
  815. SetResultErrno(socket, result);
  816. receiveRegion.Dispose();
  817. }
  818. return WriteBsdResult(context, result, errno);
  819. }
  820. [CommandHipc(30)] // 7.0.0+
  821. // SendMMsg(u32 fd, u32 vlen, u32 flags) -> (i32 ret, u32 bsd_errno, buffer<bytes, 6> message);
  822. public ResultCode SendMMsg(ServiceCtx context)
  823. {
  824. int socketFd = context.RequestData.ReadInt32();
  825. int vlen = context.RequestData.ReadInt32();
  826. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  827. ulong receivePosition = context.Request.ReceiveBuff[0].Position;
  828. ulong receiveLength = context.Request.ReceiveBuff[0].Size;
  829. WritableRegion receiveRegion = context.Memory.GetWritableRegion(receivePosition, (int)receiveLength);
  830. LinuxError errno = LinuxError.EBADF;
  831. ISocket socket = _context.RetrieveSocket(socketFd);
  832. int result = -1;
  833. if (socket != null)
  834. {
  835. errno = BsdMMsgHdr.Deserialize(out BsdMMsgHdr message, receiveRegion.Memory.Span, vlen);
  836. if (errno == LinuxError.SUCCESS)
  837. {
  838. errno = socket.SendMMsg(out result, message, socketFlags);
  839. if (errno == LinuxError.SUCCESS)
  840. {
  841. errno = BsdMMsgHdr.Serialize(receiveRegion.Memory.Span, message);
  842. }
  843. }
  844. }
  845. if (errno == LinuxError.SUCCESS)
  846. {
  847. SetResultErrno(socket, result);
  848. receiveRegion.Dispose();
  849. }
  850. return WriteBsdResult(context, result, errno);
  851. }
  852. [CommandHipc(31)] // 7.0.0+
  853. // EventFd(nn::socket::EventFdFlags flags, u64 initval) -> (i32 ret, u32 bsd_errno)
  854. public ResultCode EventFd(ServiceCtx context)
  855. {
  856. EventFdFlags flags = (EventFdFlags)context.RequestData.ReadUInt32();
  857. context.RequestData.BaseStream.Position += 4; // Padding
  858. ulong initialValue = context.RequestData.ReadUInt64();
  859. EventFileDescriptor newEventFile = new EventFileDescriptor(initialValue, flags);
  860. LinuxError errno = LinuxError.SUCCESS;
  861. int newSockFd = _context.RegisterFileDescriptor(newEventFile);
  862. if (newSockFd == -1)
  863. {
  864. errno = LinuxError.EBADF;
  865. }
  866. return WriteBsdResult(context, newSockFd, errno);
  867. }
  868. }
  869. }