ManagedSocket.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. using Ryujinx.Common.Logging;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Runtime.InteropServices;
  8. namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
  9. {
  10. class ManagedSocket : ISocket
  11. {
  12. public int Refcount { get; set; }
  13. public AddressFamily AddressFamily => Socket.AddressFamily;
  14. public SocketType SocketType => Socket.SocketType;
  15. public ProtocolType ProtocolType => Socket.ProtocolType;
  16. public bool Blocking { get => Socket.Blocking; set => Socket.Blocking = value; }
  17. public IntPtr Handle => Socket.Handle;
  18. public IPEndPoint RemoteEndPoint => Socket.RemoteEndPoint as IPEndPoint;
  19. public IPEndPoint LocalEndPoint => Socket.LocalEndPoint as IPEndPoint;
  20. public Socket Socket { get; }
  21. public ManagedSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
  22. {
  23. Socket = new Socket(addressFamily, socketType, protocolType);
  24. Refcount = 1;
  25. }
  26. private ManagedSocket(Socket socket)
  27. {
  28. Socket = socket;
  29. Refcount = 1;
  30. }
  31. private static SocketFlags ConvertBsdSocketFlags(BsdSocketFlags bsdSocketFlags)
  32. {
  33. SocketFlags socketFlags = SocketFlags.None;
  34. if (bsdSocketFlags.HasFlag(BsdSocketFlags.Oob))
  35. {
  36. socketFlags |= SocketFlags.OutOfBand;
  37. }
  38. if (bsdSocketFlags.HasFlag(BsdSocketFlags.Peek))
  39. {
  40. socketFlags |= SocketFlags.Peek;
  41. }
  42. if (bsdSocketFlags.HasFlag(BsdSocketFlags.DontRoute))
  43. {
  44. socketFlags |= SocketFlags.DontRoute;
  45. }
  46. if (bsdSocketFlags.HasFlag(BsdSocketFlags.Trunc))
  47. {
  48. socketFlags |= SocketFlags.Truncated;
  49. }
  50. if (bsdSocketFlags.HasFlag(BsdSocketFlags.CTrunc))
  51. {
  52. socketFlags |= SocketFlags.ControlDataTruncated;
  53. }
  54. bsdSocketFlags &= ~(BsdSocketFlags.Oob |
  55. BsdSocketFlags.Peek |
  56. BsdSocketFlags.DontRoute |
  57. BsdSocketFlags.DontWait |
  58. BsdSocketFlags.Trunc |
  59. BsdSocketFlags.CTrunc);
  60. if (bsdSocketFlags != BsdSocketFlags.None)
  61. {
  62. Logger.Warning?.Print(LogClass.ServiceBsd, $"Unsupported socket flags: {bsdSocketFlags}");
  63. }
  64. return socketFlags;
  65. }
  66. public LinuxError Accept(out ISocket newSocket)
  67. {
  68. try
  69. {
  70. newSocket = new ManagedSocket(Socket.Accept());
  71. return LinuxError.SUCCESS;
  72. }
  73. catch (SocketException exception)
  74. {
  75. newSocket = null;
  76. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  77. }
  78. }
  79. public LinuxError Bind(IPEndPoint localEndPoint)
  80. {
  81. try
  82. {
  83. Socket.Bind(localEndPoint);
  84. return LinuxError.SUCCESS;
  85. }
  86. catch (SocketException exception)
  87. {
  88. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  89. }
  90. }
  91. public void Close()
  92. {
  93. Socket.Close();
  94. }
  95. public LinuxError Connect(IPEndPoint remoteEndPoint)
  96. {
  97. try
  98. {
  99. Socket.Connect(remoteEndPoint);
  100. return LinuxError.SUCCESS;
  101. }
  102. catch (SocketException exception)
  103. {
  104. if (!Blocking && exception.ErrorCode == (int)WsaError.WSAEWOULDBLOCK)
  105. {
  106. return LinuxError.EINPROGRESS;
  107. }
  108. else
  109. {
  110. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  111. }
  112. }
  113. }
  114. public void Disconnect()
  115. {
  116. Socket.Disconnect(true);
  117. }
  118. public void Dispose()
  119. {
  120. Socket.Close();
  121. Socket.Dispose();
  122. }
  123. public LinuxError Listen(int backlog)
  124. {
  125. try
  126. {
  127. Socket.Listen(backlog);
  128. return LinuxError.SUCCESS;
  129. }
  130. catch (SocketException exception)
  131. {
  132. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  133. }
  134. }
  135. public bool Poll(int microSeconds, SelectMode mode)
  136. {
  137. return Socket.Poll(microSeconds, mode);
  138. }
  139. public LinuxError Shutdown(BsdSocketShutdownFlags how)
  140. {
  141. try
  142. {
  143. Socket.Shutdown((SocketShutdown)how);
  144. return LinuxError.SUCCESS;
  145. }
  146. catch (SocketException exception)
  147. {
  148. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  149. }
  150. }
  151. public LinuxError Receive(out int receiveSize, Span<byte> buffer, BsdSocketFlags flags)
  152. {
  153. LinuxError result;
  154. bool shouldBlockAfterOperation = false;
  155. try
  156. {
  157. if (Blocking && flags.HasFlag(BsdSocketFlags.DontWait))
  158. {
  159. Blocking = false;
  160. shouldBlockAfterOperation = true;
  161. }
  162. receiveSize = Socket.Receive(buffer, ConvertBsdSocketFlags(flags));
  163. result = LinuxError.SUCCESS;
  164. }
  165. catch (SocketException exception)
  166. {
  167. receiveSize = -1;
  168. result = WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  169. }
  170. if (shouldBlockAfterOperation)
  171. {
  172. Blocking = true;
  173. }
  174. return result;
  175. }
  176. public LinuxError ReceiveFrom(out int receiveSize, Span<byte> buffer, int size, BsdSocketFlags flags, out IPEndPoint remoteEndPoint)
  177. {
  178. remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
  179. LinuxError result;
  180. bool shouldBlockAfterOperation = false;
  181. try
  182. {
  183. EndPoint temp = new IPEndPoint(IPAddress.Any, 0);
  184. if (Blocking && flags.HasFlag(BsdSocketFlags.DontWait))
  185. {
  186. Blocking = false;
  187. shouldBlockAfterOperation = true;
  188. }
  189. receiveSize = Socket.ReceiveFrom(buffer[..size], ConvertBsdSocketFlags(flags), ref temp);
  190. remoteEndPoint = (IPEndPoint)temp;
  191. result = LinuxError.SUCCESS;
  192. }
  193. catch (SocketException exception)
  194. {
  195. receiveSize = -1;
  196. result = WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  197. }
  198. if (shouldBlockAfterOperation)
  199. {
  200. Blocking = true;
  201. }
  202. return result;
  203. }
  204. public LinuxError Send(out int sendSize, ReadOnlySpan<byte> buffer, BsdSocketFlags flags)
  205. {
  206. try
  207. {
  208. sendSize = Socket.Send(buffer, ConvertBsdSocketFlags(flags));
  209. return LinuxError.SUCCESS;
  210. }
  211. catch (SocketException exception)
  212. {
  213. sendSize = -1;
  214. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  215. }
  216. }
  217. public LinuxError SendTo(out int sendSize, ReadOnlySpan<byte> buffer, int size, BsdSocketFlags flags, IPEndPoint remoteEndPoint)
  218. {
  219. try
  220. {
  221. sendSize = Socket.SendTo(buffer[..size], ConvertBsdSocketFlags(flags), remoteEndPoint);
  222. return LinuxError.SUCCESS;
  223. }
  224. catch (SocketException exception)
  225. {
  226. sendSize = -1;
  227. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  228. }
  229. }
  230. public LinuxError GetSocketOption(BsdSocketOption option, SocketOptionLevel level, Span<byte> optionValue)
  231. {
  232. try
  233. {
  234. if (!WinSockHelper.TryConvertSocketOption(option, level, out SocketOptionName optionName))
  235. {
  236. Logger.Warning?.Print(LogClass.ServiceBsd, $"Unsupported GetSockOpt Option: {option} Level: {level}");
  237. return LinuxError.EOPNOTSUPP;
  238. }
  239. byte[] tempOptionValue = new byte[optionValue.Length];
  240. Socket.GetSocketOption(level, optionName, tempOptionValue);
  241. tempOptionValue.AsSpan().CopyTo(optionValue);
  242. return LinuxError.SUCCESS;
  243. }
  244. catch (SocketException exception)
  245. {
  246. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  247. }
  248. }
  249. public LinuxError SetSocketOption(BsdSocketOption option, SocketOptionLevel level, ReadOnlySpan<byte> optionValue)
  250. {
  251. try
  252. {
  253. if (!WinSockHelper.TryConvertSocketOption(option, level, out SocketOptionName optionName))
  254. {
  255. Logger.Warning?.Print(LogClass.ServiceBsd, $"Unsupported SetSockOpt Option: {option} Level: {level}");
  256. return LinuxError.EOPNOTSUPP;
  257. }
  258. int value = optionValue.Length >= 4 ? MemoryMarshal.Read<int>(optionValue) : MemoryMarshal.Read<byte>(optionValue);
  259. if (level == SocketOptionLevel.Socket && option == BsdSocketOption.SoLinger)
  260. {
  261. int value2 = 0;
  262. if (optionValue.Length >= 8)
  263. {
  264. value2 = MemoryMarshal.Read<int>(optionValue[4..]);
  265. }
  266. Socket.SetSocketOption(level, SocketOptionName.Linger, new LingerOption(value != 0, value2));
  267. }
  268. else
  269. {
  270. Socket.SetSocketOption(level, optionName, value);
  271. }
  272. return LinuxError.SUCCESS;
  273. }
  274. catch (SocketException exception)
  275. {
  276. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  277. }
  278. }
  279. public LinuxError Read(out int readSize, Span<byte> buffer)
  280. {
  281. return Receive(out readSize, buffer, BsdSocketFlags.None);
  282. }
  283. public LinuxError Write(out int writeSize, ReadOnlySpan<byte> buffer)
  284. {
  285. return Send(out writeSize, buffer, BsdSocketFlags.None);
  286. }
  287. private bool CanSupportMMsgHdr(BsdMMsgHdr message)
  288. {
  289. for (int i = 0; i < message.Messages.Length; i++)
  290. {
  291. if (message.Messages[i].Name != null ||
  292. message.Messages[i].Control != null)
  293. {
  294. return false;
  295. }
  296. }
  297. return true;
  298. }
  299. private static IList<ArraySegment<byte>> ConvertMessagesToBuffer(BsdMMsgHdr message)
  300. {
  301. int segmentCount = 0;
  302. int index = 0;
  303. foreach (BsdMsgHdr msgHeader in message.Messages)
  304. {
  305. segmentCount += msgHeader.Iov.Length;
  306. }
  307. ArraySegment<byte>[] buffers = new ArraySegment<byte>[segmentCount];
  308. foreach (BsdMsgHdr msgHeader in message.Messages)
  309. {
  310. foreach (byte[] iov in msgHeader.Iov)
  311. {
  312. buffers[index++] = new ArraySegment<byte>(iov);
  313. }
  314. // Clear the length
  315. msgHeader.Length = 0;
  316. }
  317. return buffers;
  318. }
  319. private static void UpdateMessages(out int vlen, BsdMMsgHdr message, int transferedSize)
  320. {
  321. int bytesLeft = transferedSize;
  322. int index = 0;
  323. while (bytesLeft > 0)
  324. {
  325. // First ensure we haven't finished all buffers
  326. if (index >= message.Messages.Length)
  327. {
  328. break;
  329. }
  330. BsdMsgHdr msgHeader = message.Messages[index];
  331. int possiblyTransferedBytes = 0;
  332. foreach (byte[] iov in msgHeader.Iov)
  333. {
  334. possiblyTransferedBytes += iov.Length;
  335. }
  336. int storedBytes;
  337. if (bytesLeft > possiblyTransferedBytes)
  338. {
  339. storedBytes = possiblyTransferedBytes;
  340. index++;
  341. }
  342. else
  343. {
  344. storedBytes = bytesLeft;
  345. }
  346. msgHeader.Length = (uint)storedBytes;
  347. bytesLeft -= storedBytes;
  348. }
  349. Debug.Assert(bytesLeft == 0);
  350. vlen = index + 1;
  351. }
  352. // TODO: Find a way to support passing the timeout somehow without changing the socket ReceiveTimeout.
  353. public LinuxError RecvMMsg(out int vlen, BsdMMsgHdr message, BsdSocketFlags flags, TimeVal timeout)
  354. {
  355. vlen = 0;
  356. if (message.Messages.Length == 0)
  357. {
  358. return LinuxError.SUCCESS;
  359. }
  360. if (!CanSupportMMsgHdr(message))
  361. {
  362. Logger.Warning?.Print(LogClass.ServiceBsd, $"Unsupported BsdMMsgHdr");
  363. return LinuxError.EOPNOTSUPP;
  364. }
  365. if (message.Messages.Length == 0)
  366. {
  367. return LinuxError.SUCCESS;
  368. }
  369. try
  370. {
  371. int receiveSize = Socket.Receive(ConvertMessagesToBuffer(message), ConvertBsdSocketFlags(flags), out SocketError socketError);
  372. if (receiveSize > 0)
  373. {
  374. UpdateMessages(out vlen, message, receiveSize);
  375. }
  376. return WinSockHelper.ConvertError((WsaError)socketError);
  377. }
  378. catch (SocketException exception)
  379. {
  380. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  381. }
  382. }
  383. public LinuxError SendMMsg(out int vlen, BsdMMsgHdr message, BsdSocketFlags flags)
  384. {
  385. vlen = 0;
  386. if (message.Messages.Length == 0)
  387. {
  388. return LinuxError.SUCCESS;
  389. }
  390. if (!CanSupportMMsgHdr(message))
  391. {
  392. Logger.Warning?.Print(LogClass.ServiceBsd, $"Unsupported BsdMMsgHdr");
  393. return LinuxError.EOPNOTSUPP;
  394. }
  395. if (message.Messages.Length == 0)
  396. {
  397. return LinuxError.SUCCESS;
  398. }
  399. try
  400. {
  401. int sendSize = Socket.Send(ConvertMessagesToBuffer(message), ConvertBsdSocketFlags(flags), out SocketError socketError);
  402. if (sendSize > 0)
  403. {
  404. UpdateMessages(out vlen, message, sendSize);
  405. }
  406. return WinSockHelper.ConvertError((WsaError)socketError);
  407. }
  408. catch (SocketException exception)
  409. {
  410. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  411. }
  412. }
  413. }
  414. }