IClient.cs 43 KB

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