IClient.cs 44 KB

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