IClient.cs 43 KB

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