IClient.cs 32 KB

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