IClient.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. using Ryujinx.Common;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.HLE.Utilities;
  4. using System.Buffers.Binary;
  5. using System.Collections.Generic;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Text;
  9. namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
  10. {
  11. [Service("bsd:s", true)]
  12. [Service("bsd:u", false)]
  13. class IClient : IpcService
  14. {
  15. private static Dictionary<WsaError, LinuxError> _errorMap = new Dictionary<WsaError, LinuxError>
  16. {
  17. // WSAEINTR
  18. {WsaError.WSAEINTR, LinuxError.EINTR},
  19. // WSAEWOULDBLOCK
  20. {WsaError.WSAEWOULDBLOCK, LinuxError.EWOULDBLOCK},
  21. // WSAEINPROGRESS
  22. {WsaError.WSAEINPROGRESS, LinuxError.EINPROGRESS},
  23. // WSAEALREADY
  24. {WsaError.WSAEALREADY, LinuxError.EALREADY},
  25. // WSAENOTSOCK
  26. {WsaError.WSAENOTSOCK, LinuxError.ENOTSOCK},
  27. // WSAEDESTADDRREQ
  28. {WsaError.WSAEDESTADDRREQ, LinuxError.EDESTADDRREQ},
  29. // WSAEMSGSIZE
  30. {WsaError.WSAEMSGSIZE, LinuxError.EMSGSIZE},
  31. // WSAEPROTOTYPE
  32. {WsaError.WSAEPROTOTYPE, LinuxError.EPROTOTYPE},
  33. // WSAENOPROTOOPT
  34. {WsaError.WSAENOPROTOOPT, LinuxError.ENOPROTOOPT},
  35. // WSAEPROTONOSUPPORT
  36. {WsaError.WSAEPROTONOSUPPORT, LinuxError.EPROTONOSUPPORT},
  37. // WSAESOCKTNOSUPPORT
  38. {WsaError.WSAESOCKTNOSUPPORT, LinuxError.ESOCKTNOSUPPORT},
  39. // WSAEOPNOTSUPP
  40. {WsaError.WSAEOPNOTSUPP, LinuxError.EOPNOTSUPP},
  41. // WSAEPFNOSUPPORT
  42. {WsaError.WSAEPFNOSUPPORT, LinuxError.EPFNOSUPPORT},
  43. // WSAEAFNOSUPPORT
  44. {WsaError.WSAEAFNOSUPPORT, LinuxError.EAFNOSUPPORT},
  45. // WSAEADDRINUSE
  46. {WsaError.WSAEADDRINUSE, LinuxError.EADDRINUSE},
  47. // WSAEADDRNOTAVAIL
  48. {WsaError.WSAEADDRNOTAVAIL, LinuxError.EADDRNOTAVAIL},
  49. // WSAENETDOWN
  50. {WsaError.WSAENETDOWN, LinuxError.ENETDOWN},
  51. // WSAENETUNREACH
  52. {WsaError.WSAENETUNREACH, LinuxError.ENETUNREACH},
  53. // WSAENETRESET
  54. {WsaError.WSAENETRESET, LinuxError.ENETRESET},
  55. // WSAECONNABORTED
  56. {WsaError.WSAECONNABORTED, LinuxError.ECONNABORTED},
  57. // WSAECONNRESET
  58. {WsaError.WSAECONNRESET, LinuxError.ECONNRESET},
  59. // WSAENOBUFS
  60. {WsaError.WSAENOBUFS, LinuxError.ENOBUFS},
  61. // WSAEISCONN
  62. {WsaError.WSAEISCONN, LinuxError.EISCONN},
  63. // WSAENOTCONN
  64. {WsaError.WSAENOTCONN, LinuxError.ENOTCONN},
  65. // WSAESHUTDOWN
  66. {WsaError.WSAESHUTDOWN, LinuxError.ESHUTDOWN},
  67. // WSAETOOMANYREFS
  68. {WsaError.WSAETOOMANYREFS, LinuxError.ETOOMANYREFS},
  69. // WSAETIMEDOUT
  70. {WsaError.WSAETIMEDOUT, LinuxError.ETIMEDOUT},
  71. // WSAECONNREFUSED
  72. {WsaError.WSAECONNREFUSED, LinuxError.ECONNREFUSED},
  73. // WSAELOOP
  74. {WsaError.WSAELOOP, LinuxError.ELOOP},
  75. // WSAENAMETOOLONG
  76. {WsaError.WSAENAMETOOLONG, LinuxError.ENAMETOOLONG},
  77. // WSAEHOSTDOWN
  78. {WsaError.WSAEHOSTDOWN, LinuxError.EHOSTDOWN},
  79. // WSAEHOSTUNREACH
  80. {WsaError.WSAEHOSTUNREACH, LinuxError.EHOSTUNREACH},
  81. // WSAENOTEMPTY
  82. {WsaError.WSAENOTEMPTY, LinuxError.ENOTEMPTY},
  83. // WSAEUSERS
  84. {WsaError.WSAEUSERS, LinuxError.EUSERS},
  85. // WSAEDQUOT
  86. {WsaError.WSAEDQUOT, LinuxError.EDQUOT},
  87. // WSAESTALE
  88. {WsaError.WSAESTALE, LinuxError.ESTALE},
  89. // WSAEREMOTE
  90. {WsaError.WSAEREMOTE, LinuxError.EREMOTE},
  91. // WSAEINVAL
  92. {WsaError.WSAEINVAL, LinuxError.EINVAL},
  93. // WSAEFAULT
  94. {WsaError.WSAEFAULT, LinuxError.EFAULT},
  95. // NOERROR
  96. {0, 0}
  97. };
  98. private bool _isPrivileged;
  99. private List<BsdSocket> _sockets = new List<BsdSocket>();
  100. public IClient(ServiceCtx context, bool isPrivileged)
  101. {
  102. _isPrivileged = isPrivileged;
  103. }
  104. private LinuxError ConvertError(WsaError errorCode)
  105. {
  106. if (!_errorMap.TryGetValue(errorCode, out LinuxError errno))
  107. {
  108. errno = (LinuxError)errorCode;
  109. }
  110. return errno;
  111. }
  112. private ResultCode WriteWinSock2Error(ServiceCtx context, WsaError errorCode)
  113. {
  114. return WriteBsdResult(context, -1, ConvertError(errorCode));
  115. }
  116. private ResultCode WriteBsdResult(ServiceCtx context, int result, LinuxError errorCode = 0)
  117. {
  118. if (errorCode != LinuxError.SUCCESS)
  119. {
  120. result = -1;
  121. }
  122. context.ResponseData.Write(result);
  123. context.ResponseData.Write((int)errorCode);
  124. return ResultCode.Success;
  125. }
  126. private BsdSocket RetrieveSocket(int socketFd)
  127. {
  128. if (socketFd >= 0 && _sockets.Count > socketFd)
  129. {
  130. return _sockets[socketFd];
  131. }
  132. return null;
  133. }
  134. private LinuxError SetResultErrno(Socket socket, int result)
  135. {
  136. return result == 0 && !socket.Blocking ? LinuxError.EWOULDBLOCK : LinuxError.SUCCESS;
  137. }
  138. private AddressFamily ConvertFromBsd(int domain)
  139. {
  140. if (domain == 2)
  141. {
  142. return AddressFamily.InterNetwork;
  143. }
  144. // FIXME: AF_ROUTE ignored, is that really needed?
  145. return AddressFamily.Unknown;
  146. }
  147. private ResultCode SocketInternal(ServiceCtx context, bool exempt)
  148. {
  149. AddressFamily domain = (AddressFamily)context.RequestData.ReadInt32();
  150. SocketType type = (SocketType)context.RequestData.ReadInt32();
  151. ProtocolType protocol = (ProtocolType)context.RequestData.ReadInt32();
  152. if (domain == AddressFamily.Unknown)
  153. {
  154. return WriteBsdResult(context, -1, LinuxError.EPROTONOSUPPORT);
  155. }
  156. else if ((type == SocketType.Seqpacket || type == SocketType.Raw) && !_isPrivileged)
  157. {
  158. if (domain != AddressFamily.InterNetwork || type != SocketType.Raw || protocol != ProtocolType.Icmp)
  159. {
  160. return WriteBsdResult(context, -1, LinuxError.ENOENT);
  161. }
  162. }
  163. BsdSocket newBsdSocket = new BsdSocket
  164. {
  165. Family = (int)domain,
  166. Type = (int)type,
  167. Protocol = (int)protocol,
  168. Handle = new Socket(domain, type, protocol)
  169. };
  170. _sockets.Add(newBsdSocket);
  171. if (exempt)
  172. {
  173. newBsdSocket.Handle.Disconnect(true);
  174. }
  175. return WriteBsdResult(context, _sockets.Count - 1);
  176. }
  177. private IPEndPoint ParseSockAddr(ServiceCtx context, long bufferPosition, long bufferSize)
  178. {
  179. int size = context.Memory.ReadByte(bufferPosition);
  180. int family = context.Memory.ReadByte(bufferPosition + 1);
  181. int port = BinaryPrimitives.ReverseEndianness(context.Memory.ReadUInt16(bufferPosition + 2));
  182. byte[] rawIp = context.Memory.ReadBytes(bufferPosition + 4, 4);
  183. return new IPEndPoint(new IPAddress(rawIp), port);
  184. }
  185. private void WriteSockAddr(ServiceCtx context, long bufferPosition, IPEndPoint endPoint)
  186. {
  187. context.Memory.WriteByte(bufferPosition, 0);
  188. context.Memory.WriteByte(bufferPosition + 1, (byte)endPoint.AddressFamily);
  189. context.Memory.WriteUInt16(bufferPosition + 2, BinaryPrimitives.ReverseEndianness((ushort)endPoint.Port));
  190. context.Memory.WriteBytes(bufferPosition + 4, endPoint.Address.GetAddressBytes());
  191. }
  192. private void WriteSockAddr(ServiceCtx context, long bufferPosition, BsdSocket socket, bool isRemote)
  193. {
  194. IPEndPoint endPoint = (isRemote ? socket.Handle.RemoteEndPoint : socket.Handle.LocalEndPoint) as IPEndPoint;
  195. WriteSockAddr(context, bufferPosition, endPoint);
  196. }
  197. [Command(0)]
  198. // Initialize(nn::socket::BsdBufferConfig config, u64 pid, u64 transferMemorySize, KObject<copy, transfer_memory>, pid) -> u32 bsd_errno
  199. public ResultCode RegisterClient(ServiceCtx context)
  200. {
  201. /*
  202. typedef struct {
  203. u32 version; // Observed 1 on 2.0 LibAppletWeb, 2 on 3.0.
  204. u32 tcp_tx_buf_size; // Size of the TCP transfer (send) buffer (initial or fixed).
  205. u32 tcp_rx_buf_size; // Size of the TCP recieve buffer (initial or fixed).
  206. 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.
  207. 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.
  208. u32 udp_tx_buf_size; // Size of the UDP transfer (send) buffer (typically 0x2400 bytes).
  209. u32 udp_rx_buf_size; // Size of the UDP receive buffer (typically 0xA500 bytes).
  210. u32 sb_efficiency; // Number of buffers for each socket (standard values range from 1 to 8).
  211. } BsdBufferConfig;
  212. */
  213. // bsd_error
  214. context.ResponseData.Write(0);
  215. Logger.PrintStub(LogClass.ServiceBsd);
  216. return ResultCode.Success;
  217. }
  218. [Command(1)]
  219. // StartMonitoring(u64, pid)
  220. public ResultCode StartMonitoring(ServiceCtx context)
  221. {
  222. ulong unknown0 = context.RequestData.ReadUInt64();
  223. Logger.PrintStub(LogClass.ServiceBsd, new { unknown0 });
  224. return ResultCode.Success;
  225. }
  226. [Command(2)]
  227. // Socket(u32 domain, u32 type, u32 protocol) -> (i32 ret, u32 bsd_errno)
  228. public ResultCode Socket(ServiceCtx context)
  229. {
  230. return SocketInternal(context, false);
  231. }
  232. [Command(3)]
  233. // SocketExempt(u32 domain, u32 type, u32 protocol) -> (i32 ret, u32 bsd_errno)
  234. public ResultCode SocketExempt(ServiceCtx context)
  235. {
  236. return SocketInternal(context, true);
  237. }
  238. [Command(4)]
  239. // Open(u32 flags, array<unknown, 0x21> path) -> (i32 ret, u32 bsd_errno)
  240. public ResultCode Open(ServiceCtx context)
  241. {
  242. (long bufferPosition, long bufferSize) = context.Request.GetBufferType0x21();
  243. int flags = context.RequestData.ReadInt32();
  244. byte[] rawPath = context.Memory.ReadBytes(bufferPosition, bufferSize);
  245. string path = Encoding.ASCII.GetString(rawPath);
  246. WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP);
  247. Logger.PrintStub(LogClass.ServiceBsd, new { path, flags });
  248. return ResultCode.Success;
  249. }
  250. [Command(5)]
  251. // 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)
  252. public ResultCode Select(ServiceCtx context)
  253. {
  254. WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP);
  255. Logger.PrintStub(LogClass.ServiceBsd);
  256. return ResultCode.Success;
  257. }
  258. [Command(6)]
  259. // Poll(u32 nfds, u32 timeout, buffer<unknown, 0x21, 0> fds) -> (i32 ret, u32 bsd_errno, buffer<unknown, 0x22, 0>)
  260. public ResultCode Poll(ServiceCtx context)
  261. {
  262. int fdsCount = context.RequestData.ReadInt32();
  263. int timeout = context.RequestData.ReadInt32();
  264. (long bufferPosition, long bufferSize) = context.Request.GetBufferType0x21();
  265. if (timeout < -1 || fdsCount < 0 || (fdsCount * 8) > bufferSize)
  266. {
  267. return WriteBsdResult(context, -1, LinuxError.EINVAL);
  268. }
  269. PollEvent[] events = new PollEvent[fdsCount];
  270. for (int i = 0; i < fdsCount; i++)
  271. {
  272. int socketFd = context.Memory.ReadInt32(bufferPosition + i * 8);
  273. BsdSocket socket = RetrieveSocket(socketFd);
  274. if (socket == null)
  275. {
  276. return WriteBsdResult(context, -1, LinuxError.EBADF);}
  277. PollEvent.EventTypeMask inputEvents = (PollEvent.EventTypeMask)context.Memory.ReadInt16(bufferPosition + i * 8 + 4);
  278. PollEvent.EventTypeMask outputEvents = (PollEvent.EventTypeMask)context.Memory.ReadInt16(bufferPosition + i * 8 + 6);
  279. events[i] = new PollEvent(socketFd, socket, inputEvents, outputEvents);
  280. }
  281. List<Socket> readEvents = new List<Socket>();
  282. List<Socket> writeEvents = new List<Socket>();
  283. List<Socket> errorEvents = new List<Socket>();
  284. foreach (PollEvent Event in events)
  285. {
  286. bool isValidEvent = false;
  287. if ((Event.InputEvents & PollEvent.EventTypeMask.Input) != 0)
  288. {
  289. readEvents.Add(Event.Socket.Handle);
  290. errorEvents.Add(Event.Socket.Handle);
  291. isValidEvent = true;
  292. }
  293. if ((Event.InputEvents & PollEvent.EventTypeMask.UrgentInput) != 0)
  294. {
  295. readEvents.Add(Event.Socket.Handle);
  296. errorEvents.Add(Event.Socket.Handle);
  297. isValidEvent = true;
  298. }
  299. if ((Event.InputEvents & PollEvent.EventTypeMask.Output) != 0)
  300. {
  301. writeEvents.Add(Event.Socket.Handle);
  302. errorEvents.Add(Event.Socket.Handle);
  303. isValidEvent = true;
  304. }
  305. if ((Event.InputEvents & PollEvent.EventTypeMask.Error) != 0)
  306. {
  307. errorEvents.Add(Event.Socket.Handle);
  308. isValidEvent = true;
  309. }
  310. if (!isValidEvent)
  311. {
  312. Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Poll input event type: {Event.InputEvents}");
  313. return WriteBsdResult(context, -1, LinuxError.EINVAL);
  314. }
  315. }
  316. try
  317. {
  318. System.Net.Sockets.Socket.Select(readEvents, writeEvents, errorEvents, timeout);
  319. }
  320. catch (SocketException exception)
  321. {
  322. return WriteWinSock2Error(context, (WsaError)exception.ErrorCode);
  323. }
  324. for (int i = 0; i < fdsCount; i++)
  325. {
  326. PollEvent Event = events[i];
  327. context.Memory.WriteInt32(bufferPosition + i * 8, Event.SocketFd);
  328. context.Memory.WriteInt16(bufferPosition + i * 8 + 4, (short)Event.InputEvents);
  329. PollEvent.EventTypeMask outputEvents = 0;
  330. Socket socket = Event.Socket.Handle;
  331. if (errorEvents.Contains(socket))
  332. {
  333. outputEvents |= PollEvent.EventTypeMask.Error;
  334. if (!socket.Connected || !socket.IsBound)
  335. {
  336. outputEvents |= PollEvent.EventTypeMask.Disconnected;
  337. }
  338. }
  339. if (readEvents.Contains(socket))
  340. {
  341. if ((Event.InputEvents & PollEvent.EventTypeMask.Input) != 0)
  342. {
  343. outputEvents |= PollEvent.EventTypeMask.Input;
  344. }
  345. }
  346. if (writeEvents.Contains(socket))
  347. {
  348. outputEvents |= PollEvent.EventTypeMask.Output;
  349. }
  350. context.Memory.WriteInt16(bufferPosition + i * 8 + 6, (short)outputEvents);
  351. }
  352. return WriteBsdResult(context, readEvents.Count + writeEvents.Count + errorEvents.Count, LinuxError.SUCCESS);
  353. }
  354. [Command(7)]
  355. // Sysctl(buffer<unknown, 0x21, 0>, buffer<unknown, 0x21, 0>) -> (i32 ret, u32 bsd_errno, u32, buffer<unknown, 0x22, 0>)
  356. public ResultCode Sysctl(ServiceCtx context)
  357. {
  358. WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP);
  359. Logger.PrintStub(LogClass.ServiceBsd);
  360. return ResultCode.Success;
  361. }
  362. [Command(8)]
  363. // Recv(u32 socket, u32 flags) -> (i32 ret, u32 bsd_errno, array<i8, 0x22> message)
  364. public ResultCode Recv(ServiceCtx context)
  365. {
  366. int socketFd = context.RequestData.ReadInt32();
  367. SocketFlags socketFlags = (SocketFlags)context.RequestData.ReadInt32();
  368. (long receivePosition, long receiveLength) = context.Request.GetBufferType0x22();
  369. LinuxError errno = LinuxError.EBADF;
  370. BsdSocket socket = RetrieveSocket(socketFd);
  371. int result = -1;
  372. if (socket != null)
  373. {
  374. if (socketFlags != SocketFlags.None && (socketFlags & SocketFlags.OutOfBand) == 0
  375. && (socketFlags & SocketFlags.Peek) == 0)
  376. {
  377. Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Recv flags: {socketFlags}");
  378. return WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP);
  379. }
  380. byte[] receivedBuffer = new byte[receiveLength];
  381. try
  382. {
  383. result = socket.Handle.Receive(receivedBuffer, socketFlags);
  384. errno = SetResultErrno(socket.Handle, result);
  385. context.Memory.WriteBytes(receivePosition, receivedBuffer);
  386. }
  387. catch (SocketException exception)
  388. {
  389. errno = ConvertError((WsaError)exception.ErrorCode);
  390. }
  391. }
  392. return WriteBsdResult(context, result, errno);
  393. }
  394. [Command(9)]
  395. // RecvFrom(u32 sock, u32 flags) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<i8, 0x22, 0> message, buffer<nn::socket::sockaddr_in, 0x22, 0x10>)
  396. public ResultCode RecvFrom(ServiceCtx context)
  397. {
  398. int socketFd = context.RequestData.ReadInt32();
  399. SocketFlags socketFlags = (SocketFlags)context.RequestData.ReadInt32();
  400. (long receivePosition, long receiveLength) = context.Request.GetBufferType0x22();
  401. (long sockAddrOutPosition, long sockAddrOutSize) = context.Request.GetBufferType0x22(1);
  402. LinuxError errno = LinuxError.EBADF;
  403. BsdSocket socket = RetrieveSocket(socketFd);
  404. int result = -1;
  405. if (socket != null)
  406. {
  407. if (socketFlags != SocketFlags.None && (socketFlags & SocketFlags.OutOfBand) == 0
  408. && (socketFlags & SocketFlags.Peek) == 0)
  409. {
  410. Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Recv flags: {socketFlags}");
  411. return WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP);
  412. }
  413. byte[] receivedBuffer = new byte[receiveLength];
  414. EndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
  415. try
  416. {
  417. result = socket.Handle.ReceiveFrom(receivedBuffer, receivedBuffer.Length, socketFlags, ref endPoint);
  418. errno = SetResultErrno(socket.Handle, result);
  419. context.Memory.WriteBytes(receivePosition, receivedBuffer);
  420. WriteSockAddr(context, sockAddrOutPosition, (IPEndPoint)endPoint);
  421. }
  422. catch (SocketException exception)
  423. {
  424. errno = ConvertError((WsaError)exception.ErrorCode);
  425. }
  426. }
  427. return WriteBsdResult(context, result, errno);
  428. }
  429. [Command(10)]
  430. // Send(u32 socket, u32 flags, buffer<i8, 0x21, 0>) -> (i32 ret, u32 bsd_errno)
  431. public ResultCode Send(ServiceCtx context)
  432. {
  433. int socketFd = context.RequestData.ReadInt32();
  434. SocketFlags socketFlags = (SocketFlags)context.RequestData.ReadInt32();
  435. (long sendPosition, long sendSize) = context.Request.GetBufferType0x21();
  436. LinuxError errno = LinuxError.EBADF;
  437. BsdSocket socket = RetrieveSocket(socketFd);
  438. int result = -1;
  439. if (socket != null)
  440. {
  441. if (socketFlags != SocketFlags.None && socketFlags != SocketFlags.OutOfBand
  442. && socketFlags != SocketFlags.Peek && socketFlags != SocketFlags.DontRoute)
  443. {
  444. Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Send flags: {socketFlags}");
  445. return WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP);
  446. }
  447. byte[] sendBuffer = context.Memory.ReadBytes(sendPosition, sendSize);
  448. try
  449. {
  450. result = socket.Handle.Send(sendBuffer, socketFlags);
  451. errno = SetResultErrno(socket.Handle, result);
  452. }
  453. catch (SocketException exception)
  454. {
  455. errno = ConvertError((WsaError)exception.ErrorCode);
  456. }
  457. }
  458. return WriteBsdResult(context, result, errno);
  459. }
  460. [Command(11)]
  461. // SendTo(u32 socket, u32 flags, buffer<i8, 0x21, 0>, buffer<nn::socket::sockaddr_in, 0x21, 0x10>) -> (i32 ret, u32 bsd_errno)
  462. public ResultCode SendTo(ServiceCtx context)
  463. {
  464. int socketFd = context.RequestData.ReadInt32();
  465. SocketFlags socketFlags = (SocketFlags)context.RequestData.ReadInt32();
  466. (long sendPosition, long sendSize) = context.Request.GetBufferType0x21();
  467. (long bufferPosition, long bufferSize) = context.Request.GetBufferType0x21(1);
  468. LinuxError errno = LinuxError.EBADF;
  469. BsdSocket socket = RetrieveSocket(socketFd);
  470. int result = -1;
  471. if (socket != null)
  472. {
  473. if (socketFlags != SocketFlags.None && socketFlags != SocketFlags.OutOfBand
  474. && socketFlags != SocketFlags.Peek && socketFlags != SocketFlags.DontRoute)
  475. {
  476. Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Send flags: {socketFlags}");
  477. return WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP);
  478. }
  479. byte[] sendBuffer = context.Memory.ReadBytes(sendPosition, sendSize);
  480. EndPoint endPoint = ParseSockAddr(context, bufferPosition, bufferSize);
  481. try
  482. {
  483. result = socket.Handle.SendTo(sendBuffer, sendBuffer.Length, socketFlags, endPoint);
  484. errno = SetResultErrno(socket.Handle, result);
  485. }
  486. catch (SocketException exception)
  487. {
  488. errno = ConvertError((WsaError)exception.ErrorCode);
  489. }
  490. }
  491. return WriteBsdResult(context, result, errno);
  492. }
  493. [Command(12)]
  494. // Accept(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<nn::socket::sockaddr_in, 0x22, 0x10> addr)
  495. public ResultCode Accept(ServiceCtx context)
  496. {
  497. int socketFd = context.RequestData.ReadInt32();
  498. (long bufferPos, long bufferSize) = context.Request.GetBufferType0x22();
  499. LinuxError errno = LinuxError.EBADF;
  500. BsdSocket socket = RetrieveSocket(socketFd);
  501. if (socket != null)
  502. {
  503. errno = LinuxError.SUCCESS;
  504. Socket newSocket = null;
  505. try
  506. {
  507. newSocket = socket.Handle.Accept();
  508. }
  509. catch (SocketException exception)
  510. {
  511. errno = ConvertError((WsaError)exception.ErrorCode);
  512. }
  513. if (newSocket == null && errno == LinuxError.SUCCESS)
  514. {
  515. errno = LinuxError.EWOULDBLOCK;
  516. }
  517. else if (errno == LinuxError.SUCCESS)
  518. {
  519. BsdSocket newBsdSocket = new BsdSocket
  520. {
  521. Family = (int)newSocket.AddressFamily,
  522. Type = (int)newSocket.SocketType,
  523. Protocol = (int)newSocket.ProtocolType,
  524. Handle = newSocket
  525. };
  526. _sockets.Add(newBsdSocket);
  527. WriteSockAddr(context, bufferPos, newBsdSocket, true);
  528. WriteBsdResult(context, _sockets.Count - 1, errno);
  529. context.ResponseData.Write(0x10);
  530. return ResultCode.Success;
  531. }
  532. }
  533. return WriteBsdResult(context, -1, errno);
  534. }
  535. [Command(13)]
  536. // Bind(u32 socket, buffer<nn::socket::sockaddr_in, 0x21, 0x10> addr) -> (i32 ret, u32 bsd_errno)
  537. public ResultCode Bind(ServiceCtx context)
  538. {
  539. int socketFd = context.RequestData.ReadInt32();
  540. (long bufferPos, long bufferSize) = context.Request.GetBufferType0x21();
  541. LinuxError errno = LinuxError.EBADF;
  542. BsdSocket socket = RetrieveSocket(socketFd);
  543. if (socket != null)
  544. {
  545. errno = LinuxError.SUCCESS;
  546. try
  547. {
  548. IPEndPoint endPoint = ParseSockAddr(context, bufferPos, bufferSize);
  549. socket.Handle.Bind(endPoint);
  550. }
  551. catch (SocketException exception)
  552. {
  553. errno = ConvertError((WsaError)exception.ErrorCode);
  554. }
  555. }
  556. return WriteBsdResult(context, 0, errno);
  557. }
  558. [Command(14)]
  559. // Connect(u32 socket, buffer<nn::socket::sockaddr_in, 0x21, 0x10>) -> (i32 ret, u32 bsd_errno)
  560. public ResultCode Connect(ServiceCtx context)
  561. {
  562. int socketFd = context.RequestData.ReadInt32();
  563. (long bufferPos, long bufferSize) = context.Request.GetBufferType0x21();
  564. LinuxError errno = LinuxError.EBADF;
  565. BsdSocket socket = RetrieveSocket(socketFd);
  566. if (socket != null)
  567. {
  568. errno = LinuxError.SUCCESS;
  569. try
  570. {
  571. IPEndPoint endPoint = ParseSockAddr(context, bufferPos, bufferSize);
  572. socket.Handle.Connect(endPoint);
  573. }
  574. catch (SocketException exception)
  575. {
  576. errno = ConvertError((WsaError)exception.ErrorCode);
  577. }
  578. }
  579. return WriteBsdResult(context, 0, errno);
  580. }
  581. [Command(15)]
  582. // GetPeerName(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<nn::socket::sockaddr_in, 0x22, 0x10> addr)
  583. public ResultCode GetPeerName(ServiceCtx context)
  584. {
  585. int socketFd = context.RequestData.ReadInt32();
  586. (long bufferPos, long bufferSize) = context.Request.GetBufferType0x22();
  587. LinuxError errno = LinuxError.EBADF;
  588. BsdSocket socket = RetrieveSocket(socketFd);
  589. if (socket != null)
  590. {
  591. errno = LinuxError.SUCCESS;
  592. WriteSockAddr(context, bufferPos, socket, true);
  593. WriteBsdResult(context, 0, errno);
  594. context.ResponseData.Write(0x10);
  595. }
  596. return WriteBsdResult(context, 0, errno);
  597. }
  598. [Command(16)]
  599. // GetSockName(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer<nn::socket::sockaddr_in, 0x22, 0x10> addr)
  600. public ResultCode GetSockName(ServiceCtx context)
  601. {
  602. int socketFd = context.RequestData.ReadInt32();
  603. (long bufferPos, long bufferSize) = context.Request.GetBufferType0x22();
  604. LinuxError errno = LinuxError.EBADF;
  605. BsdSocket socket = RetrieveSocket(socketFd);
  606. if (socket != null)
  607. {
  608. errno = LinuxError.SUCCESS;
  609. WriteSockAddr(context, bufferPos, socket, false);
  610. WriteBsdResult(context, 0, errno);
  611. context.ResponseData.Write(0x10);
  612. }
  613. return WriteBsdResult(context, 0, errno);
  614. }
  615. [Command(17)]
  616. // GetSockOpt(u32 socket, u32 level, u32 option_name) -> (i32 ret, u32 bsd_errno, u32, buffer<unknown, 0x22, 0>)
  617. public ResultCode GetSockOpt(ServiceCtx context)
  618. {
  619. int socketFd = context.RequestData.ReadInt32();
  620. int level = context.RequestData.ReadInt32();
  621. int optionName = context.RequestData.ReadInt32();
  622. (long bufferPosition, long bufferSize) = context.Request.GetBufferType0x22();
  623. LinuxError errno = LinuxError.EBADF;
  624. BsdSocket socket = RetrieveSocket(socketFd);
  625. if (socket != null)
  626. {
  627. errno = LinuxError.ENOPROTOOPT;
  628. if (level == 0xFFFF)
  629. {
  630. errno = HandleGetSocketOption(context, socket, (SocketOptionName)optionName, bufferPosition, bufferSize);
  631. }
  632. else
  633. {
  634. Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported GetSockOpt Level: {(SocketOptionLevel)level}");
  635. }
  636. }
  637. return WriteBsdResult(context, 0, errno);
  638. }
  639. [Command(18)]
  640. // Listen(u32 socket, u32 backlog) -> (i32 ret, u32 bsd_errno)
  641. public ResultCode Listen(ServiceCtx context)
  642. {
  643. int socketFd = context.RequestData.ReadInt32();
  644. int backlog = context.RequestData.ReadInt32();
  645. LinuxError errno = LinuxError.EBADF;
  646. BsdSocket socket = RetrieveSocket(socketFd);
  647. if (socket != null)
  648. {
  649. errno = LinuxError.SUCCESS;
  650. try
  651. {
  652. socket.Handle.Listen(backlog);
  653. }
  654. catch (SocketException exception)
  655. {
  656. errno = ConvertError((WsaError)exception.ErrorCode);
  657. }
  658. }
  659. return WriteBsdResult(context, 0, errno);
  660. }
  661. [Command(19)]
  662. // 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>)
  663. public ResultCode Ioctl(ServiceCtx context)
  664. {
  665. int socketFd = context.RequestData.ReadInt32();
  666. BsdIoctl cmd = (BsdIoctl)context.RequestData.ReadInt32();
  667. int bufferCount = context.RequestData.ReadInt32();
  668. LinuxError errno = LinuxError.EBADF;
  669. BsdSocket socket = RetrieveSocket(socketFd);
  670. if (socket != null)
  671. {
  672. switch (cmd)
  673. {
  674. case BsdIoctl.AtMark:
  675. errno = LinuxError.SUCCESS;
  676. (long bufferPosition, long bufferSize) = context.Request.GetBufferType0x22();
  677. // FIXME: OOB not implemented.
  678. context.Memory.WriteInt32(bufferPosition, 0);
  679. break;
  680. default:
  681. errno = LinuxError.EOPNOTSUPP;
  682. Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Ioctl Cmd: {cmd}");
  683. break;
  684. }
  685. }
  686. return WriteBsdResult(context, 0, errno);
  687. }
  688. [Command(20)]
  689. // Fcntl(u32 socket, u32 cmd, u32 arg) -> (i32 ret, u32 bsd_errno)
  690. public ResultCode Fcntl(ServiceCtx context)
  691. {
  692. int socketFd = context.RequestData.ReadInt32();
  693. int cmd = context.RequestData.ReadInt32();
  694. int arg = context.RequestData.ReadInt32();
  695. int result = 0;
  696. LinuxError errno = LinuxError.EBADF;
  697. BsdSocket socket = RetrieveSocket(socketFd);
  698. if (socket != null)
  699. {
  700. errno = LinuxError.SUCCESS;
  701. if (cmd == 0x3)
  702. {
  703. result = !socket.Handle.Blocking ? 0x800 : 0;
  704. }
  705. else if (cmd == 0x4 && arg == 0x800)
  706. {
  707. socket.Handle.Blocking = false;
  708. result = 0;
  709. }
  710. else
  711. {
  712. errno = LinuxError.EOPNOTSUPP;
  713. }
  714. }
  715. return WriteBsdResult(context, result, errno);
  716. }
  717. private LinuxError HandleGetSocketOption(ServiceCtx context, BsdSocket socket, SocketOptionName optionName, long optionValuePosition, long optionValueSize)
  718. {
  719. try
  720. {
  721. byte[] optionValue = new byte[optionValueSize];
  722. switch (optionName)
  723. {
  724. case SocketOptionName.Broadcast:
  725. case SocketOptionName.DontLinger:
  726. case SocketOptionName.Debug:
  727. case SocketOptionName.Error:
  728. case SocketOptionName.KeepAlive:
  729. case SocketOptionName.OutOfBandInline:
  730. case SocketOptionName.ReceiveBuffer:
  731. case SocketOptionName.ReceiveTimeout:
  732. case SocketOptionName.SendBuffer:
  733. case SocketOptionName.SendTimeout:
  734. case SocketOptionName.Type:
  735. case SocketOptionName.Linger:
  736. socket.Handle.GetSocketOption(SocketOptionLevel.Socket, optionName, optionValue);
  737. context.Memory.WriteBytes(optionValuePosition, optionValue);
  738. return LinuxError.SUCCESS;
  739. case (SocketOptionName)0x200:
  740. socket.Handle.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, optionValue);
  741. context.Memory.WriteBytes(optionValuePosition, optionValue);
  742. return LinuxError.SUCCESS;
  743. default:
  744. Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported SetSockOpt OptionName: {optionName}");
  745. return LinuxError.EOPNOTSUPP;
  746. }
  747. }
  748. catch (SocketException exception)
  749. {
  750. return ConvertError((WsaError)exception.ErrorCode);
  751. }
  752. }
  753. private LinuxError HandleSetSocketOption(ServiceCtx context, BsdSocket socket, SocketOptionName optionName, long optionValuePosition, long optionValueSize)
  754. {
  755. try
  756. {
  757. switch (optionName)
  758. {
  759. case SocketOptionName.Broadcast:
  760. case SocketOptionName.DontLinger:
  761. case SocketOptionName.Debug:
  762. case SocketOptionName.Error:
  763. case SocketOptionName.KeepAlive:
  764. case SocketOptionName.OutOfBandInline:
  765. case SocketOptionName.ReceiveBuffer:
  766. case SocketOptionName.ReceiveTimeout:
  767. case SocketOptionName.SendBuffer:
  768. case SocketOptionName.SendTimeout:
  769. case SocketOptionName.Type:
  770. case SocketOptionName.ReuseAddress:
  771. socket.Handle.SetSocketOption(SocketOptionLevel.Socket, optionName, context.Memory.ReadInt32(optionValuePosition));
  772. return LinuxError.SUCCESS;
  773. case (SocketOptionName)0x200:
  774. socket.Handle.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, context.Memory.ReadInt32(optionValuePosition));
  775. return LinuxError.SUCCESS;
  776. case SocketOptionName.Linger:
  777. socket.Handle.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger,
  778. new LingerOption(context.Memory.ReadInt32(optionValuePosition) != 0, context.Memory.ReadInt32(optionValuePosition + 4)));
  779. return LinuxError.SUCCESS;
  780. default:
  781. Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported SetSockOpt OptionName: {optionName}");
  782. return LinuxError.EOPNOTSUPP;
  783. }
  784. }
  785. catch (SocketException exception)
  786. {
  787. return ConvertError((WsaError)exception.ErrorCode);
  788. }
  789. }
  790. [Command(21)]
  791. // SetSockOpt(u32 socket, u32 level, u32 option_name, buffer<unknown, 0x21, 0> option_value) -> (i32 ret, u32 bsd_errno)
  792. public ResultCode SetSockOpt(ServiceCtx context)
  793. {
  794. int socketFd = context.RequestData.ReadInt32();
  795. int level = context.RequestData.ReadInt32();
  796. int optionName = context.RequestData.ReadInt32();
  797. (long bufferPos, long bufferSize) = context.Request.GetBufferType0x21();
  798. LinuxError errno = LinuxError.EBADF;
  799. BsdSocket socket = RetrieveSocket(socketFd);
  800. if (socket != null)
  801. {
  802. errno = LinuxError.ENOPROTOOPT;
  803. if (level == 0xFFFF)
  804. {
  805. errno = HandleSetSocketOption(context, socket, (SocketOptionName)optionName, bufferPos, bufferSize);
  806. }
  807. else
  808. {
  809. Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported SetSockOpt Level: {(SocketOptionLevel)level}");
  810. }
  811. }
  812. return WriteBsdResult(context, 0, errno);
  813. }
  814. [Command(22)]
  815. // Shutdown(u32 socket, u32 how) -> (i32 ret, u32 bsd_errno)
  816. public ResultCode Shutdown(ServiceCtx context)
  817. {
  818. int socketFd = context.RequestData.ReadInt32();
  819. int how = context.RequestData.ReadInt32();
  820. LinuxError errno = LinuxError.EBADF;
  821. BsdSocket socket = RetrieveSocket(socketFd);
  822. if (socket != null)
  823. {
  824. errno = LinuxError.EINVAL;
  825. if (how >= 0 && how <= 2)
  826. {
  827. errno = LinuxError.SUCCESS;
  828. try
  829. {
  830. socket.Handle.Shutdown((SocketShutdown)how);
  831. }
  832. catch (SocketException exception)
  833. {
  834. errno = ConvertError((WsaError)exception.ErrorCode);
  835. }
  836. }
  837. }
  838. return WriteBsdResult(context, 0, errno);
  839. }
  840. [Command(23)]
  841. // ShutdownAllSockets(u32 how) -> (i32 ret, u32 bsd_errno)
  842. public ResultCode ShutdownAllSockets(ServiceCtx context)
  843. {
  844. int how = context.RequestData.ReadInt32();
  845. LinuxError errno = LinuxError.EINVAL;
  846. if (how >= 0 && how <= 2)
  847. {
  848. errno = LinuxError.SUCCESS;
  849. foreach (BsdSocket socket in _sockets)
  850. {
  851. if (socket != null)
  852. {
  853. try
  854. {
  855. socket.Handle.Shutdown((SocketShutdown)how);
  856. }
  857. catch (SocketException exception)
  858. {
  859. errno = ConvertError((WsaError)exception.ErrorCode);
  860. break;
  861. }
  862. }
  863. }
  864. }
  865. return WriteBsdResult(context, 0, errno);
  866. }
  867. [Command(24)]
  868. // Write(u32 socket, buffer<i8, 0x21, 0> message) -> (i32 ret, u32 bsd_errno)
  869. public ResultCode Write(ServiceCtx context)
  870. {
  871. int socketFd = context.RequestData.ReadInt32();
  872. (long sendPosition, long sendSize) = context.Request.GetBufferType0x21();
  873. LinuxError errno = LinuxError.EBADF;
  874. BsdSocket socket = RetrieveSocket(socketFd);
  875. int result = -1;
  876. if (socket != null)
  877. {
  878. byte[] sendBuffer = context.Memory.ReadBytes(sendPosition, sendSize);
  879. try
  880. {
  881. result = socket.Handle.Send(sendBuffer);
  882. errno = SetResultErrno(socket.Handle, result);
  883. }
  884. catch (SocketException exception)
  885. {
  886. errno = ConvertError((WsaError)exception.ErrorCode);
  887. }
  888. }
  889. return WriteBsdResult(context, result, errno);
  890. }
  891. [Command(25)]
  892. // Read(u32 socket) -> (i32 ret, u32 bsd_errno, buffer<i8, 0x22, 0> message)
  893. public ResultCode Read(ServiceCtx context)
  894. {
  895. int socketFd = context.RequestData.ReadInt32();
  896. (long receivePosition, long receiveLength) = context.Request.GetBufferType0x22();
  897. LinuxError errno = LinuxError.EBADF;
  898. BsdSocket socket = RetrieveSocket(socketFd);
  899. int result = -1;
  900. if (socket != null)
  901. {
  902. byte[] receivedBuffer = new byte[receiveLength];
  903. try
  904. {
  905. result = socket.Handle.Receive(receivedBuffer);
  906. errno = SetResultErrno(socket.Handle, result);
  907. }
  908. catch (SocketException exception)
  909. {
  910. errno = ConvertError((WsaError)exception.ErrorCode);
  911. }
  912. }
  913. return WriteBsdResult(context, result, errno);
  914. }
  915. [Command(26)]
  916. // Close(u32 socket) -> (i32 ret, u32 bsd_errno)
  917. public ResultCode Close(ServiceCtx context)
  918. {
  919. int socketFd = context.RequestData.ReadInt32();
  920. LinuxError errno = LinuxError.EBADF;
  921. BsdSocket socket = RetrieveSocket(socketFd);
  922. if (socket != null)
  923. {
  924. socket.Handle.Close();
  925. _sockets[socketFd] = null;
  926. errno = LinuxError.SUCCESS;
  927. }
  928. return WriteBsdResult(context, 0, errno);
  929. }
  930. [Command(27)]
  931. // DuplicateSocket(u32 socket, u64 reserved) -> (i32 ret, u32 bsd_errno)
  932. public ResultCode DuplicateSocket(ServiceCtx context)
  933. {
  934. int socketFd = context.RequestData.ReadInt32();
  935. ulong reserved = context.RequestData.ReadUInt64();
  936. LinuxError errno = LinuxError.ENOENT;
  937. int newSockFd = -1;
  938. if (_isPrivileged)
  939. {
  940. errno = LinuxError.EBADF;
  941. BsdSocket oldSocket = RetrieveSocket(socketFd);
  942. if (oldSocket != null)
  943. {
  944. _sockets.Add(oldSocket);
  945. newSockFd = _sockets.Count - 1;
  946. }
  947. }
  948. return WriteBsdResult(context, newSockFd, errno);
  949. }
  950. }
  951. }