IClient.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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 inputBufferPosition, ulong inputBufferSize) = context.Request.GetBufferType0x21();
  178. (ulong outputBufferPosition, ulong outputBufferSize) = context.Request.GetBufferType0x22();
  179. if (timeout < -1 || fdsCount < 0 || (ulong)(fdsCount * 8) > inputBufferSize)
  180. {
  181. return WriteBsdResult(context, -1, LinuxError.EINVAL);
  182. }
  183. PollEvent[] events = new PollEvent[fdsCount];
  184. for (int i = 0; i < fdsCount; i++)
  185. {
  186. PollEventData pollEventData = context.Memory.Read<PollEventData>(inputBufferPosition + (ulong)(i * Unsafe.SizeOf<PollEventData>()));
  187. IFileDescriptor fileDescriptor = _context.RetrieveFileDescriptor(pollEventData.SocketFd);
  188. if (fileDescriptor == null)
  189. {
  190. return WriteBsdResult(context, -1, LinuxError.EBADF);
  191. }
  192. events[i] = new PollEvent(pollEventData, fileDescriptor);
  193. }
  194. List<PollEvent> discoveredEvents = new List<PollEvent>();
  195. List<PollEvent>[] eventsByPollManager = new List<PollEvent>[_pollManagers.Count];
  196. for (int i = 0; i < eventsByPollManager.Length; i++)
  197. {
  198. eventsByPollManager[i] = new List<PollEvent>();
  199. foreach (PollEvent evnt in events)
  200. {
  201. if (_pollManagers[i].IsCompatible(evnt))
  202. {
  203. eventsByPollManager[i].Add(evnt);
  204. discoveredEvents.Add(evnt);
  205. }
  206. }
  207. }
  208. foreach (PollEvent evnt in events)
  209. {
  210. if (!discoveredEvents.Contains(evnt))
  211. {
  212. Logger.Error?.Print(LogClass.ServiceBsd, $"Poll operation is not supported for {evnt.FileDescriptor.GetType().Name}!");
  213. return WriteBsdResult(context, -1, LinuxError.EBADF);
  214. }
  215. }
  216. int updateCount = 0;
  217. LinuxError errno = LinuxError.SUCCESS;
  218. if (fdsCount != 0)
  219. {
  220. bool IsUnexpectedLinuxError(LinuxError error)
  221. {
  222. return error != LinuxError.SUCCESS && error != LinuxError.ETIMEDOUT;
  223. }
  224. // Hybrid approach
  225. long budgetLeftMilliseconds;
  226. if (timeout == -1)
  227. {
  228. budgetLeftMilliseconds = PerformanceCounter.ElapsedMilliseconds + uint.MaxValue;
  229. }
  230. else
  231. {
  232. budgetLeftMilliseconds = PerformanceCounter.ElapsedMilliseconds + timeout;
  233. }
  234. do
  235. {
  236. for (int i = 0; i < eventsByPollManager.Length; i++)
  237. {
  238. if (eventsByPollManager[i].Count == 0)
  239. {
  240. continue;
  241. }
  242. errno = _pollManagers[i].Poll(eventsByPollManager[i], 0, out updateCount);
  243. if (IsUnexpectedLinuxError(errno))
  244. {
  245. break;
  246. }
  247. if (updateCount > 0)
  248. {
  249. break;
  250. }
  251. }
  252. // If we are here, that mean nothing was availaible, sleep for 50ms
  253. context.Device.System.KernelContext.Syscall.SleepThread(50 * 1000000);
  254. }
  255. while (PerformanceCounter.ElapsedMilliseconds < budgetLeftMilliseconds);
  256. }
  257. else if (timeout == -1)
  258. {
  259. // 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)
  260. throw new InvalidOperationException();
  261. }
  262. else
  263. {
  264. context.Device.System.KernelContext.Syscall.SleepThread(timeout);
  265. }
  266. // TODO: Spanify
  267. for (int i = 0; i < fdsCount; i++)
  268. {
  269. context.Memory.Write(outputBufferPosition + (ulong)(i * Unsafe.SizeOf<PollEventData>()), events[i].Data);
  270. }
  271. return WriteBsdResult(context, updateCount, errno);
  272. }
  273. [CommandHipc(7)]
  274. // Sysctl(buffer<unknown, 0x21, 0>, buffer<unknown, 0x21, 0>) -> (i32 ret, u32 bsd_errno, u32, buffer<unknown, 0x22, 0>)
  275. public ResultCode Sysctl(ServiceCtx context)
  276. {
  277. WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP);
  278. Logger.Stub?.PrintStub(LogClass.ServiceBsd);
  279. return ResultCode.Success;
  280. }
  281. [CommandHipc(8)]
  282. // Recv(u32 socket, u32 flags) -> (i32 ret, u32 bsd_errno, array<i8, 0x22> message)
  283. public ResultCode Recv(ServiceCtx context)
  284. {
  285. int socketFd = context.RequestData.ReadInt32();
  286. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  287. (ulong receivePosition, ulong receiveLength) = context.Request.GetBufferType0x22();
  288. WritableRegion receiveRegion = context.Memory.GetWritableRegion(receivePosition, (int)receiveLength);
  289. LinuxError errno = LinuxError.EBADF;
  290. ISocket socket = _context.RetrieveSocket(socketFd);
  291. int result = -1;
  292. if (socket != null)
  293. {
  294. errno = socket.Receive(out result, receiveRegion.Memory.Span, socketFlags);
  295. if (errno == LinuxError.SUCCESS)
  296. {
  297. SetResultErrno(socket, result);
  298. receiveRegion.Dispose();
  299. }
  300. }
  301. return WriteBsdResult(context, result, errno);
  302. }
  303. [CommandHipc(9)]
  304. // RecvFrom(u32 sock, u32 flags) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<i8, 0x22, 0> message, buffer<nn::socket::sockaddr_in, 0x22, 0x10>)
  305. public ResultCode RecvFrom(ServiceCtx context)
  306. {
  307. int socketFd = context.RequestData.ReadInt32();
  308. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  309. (ulong receivePosition, ulong receiveLength) = context.Request.GetBufferType0x22(0);
  310. (ulong sockAddrOutPosition, ulong sockAddrOutSize) = context.Request.GetBufferType0x22(1);
  311. WritableRegion receiveRegion = context.Memory.GetWritableRegion(receivePosition, (int)receiveLength);
  312. LinuxError errno = LinuxError.EBADF;
  313. ISocket socket = _context.RetrieveSocket(socketFd);
  314. int result = -1;
  315. if (socket != null)
  316. {
  317. errno = socket.ReceiveFrom(out result, receiveRegion.Memory.Span, receiveRegion.Memory.Span.Length, socketFlags, out IPEndPoint endPoint);
  318. if (errno == LinuxError.SUCCESS)
  319. {
  320. SetResultErrno(socket, result);
  321. receiveRegion.Dispose();
  322. context.Memory.Write(sockAddrOutPosition, BsdSockAddr.FromIPEndPoint(endPoint));
  323. }
  324. }
  325. return WriteBsdResult(context, result, errno);
  326. }
  327. [CommandHipc(10)]
  328. // Send(u32 socket, u32 flags, buffer<i8, 0x21, 0>) -> (i32 ret, u32 bsd_errno)
  329. public ResultCode Send(ServiceCtx context)
  330. {
  331. int socketFd = context.RequestData.ReadInt32();
  332. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  333. (ulong sendPosition, ulong sendSize) = context.Request.GetBufferType0x21();
  334. ReadOnlySpan<byte> sendBuffer = context.Memory.GetSpan(sendPosition, (int)sendSize);
  335. LinuxError errno = LinuxError.EBADF;
  336. ISocket socket = _context.RetrieveSocket(socketFd);
  337. int result = -1;
  338. if (socket != null)
  339. {
  340. errno = socket.Send(out result, sendBuffer, socketFlags);
  341. if (errno == LinuxError.SUCCESS)
  342. {
  343. SetResultErrno(socket, result);
  344. }
  345. }
  346. return WriteBsdResult(context, result, errno);
  347. }
  348. [CommandHipc(11)]
  349. // SendTo(u32 socket, u32 flags, buffer<i8, 0x21, 0>, buffer<nn::socket::sockaddr_in, 0x21, 0x10>) -> (i32 ret, u32 bsd_errno)
  350. public ResultCode SendTo(ServiceCtx context)
  351. {
  352. int socketFd = context.RequestData.ReadInt32();
  353. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  354. (ulong sendPosition, ulong sendSize) = context.Request.GetBufferType0x21(0);
  355. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x21(1);
  356. ReadOnlySpan<byte> sendBuffer = context.Memory.GetSpan(sendPosition, (int)sendSize);
  357. LinuxError errno = LinuxError.EBADF;
  358. ISocket socket = _context.RetrieveSocket(socketFd);
  359. int result = -1;
  360. if (socket != null)
  361. {
  362. IPEndPoint endPoint = context.Memory.Read<BsdSockAddr>(bufferPosition).ToIPEndPoint();
  363. errno = socket.SendTo(out result, sendBuffer, sendBuffer.Length, socketFlags, endPoint);
  364. if (errno == LinuxError.SUCCESS)
  365. {
  366. SetResultErrno(socket, result);
  367. }
  368. }
  369. return WriteBsdResult(context, result, errno);
  370. }
  371. [CommandHipc(12)]
  372. // Accept(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<nn::socket::sockaddr_in, 0x22, 0x10> addr)
  373. public ResultCode Accept(ServiceCtx context)
  374. {
  375. int socketFd = context.RequestData.ReadInt32();
  376. (ulong bufferPos, ulong bufferSize) = context.Request.GetBufferType0x22();
  377. LinuxError errno = LinuxError.EBADF;
  378. ISocket socket = _context.RetrieveSocket(socketFd);
  379. if (socket != null)
  380. {
  381. errno = socket.Accept(out ISocket newSocket);
  382. if (newSocket == null && errno == LinuxError.SUCCESS)
  383. {
  384. errno = LinuxError.EWOULDBLOCK;
  385. }
  386. else if (errno == LinuxError.SUCCESS)
  387. {
  388. int newSockFd = _context.RegisterFileDescriptor(newSocket);
  389. if (newSockFd == -1)
  390. {
  391. errno = LinuxError.EBADF;
  392. }
  393. else
  394. {
  395. WriteSockAddr(context, bufferPos, newSocket, true);
  396. }
  397. WriteBsdResult(context, newSockFd, errno);
  398. context.ResponseData.Write(0x10);
  399. return ResultCode.Success;
  400. }
  401. }
  402. return WriteBsdResult(context, -1, errno);
  403. }
  404. [CommandHipc(13)]
  405. // Bind(u32 socket, buffer<nn::socket::sockaddr_in, 0x21, 0x10> addr) -> (i32 ret, u32 bsd_errno)
  406. public ResultCode Bind(ServiceCtx context)
  407. {
  408. int socketFd = context.RequestData.ReadInt32();
  409. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x21();
  410. LinuxError errno = LinuxError.EBADF;
  411. ISocket socket = _context.RetrieveSocket(socketFd);
  412. if (socket != null)
  413. {
  414. IPEndPoint endPoint = context.Memory.Read<BsdSockAddr>(bufferPosition).ToIPEndPoint();
  415. errno = socket.Bind(endPoint);
  416. }
  417. return WriteBsdResult(context, 0, errno);
  418. }
  419. [CommandHipc(14)]
  420. // Connect(u32 socket, buffer<nn::socket::sockaddr_in, 0x21, 0x10>) -> (i32 ret, u32 bsd_errno)
  421. public ResultCode Connect(ServiceCtx context)
  422. {
  423. int socketFd = context.RequestData.ReadInt32();
  424. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x21();
  425. LinuxError errno = LinuxError.EBADF;
  426. ISocket socket = _context.RetrieveSocket(socketFd);
  427. if (socket != null)
  428. {
  429. IPEndPoint endPoint = context.Memory.Read<BsdSockAddr>(bufferPosition).ToIPEndPoint();
  430. errno = socket.Connect(endPoint);
  431. }
  432. return WriteBsdResult(context, 0, errno);
  433. }
  434. [CommandHipc(15)]
  435. // GetPeerName(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<nn::socket::sockaddr_in, 0x22, 0x10> addr)
  436. public ResultCode GetPeerName(ServiceCtx context)
  437. {
  438. int socketFd = context.RequestData.ReadInt32();
  439. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x22();
  440. LinuxError errno = LinuxError.EBADF;
  441. ISocket socket = _context.RetrieveSocket(socketFd);
  442. if (socket != null)
  443. {
  444. errno = LinuxError.SUCCESS;
  445. WriteSockAddr(context, bufferPosition, socket, true);
  446. WriteBsdResult(context, 0, errno);
  447. context.ResponseData.Write(Unsafe.SizeOf<BsdSockAddr>());
  448. }
  449. return WriteBsdResult(context, 0, errno);
  450. }
  451. [CommandHipc(16)]
  452. // GetSockName(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<nn::socket::sockaddr_in, 0x22, 0x10> addr)
  453. public ResultCode GetSockName(ServiceCtx context)
  454. {
  455. int socketFd = context.RequestData.ReadInt32();
  456. (ulong bufferPos, ulong bufferSize) = context.Request.GetBufferType0x22();
  457. LinuxError errno = LinuxError.EBADF;
  458. ISocket socket = _context.RetrieveSocket(socketFd);
  459. if (socket != null)
  460. {
  461. errno = LinuxError.SUCCESS;
  462. WriteSockAddr(context, bufferPos, socket, false);
  463. WriteBsdResult(context, 0, errno);
  464. context.ResponseData.Write(Unsafe.SizeOf<BsdSockAddr>());
  465. }
  466. return WriteBsdResult(context, 0, errno);
  467. }
  468. [CommandHipc(17)]
  469. // GetSockOpt(u32 socket, u32 level, u32 option_name) -> (i32 ret, u32 bsd_errno, u32, buffer<unknown, 0x22, 0>)
  470. public ResultCode GetSockOpt(ServiceCtx context)
  471. {
  472. int socketFd = context.RequestData.ReadInt32();
  473. SocketOptionLevel level = (SocketOptionLevel)context.RequestData.ReadInt32();
  474. BsdSocketOption option = (BsdSocketOption)context.RequestData.ReadInt32();
  475. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x22();
  476. WritableRegion optionValue = context.Memory.GetWritableRegion(bufferPosition, (int)bufferSize);
  477. LinuxError errno = LinuxError.EBADF;
  478. ISocket socket = _context.RetrieveSocket(socketFd);
  479. if (socket != null)
  480. {
  481. errno = socket.GetSocketOption(option, level, optionValue.Memory.Span);
  482. if (errno == LinuxError.SUCCESS)
  483. {
  484. optionValue.Dispose();
  485. }
  486. }
  487. return WriteBsdResult(context, 0, errno);
  488. }
  489. [CommandHipc(18)]
  490. // Listen(u32 socket, u32 backlog) -> (i32 ret, u32 bsd_errno)
  491. public ResultCode Listen(ServiceCtx context)
  492. {
  493. int socketFd = context.RequestData.ReadInt32();
  494. int backlog = context.RequestData.ReadInt32();
  495. LinuxError errno = LinuxError.EBADF;
  496. ISocket socket = _context.RetrieveSocket(socketFd);
  497. if (socket != null)
  498. {
  499. errno = socket.Listen(backlog);
  500. }
  501. return WriteBsdResult(context, 0, errno);
  502. }
  503. [CommandHipc(19)]
  504. // 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>)
  505. public ResultCode Ioctl(ServiceCtx context)
  506. {
  507. int socketFd = context.RequestData.ReadInt32();
  508. BsdIoctl cmd = (BsdIoctl)context.RequestData.ReadInt32();
  509. int bufferCount = context.RequestData.ReadInt32();
  510. LinuxError errno = LinuxError.EBADF;
  511. ISocket socket = _context.RetrieveSocket(socketFd);
  512. if (socket != null)
  513. {
  514. switch (cmd)
  515. {
  516. case BsdIoctl.AtMark:
  517. errno = LinuxError.SUCCESS;
  518. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x22();
  519. // FIXME: OOB not implemented.
  520. context.Memory.Write(bufferPosition, 0);
  521. break;
  522. default:
  523. errno = LinuxError.EOPNOTSUPP;
  524. Logger.Warning?.Print(LogClass.ServiceBsd, $"Unsupported Ioctl Cmd: {cmd}");
  525. break;
  526. }
  527. }
  528. return WriteBsdResult(context, 0, errno);
  529. }
  530. [CommandHipc(20)]
  531. // Fcntl(u32 socket, u32 cmd, u32 arg) -> (i32 ret, u32 bsd_errno)
  532. public ResultCode Fcntl(ServiceCtx context)
  533. {
  534. int socketFd = context.RequestData.ReadInt32();
  535. int cmd = context.RequestData.ReadInt32();
  536. int arg = context.RequestData.ReadInt32();
  537. int result = 0;
  538. LinuxError errno = LinuxError.EBADF;
  539. ISocket socket = _context.RetrieveSocket(socketFd);
  540. if (socket != null)
  541. {
  542. errno = LinuxError.SUCCESS;
  543. if (cmd == 0x3)
  544. {
  545. result = !socket.Blocking ? 0x800 : 0;
  546. }
  547. else if (cmd == 0x4 && arg == 0x800)
  548. {
  549. socket.Blocking = false;
  550. result = 0;
  551. }
  552. else
  553. {
  554. errno = LinuxError.EOPNOTSUPP;
  555. }
  556. }
  557. return WriteBsdResult(context, result, errno);
  558. }
  559. [CommandHipc(21)]
  560. // SetSockOpt(u32 socket, u32 level, u32 option_name, buffer<unknown, 0x21, 0> option_value) -> (i32 ret, u32 bsd_errno)
  561. public ResultCode SetSockOpt(ServiceCtx context)
  562. {
  563. int socketFd = context.RequestData.ReadInt32();
  564. SocketOptionLevel level = (SocketOptionLevel)context.RequestData.ReadInt32();
  565. BsdSocketOption option = (BsdSocketOption)context.RequestData.ReadInt32();
  566. (ulong bufferPos, ulong bufferSize) = context.Request.GetBufferType0x21();
  567. ReadOnlySpan<byte> optionValue = context.Memory.GetSpan(bufferPos, (int)bufferSize);
  568. LinuxError errno = LinuxError.EBADF;
  569. ISocket socket = _context.RetrieveSocket(socketFd);
  570. if (socket != null)
  571. {
  572. errno = socket.SetSocketOption(option, level, optionValue);
  573. }
  574. return WriteBsdResult(context, 0, errno);
  575. }
  576. [CommandHipc(22)]
  577. // Shutdown(u32 socket, u32 how) -> (i32 ret, u32 bsd_errno)
  578. public ResultCode Shutdown(ServiceCtx context)
  579. {
  580. int socketFd = context.RequestData.ReadInt32();
  581. int how = context.RequestData.ReadInt32();
  582. LinuxError errno = LinuxError.EBADF;
  583. ISocket socket = _context.RetrieveSocket(socketFd);
  584. if (socket != null)
  585. {
  586. errno = LinuxError.EINVAL;
  587. if (how >= 0 && how <= 2)
  588. {
  589. errno = socket.Shutdown((BsdSocketShutdownFlags)how);
  590. }
  591. }
  592. return WriteBsdResult(context, 0, errno);
  593. }
  594. [CommandHipc(23)]
  595. // ShutdownAllSockets(u32 how) -> (i32 ret, u32 bsd_errno)
  596. public ResultCode ShutdownAllSockets(ServiceCtx context)
  597. {
  598. int how = context.RequestData.ReadInt32();
  599. LinuxError errno = LinuxError.EINVAL;
  600. if (how >= 0 && how <= 2)
  601. {
  602. errno = _context.ShutdownAllSockets((BsdSocketShutdownFlags)how);
  603. }
  604. return WriteBsdResult(context, 0, errno);
  605. }
  606. [CommandHipc(24)]
  607. // Write(u32 fd, buffer<i8, 0x21, 0> message) -> (i32 ret, u32 bsd_errno)
  608. public ResultCode Write(ServiceCtx context)
  609. {
  610. int fd = context.RequestData.ReadInt32();
  611. (ulong sendPosition, ulong sendSize) = context.Request.GetBufferType0x21();
  612. ReadOnlySpan<byte> sendBuffer = context.Memory.GetSpan(sendPosition, (int)sendSize);
  613. LinuxError errno = LinuxError.EBADF;
  614. IFileDescriptor file = _context.RetrieveFileDescriptor(fd);
  615. int result = -1;
  616. if (file != null)
  617. {
  618. errno = file.Write(out result, sendBuffer);
  619. if (errno == LinuxError.SUCCESS)
  620. {
  621. SetResultErrno(file, result);
  622. }
  623. }
  624. return WriteBsdResult(context, result, errno);
  625. }
  626. [CommandHipc(25)]
  627. // Read(u32 fd) -> (i32 ret, u32 bsd_errno, buffer<i8, 0x22, 0> message)
  628. public ResultCode Read(ServiceCtx context)
  629. {
  630. int fd = context.RequestData.ReadInt32();
  631. (ulong receivePosition, ulong receiveLength) = context.Request.GetBufferType0x22();
  632. WritableRegion receiveRegion = context.Memory.GetWritableRegion(receivePosition, (int)receiveLength);
  633. LinuxError errno = LinuxError.EBADF;
  634. IFileDescriptor file = _context.RetrieveFileDescriptor(fd);
  635. int result = -1;
  636. if (file != null)
  637. {
  638. errno = file.Read(out result, receiveRegion.Memory.Span);
  639. if (errno == LinuxError.SUCCESS)
  640. {
  641. SetResultErrno(file, result);
  642. receiveRegion.Dispose();
  643. }
  644. }
  645. return WriteBsdResult(context, result, errno);
  646. }
  647. [CommandHipc(26)]
  648. // Close(u32 fd) -> (i32 ret, u32 bsd_errno)
  649. public ResultCode Close(ServiceCtx context)
  650. {
  651. int fd = context.RequestData.ReadInt32();
  652. LinuxError errno = LinuxError.EBADF;
  653. if (_context.CloseFileDescriptor(fd))
  654. {
  655. errno = LinuxError.SUCCESS;
  656. }
  657. return WriteBsdResult(context, 0, errno);
  658. }
  659. [CommandHipc(27)]
  660. // DuplicateSocket(u32 fd, u64 reserved) -> (i32 ret, u32 bsd_errno)
  661. public ResultCode DuplicateSocket(ServiceCtx context)
  662. {
  663. int fd = context.RequestData.ReadInt32();
  664. ulong reserved = context.RequestData.ReadUInt64();
  665. LinuxError errno = LinuxError.ENOENT;
  666. int newSockFd = -1;
  667. if (_isPrivileged)
  668. {
  669. errno = LinuxError.SUCCESS;
  670. newSockFd = _context.DuplicateFileDescriptor(fd);
  671. if (newSockFd == -1)
  672. {
  673. errno = LinuxError.EBADF;
  674. }
  675. }
  676. return WriteBsdResult(context, newSockFd, errno);
  677. }
  678. [CommandHipc(31)] // 7.0.0+
  679. // EventFd(u64 initval, nn::socket::EventFdFlags flags) -> (i32 ret, u32 bsd_errno)
  680. public ResultCode EventFd(ServiceCtx context)
  681. {
  682. ulong initialValue = context.RequestData.ReadUInt64();
  683. EventFdFlags flags = (EventFdFlags)context.RequestData.ReadUInt32();
  684. EventFileDescriptor newEventFile = new EventFileDescriptor(initialValue, flags);
  685. LinuxError errno = LinuxError.SUCCESS;
  686. int newSockFd = _context.RegisterFileDescriptor(newEventFile);
  687. if (newSockFd == -1)
  688. {
  689. errno = LinuxError.EBADF;
  690. }
  691. return WriteBsdResult(context, newSockFd, errno);
  692. }
  693. }
  694. }