IClient.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  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. // In case of non blocking call timeout should not be returned.
  272. if (timeout == 0 && errno == LinuxError.ETIMEDOUT)
  273. {
  274. errno = LinuxError.SUCCESS;
  275. }
  276. return WriteBsdResult(context, updateCount, errno);
  277. }
  278. [CommandHipc(7)]
  279. // Sysctl(buffer<unknown, 0x21, 0>, buffer<unknown, 0x21, 0>) -> (i32 ret, u32 bsd_errno, u32, buffer<unknown, 0x22, 0>)
  280. public ResultCode Sysctl(ServiceCtx context)
  281. {
  282. WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP);
  283. Logger.Stub?.PrintStub(LogClass.ServiceBsd);
  284. return ResultCode.Success;
  285. }
  286. [CommandHipc(8)]
  287. // Recv(u32 socket, u32 flags) -> (i32 ret, u32 bsd_errno, array<i8, 0x22> message)
  288. public ResultCode Recv(ServiceCtx context)
  289. {
  290. int socketFd = context.RequestData.ReadInt32();
  291. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  292. (ulong receivePosition, ulong receiveLength) = context.Request.GetBufferType0x22();
  293. WritableRegion receiveRegion = context.Memory.GetWritableRegion(receivePosition, (int)receiveLength);
  294. LinuxError errno = LinuxError.EBADF;
  295. ISocket socket = _context.RetrieveSocket(socketFd);
  296. int result = -1;
  297. if (socket != null)
  298. {
  299. errno = socket.Receive(out result, receiveRegion.Memory.Span, socketFlags);
  300. if (errno == LinuxError.SUCCESS)
  301. {
  302. SetResultErrno(socket, result);
  303. receiveRegion.Dispose();
  304. }
  305. }
  306. return WriteBsdResult(context, result, errno);
  307. }
  308. [CommandHipc(9)]
  309. // RecvFrom(u32 sock, u32 flags) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<i8, 0x22, 0> message, buffer<nn::socket::sockaddr_in, 0x22, 0x10>)
  310. public ResultCode RecvFrom(ServiceCtx context)
  311. {
  312. int socketFd = context.RequestData.ReadInt32();
  313. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  314. (ulong receivePosition, ulong receiveLength) = context.Request.GetBufferType0x22(0);
  315. (ulong sockAddrOutPosition, ulong sockAddrOutSize) = context.Request.GetBufferType0x22(1);
  316. WritableRegion receiveRegion = context.Memory.GetWritableRegion(receivePosition, (int)receiveLength);
  317. LinuxError errno = LinuxError.EBADF;
  318. ISocket socket = _context.RetrieveSocket(socketFd);
  319. int result = -1;
  320. if (socket != null)
  321. {
  322. errno = socket.ReceiveFrom(out result, receiveRegion.Memory.Span, receiveRegion.Memory.Span.Length, socketFlags, out IPEndPoint endPoint);
  323. if (errno == LinuxError.SUCCESS)
  324. {
  325. SetResultErrno(socket, result);
  326. receiveRegion.Dispose();
  327. context.Memory.Write(sockAddrOutPosition, BsdSockAddr.FromIPEndPoint(endPoint));
  328. }
  329. }
  330. return WriteBsdResult(context, result, errno);
  331. }
  332. [CommandHipc(10)]
  333. // Send(u32 socket, u32 flags, buffer<i8, 0x21, 0>) -> (i32 ret, u32 bsd_errno)
  334. public ResultCode Send(ServiceCtx context)
  335. {
  336. int socketFd = context.RequestData.ReadInt32();
  337. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  338. (ulong sendPosition, ulong sendSize) = context.Request.GetBufferType0x21();
  339. ReadOnlySpan<byte> sendBuffer = context.Memory.GetSpan(sendPosition, (int)sendSize);
  340. LinuxError errno = LinuxError.EBADF;
  341. ISocket socket = _context.RetrieveSocket(socketFd);
  342. int result = -1;
  343. if (socket != null)
  344. {
  345. errno = socket.Send(out result, sendBuffer, socketFlags);
  346. if (errno == LinuxError.SUCCESS)
  347. {
  348. SetResultErrno(socket, result);
  349. }
  350. }
  351. return WriteBsdResult(context, result, errno);
  352. }
  353. [CommandHipc(11)]
  354. // SendTo(u32 socket, u32 flags, buffer<i8, 0x21, 0>, buffer<nn::socket::sockaddr_in, 0x21, 0x10>) -> (i32 ret, u32 bsd_errno)
  355. public ResultCode SendTo(ServiceCtx context)
  356. {
  357. int socketFd = context.RequestData.ReadInt32();
  358. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  359. (ulong sendPosition, ulong sendSize) = context.Request.GetBufferType0x21(0);
  360. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x21(1);
  361. ReadOnlySpan<byte> sendBuffer = context.Memory.GetSpan(sendPosition, (int)sendSize);
  362. LinuxError errno = LinuxError.EBADF;
  363. ISocket socket = _context.RetrieveSocket(socketFd);
  364. int result = -1;
  365. if (socket != null)
  366. {
  367. IPEndPoint endPoint = context.Memory.Read<BsdSockAddr>(bufferPosition).ToIPEndPoint();
  368. errno = socket.SendTo(out result, sendBuffer, sendBuffer.Length, socketFlags, endPoint);
  369. if (errno == LinuxError.SUCCESS)
  370. {
  371. SetResultErrno(socket, result);
  372. }
  373. }
  374. return WriteBsdResult(context, result, errno);
  375. }
  376. [CommandHipc(12)]
  377. // Accept(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<nn::socket::sockaddr_in, 0x22, 0x10> addr)
  378. public ResultCode Accept(ServiceCtx context)
  379. {
  380. int socketFd = context.RequestData.ReadInt32();
  381. (ulong bufferPos, ulong bufferSize) = context.Request.GetBufferType0x22();
  382. LinuxError errno = LinuxError.EBADF;
  383. ISocket socket = _context.RetrieveSocket(socketFd);
  384. if (socket != null)
  385. {
  386. errno = socket.Accept(out ISocket newSocket);
  387. if (newSocket == null && errno == LinuxError.SUCCESS)
  388. {
  389. errno = LinuxError.EWOULDBLOCK;
  390. }
  391. else if (errno == LinuxError.SUCCESS)
  392. {
  393. int newSockFd = _context.RegisterFileDescriptor(newSocket);
  394. if (newSockFd == -1)
  395. {
  396. errno = LinuxError.EBADF;
  397. }
  398. else
  399. {
  400. WriteSockAddr(context, bufferPos, newSocket, true);
  401. }
  402. WriteBsdResult(context, newSockFd, errno);
  403. context.ResponseData.Write(0x10);
  404. return ResultCode.Success;
  405. }
  406. }
  407. return WriteBsdResult(context, -1, errno);
  408. }
  409. [CommandHipc(13)]
  410. // Bind(u32 socket, buffer<nn::socket::sockaddr_in, 0x21, 0x10> addr) -> (i32 ret, u32 bsd_errno)
  411. public ResultCode Bind(ServiceCtx context)
  412. {
  413. int socketFd = context.RequestData.ReadInt32();
  414. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x21();
  415. LinuxError errno = LinuxError.EBADF;
  416. ISocket socket = _context.RetrieveSocket(socketFd);
  417. if (socket != null)
  418. {
  419. IPEndPoint endPoint = context.Memory.Read<BsdSockAddr>(bufferPosition).ToIPEndPoint();
  420. errno = socket.Bind(endPoint);
  421. }
  422. return WriteBsdResult(context, 0, errno);
  423. }
  424. [CommandHipc(14)]
  425. // Connect(u32 socket, buffer<nn::socket::sockaddr_in, 0x21, 0x10>) -> (i32 ret, u32 bsd_errno)
  426. public ResultCode Connect(ServiceCtx context)
  427. {
  428. int socketFd = context.RequestData.ReadInt32();
  429. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x21();
  430. LinuxError errno = LinuxError.EBADF;
  431. ISocket socket = _context.RetrieveSocket(socketFd);
  432. if (socket != null)
  433. {
  434. IPEndPoint endPoint = context.Memory.Read<BsdSockAddr>(bufferPosition).ToIPEndPoint();
  435. errno = socket.Connect(endPoint);
  436. }
  437. return WriteBsdResult(context, 0, errno);
  438. }
  439. [CommandHipc(15)]
  440. // GetPeerName(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<nn::socket::sockaddr_in, 0x22, 0x10> addr)
  441. public ResultCode GetPeerName(ServiceCtx context)
  442. {
  443. int socketFd = context.RequestData.ReadInt32();
  444. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x22();
  445. LinuxError errno = LinuxError.EBADF;
  446. ISocket socket = _context.RetrieveSocket(socketFd);
  447. if (socket != null)
  448. {
  449. errno = LinuxError.ENOTCONN;
  450. if (socket.RemoteEndPoint != null)
  451. {
  452. errno = LinuxError.SUCCESS;
  453. WriteSockAddr(context, bufferPosition, socket, true);
  454. WriteBsdResult(context, 0, errno);
  455. context.ResponseData.Write(Unsafe.SizeOf<BsdSockAddr>());
  456. }
  457. }
  458. return WriteBsdResult(context, 0, errno);
  459. }
  460. [CommandHipc(16)]
  461. // GetSockName(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<nn::socket::sockaddr_in, 0x22, 0x10> addr)
  462. public ResultCode GetSockName(ServiceCtx context)
  463. {
  464. int socketFd = context.RequestData.ReadInt32();
  465. (ulong bufferPos, ulong bufferSize) = context.Request.GetBufferType0x22();
  466. LinuxError errno = LinuxError.EBADF;
  467. ISocket socket = _context.RetrieveSocket(socketFd);
  468. if (socket != null)
  469. {
  470. errno = LinuxError.SUCCESS;
  471. WriteSockAddr(context, bufferPos, socket, false);
  472. WriteBsdResult(context, 0, errno);
  473. context.ResponseData.Write(Unsafe.SizeOf<BsdSockAddr>());
  474. }
  475. return WriteBsdResult(context, 0, errno);
  476. }
  477. [CommandHipc(17)]
  478. // GetSockOpt(u32 socket, u32 level, u32 option_name) -> (i32 ret, u32 bsd_errno, u32, buffer<unknown, 0x22, 0>)
  479. public ResultCode GetSockOpt(ServiceCtx context)
  480. {
  481. int socketFd = context.RequestData.ReadInt32();
  482. SocketOptionLevel level = (SocketOptionLevel)context.RequestData.ReadInt32();
  483. BsdSocketOption option = (BsdSocketOption)context.RequestData.ReadInt32();
  484. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x22();
  485. WritableRegion optionValue = context.Memory.GetWritableRegion(bufferPosition, (int)bufferSize);
  486. LinuxError errno = LinuxError.EBADF;
  487. ISocket socket = _context.RetrieveSocket(socketFd);
  488. if (socket != null)
  489. {
  490. errno = socket.GetSocketOption(option, level, optionValue.Memory.Span);
  491. if (errno == LinuxError.SUCCESS)
  492. {
  493. optionValue.Dispose();
  494. }
  495. }
  496. return WriteBsdResult(context, 0, errno);
  497. }
  498. [CommandHipc(18)]
  499. // Listen(u32 socket, u32 backlog) -> (i32 ret, u32 bsd_errno)
  500. public ResultCode Listen(ServiceCtx context)
  501. {
  502. int socketFd = context.RequestData.ReadInt32();
  503. int backlog = context.RequestData.ReadInt32();
  504. LinuxError errno = LinuxError.EBADF;
  505. ISocket socket = _context.RetrieveSocket(socketFd);
  506. if (socket != null)
  507. {
  508. errno = socket.Listen(backlog);
  509. }
  510. return WriteBsdResult(context, 0, errno);
  511. }
  512. [CommandHipc(19)]
  513. // 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>)
  514. public ResultCode Ioctl(ServiceCtx context)
  515. {
  516. int socketFd = context.RequestData.ReadInt32();
  517. BsdIoctl cmd = (BsdIoctl)context.RequestData.ReadInt32();
  518. int bufferCount = context.RequestData.ReadInt32();
  519. LinuxError errno = LinuxError.EBADF;
  520. ISocket socket = _context.RetrieveSocket(socketFd);
  521. if (socket != null)
  522. {
  523. switch (cmd)
  524. {
  525. case BsdIoctl.AtMark:
  526. errno = LinuxError.SUCCESS;
  527. (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x22();
  528. // FIXME: OOB not implemented.
  529. context.Memory.Write(bufferPosition, 0);
  530. break;
  531. default:
  532. errno = LinuxError.EOPNOTSUPP;
  533. Logger.Warning?.Print(LogClass.ServiceBsd, $"Unsupported Ioctl Cmd: {cmd}");
  534. break;
  535. }
  536. }
  537. return WriteBsdResult(context, 0, errno);
  538. }
  539. [CommandHipc(20)]
  540. // Fcntl(u32 socket, u32 cmd, u32 arg) -> (i32 ret, u32 bsd_errno)
  541. public ResultCode Fcntl(ServiceCtx context)
  542. {
  543. int socketFd = context.RequestData.ReadInt32();
  544. int cmd = context.RequestData.ReadInt32();
  545. int arg = context.RequestData.ReadInt32();
  546. int result = 0;
  547. LinuxError errno = LinuxError.EBADF;
  548. ISocket socket = _context.RetrieveSocket(socketFd);
  549. if (socket != null)
  550. {
  551. errno = LinuxError.SUCCESS;
  552. if (cmd == 0x3)
  553. {
  554. result = !socket.Blocking ? 0x800 : 0;
  555. }
  556. else if (cmd == 0x4 && arg == 0x800)
  557. {
  558. socket.Blocking = false;
  559. result = 0;
  560. }
  561. else
  562. {
  563. errno = LinuxError.EOPNOTSUPP;
  564. }
  565. }
  566. return WriteBsdResult(context, result, errno);
  567. }
  568. [CommandHipc(21)]
  569. // SetSockOpt(u32 socket, u32 level, u32 option_name, buffer<unknown, 0x21, 0> option_value) -> (i32 ret, u32 bsd_errno)
  570. public ResultCode SetSockOpt(ServiceCtx context)
  571. {
  572. int socketFd = context.RequestData.ReadInt32();
  573. SocketOptionLevel level = (SocketOptionLevel)context.RequestData.ReadInt32();
  574. BsdSocketOption option = (BsdSocketOption)context.RequestData.ReadInt32();
  575. (ulong bufferPos, ulong bufferSize) = context.Request.GetBufferType0x21();
  576. ReadOnlySpan<byte> optionValue = context.Memory.GetSpan(bufferPos, (int)bufferSize);
  577. LinuxError errno = LinuxError.EBADF;
  578. ISocket socket = _context.RetrieveSocket(socketFd);
  579. if (socket != null)
  580. {
  581. errno = socket.SetSocketOption(option, level, optionValue);
  582. }
  583. return WriteBsdResult(context, 0, errno);
  584. }
  585. [CommandHipc(22)]
  586. // Shutdown(u32 socket, u32 how) -> (i32 ret, u32 bsd_errno)
  587. public ResultCode Shutdown(ServiceCtx context)
  588. {
  589. int socketFd = context.RequestData.ReadInt32();
  590. int how = context.RequestData.ReadInt32();
  591. LinuxError errno = LinuxError.EBADF;
  592. ISocket socket = _context.RetrieveSocket(socketFd);
  593. if (socket != null)
  594. {
  595. errno = LinuxError.EINVAL;
  596. if (how >= 0 && how <= 2)
  597. {
  598. errno = socket.Shutdown((BsdSocketShutdownFlags)how);
  599. }
  600. }
  601. return WriteBsdResult(context, 0, errno);
  602. }
  603. [CommandHipc(23)]
  604. // ShutdownAllSockets(u32 how) -> (i32 ret, u32 bsd_errno)
  605. public ResultCode ShutdownAllSockets(ServiceCtx context)
  606. {
  607. int how = context.RequestData.ReadInt32();
  608. LinuxError errno = LinuxError.EINVAL;
  609. if (how >= 0 && how <= 2)
  610. {
  611. errno = _context.ShutdownAllSockets((BsdSocketShutdownFlags)how);
  612. }
  613. return WriteBsdResult(context, 0, errno);
  614. }
  615. [CommandHipc(24)]
  616. // Write(u32 fd, buffer<i8, 0x21, 0> message) -> (i32 ret, u32 bsd_errno)
  617. public ResultCode Write(ServiceCtx context)
  618. {
  619. int fd = context.RequestData.ReadInt32();
  620. (ulong sendPosition, ulong sendSize) = context.Request.GetBufferType0x21();
  621. ReadOnlySpan<byte> sendBuffer = context.Memory.GetSpan(sendPosition, (int)sendSize);
  622. LinuxError errno = LinuxError.EBADF;
  623. IFileDescriptor file = _context.RetrieveFileDescriptor(fd);
  624. int result = -1;
  625. if (file != null)
  626. {
  627. errno = file.Write(out result, sendBuffer);
  628. if (errno == LinuxError.SUCCESS)
  629. {
  630. SetResultErrno(file, result);
  631. }
  632. }
  633. return WriteBsdResult(context, result, errno);
  634. }
  635. [CommandHipc(25)]
  636. // Read(u32 fd) -> (i32 ret, u32 bsd_errno, buffer<i8, 0x22, 0> message)
  637. public ResultCode Read(ServiceCtx context)
  638. {
  639. int fd = context.RequestData.ReadInt32();
  640. (ulong receivePosition, ulong receiveLength) = context.Request.GetBufferType0x22();
  641. WritableRegion receiveRegion = context.Memory.GetWritableRegion(receivePosition, (int)receiveLength);
  642. LinuxError errno = LinuxError.EBADF;
  643. IFileDescriptor file = _context.RetrieveFileDescriptor(fd);
  644. int result = -1;
  645. if (file != null)
  646. {
  647. errno = file.Read(out result, receiveRegion.Memory.Span);
  648. if (errno == LinuxError.SUCCESS)
  649. {
  650. SetResultErrno(file, result);
  651. receiveRegion.Dispose();
  652. }
  653. }
  654. return WriteBsdResult(context, result, errno);
  655. }
  656. [CommandHipc(26)]
  657. // Close(u32 fd) -> (i32 ret, u32 bsd_errno)
  658. public ResultCode Close(ServiceCtx context)
  659. {
  660. int fd = context.RequestData.ReadInt32();
  661. LinuxError errno = LinuxError.EBADF;
  662. if (_context.CloseFileDescriptor(fd))
  663. {
  664. errno = LinuxError.SUCCESS;
  665. }
  666. return WriteBsdResult(context, 0, errno);
  667. }
  668. [CommandHipc(27)]
  669. // DuplicateSocket(u32 fd, u64 reserved) -> (i32 ret, u32 bsd_errno)
  670. public ResultCode DuplicateSocket(ServiceCtx context)
  671. {
  672. int fd = context.RequestData.ReadInt32();
  673. ulong reserved = context.RequestData.ReadUInt64();
  674. LinuxError errno = LinuxError.ENOENT;
  675. int newSockFd = -1;
  676. if (_isPrivileged)
  677. {
  678. errno = LinuxError.SUCCESS;
  679. newSockFd = _context.DuplicateFileDescriptor(fd);
  680. if (newSockFd == -1)
  681. {
  682. errno = LinuxError.EBADF;
  683. }
  684. }
  685. return WriteBsdResult(context, newSockFd, errno);
  686. }
  687. [CommandHipc(29)] // 7.0.0+
  688. // RecvMMsg(u32 fd, u32 vlen, u32 flags, u32 reserved, nn::socket::TimeVal timeout) -> (i32 ret, u32 bsd_errno, buffer<bytes, 6> message);
  689. public ResultCode RecvMMsg(ServiceCtx context)
  690. {
  691. int socketFd = context.RequestData.ReadInt32();
  692. int vlen = context.RequestData.ReadInt32();
  693. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  694. uint reserved = context.RequestData.ReadUInt32();
  695. TimeVal timeout = context.RequestData.ReadStruct<TimeVal>();
  696. ulong receivePosition = context.Request.ReceiveBuff[0].Position;
  697. ulong receiveLength = context.Request.ReceiveBuff[0].Size;
  698. WritableRegion receiveRegion = context.Memory.GetWritableRegion(receivePosition, (int)receiveLength);
  699. LinuxError errno = LinuxError.EBADF;
  700. ISocket socket = _context.RetrieveSocket(socketFd);
  701. int result = -1;
  702. if (socket != null)
  703. {
  704. errno = BsdMMsgHdr.Deserialize(out BsdMMsgHdr message, receiveRegion.Memory.Span, vlen);
  705. if (errno == LinuxError.SUCCESS)
  706. {
  707. errno = socket.RecvMMsg(out result, message, socketFlags, timeout);
  708. if (errno == LinuxError.SUCCESS)
  709. {
  710. errno = BsdMMsgHdr.Serialize(receiveRegion.Memory.Span, message);
  711. }
  712. }
  713. }
  714. if (errno == LinuxError.SUCCESS)
  715. {
  716. SetResultErrno(socket, result);
  717. receiveRegion.Dispose();
  718. }
  719. return WriteBsdResult(context, result, errno);
  720. }
  721. [CommandHipc(30)] // 7.0.0+
  722. // SendMMsg(u32 fd, u32 vlen, u32 flags) -> (i32 ret, u32 bsd_errno, buffer<bytes, 6> message);
  723. public ResultCode SendMMsg(ServiceCtx context)
  724. {
  725. int socketFd = context.RequestData.ReadInt32();
  726. int vlen = context.RequestData.ReadInt32();
  727. BsdSocketFlags socketFlags = (BsdSocketFlags)context.RequestData.ReadInt32();
  728. ulong receivePosition = context.Request.ReceiveBuff[0].Position;
  729. ulong receiveLength = context.Request.ReceiveBuff[0].Size;
  730. WritableRegion receiveRegion = context.Memory.GetWritableRegion(receivePosition, (int)receiveLength);
  731. LinuxError errno = LinuxError.EBADF;
  732. ISocket socket = _context.RetrieveSocket(socketFd);
  733. int result = -1;
  734. if (socket != null)
  735. {
  736. errno = BsdMMsgHdr.Deserialize(out BsdMMsgHdr message, receiveRegion.Memory.Span, vlen);
  737. if (errno == LinuxError.SUCCESS)
  738. {
  739. errno = socket.SendMMsg(out result, message, socketFlags);
  740. if (errno == LinuxError.SUCCESS)
  741. {
  742. errno = BsdMMsgHdr.Serialize(receiveRegion.Memory.Span, message);
  743. }
  744. }
  745. }
  746. if (errno == LinuxError.SUCCESS)
  747. {
  748. SetResultErrno(socket, result);
  749. receiveRegion.Dispose();
  750. }
  751. return WriteBsdResult(context, result, errno);
  752. }
  753. [CommandHipc(31)] // 7.0.0+
  754. // EventFd(u64 initval, nn::socket::EventFdFlags flags) -> (i32 ret, u32 bsd_errno)
  755. public ResultCode EventFd(ServiceCtx context)
  756. {
  757. ulong initialValue = context.RequestData.ReadUInt64();
  758. EventFdFlags flags = (EventFdFlags)context.RequestData.ReadUInt32();
  759. EventFileDescriptor newEventFile = new EventFileDescriptor(initialValue, flags);
  760. LinuxError errno = LinuxError.SUCCESS;
  761. int newSockFd = _context.RegisterFileDescriptor(newEventFile);
  762. if (newSockFd == -1)
  763. {
  764. errno = LinuxError.EBADF;
  765. }
  766. return WriteBsdResult(context, newSockFd, errno);
  767. }
  768. }
  769. }