ManagedSocket.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. if (!Socket.IsBound)
  190. {
  191. receiveSize = -1;
  192. return LinuxError.EOPNOTSUPP;
  193. }
  194. receiveSize = Socket.ReceiveFrom(buffer[..size], ConvertBsdSocketFlags(flags), ref temp);
  195. remoteEndPoint = (IPEndPoint)temp;
  196. result = LinuxError.SUCCESS;
  197. }
  198. catch (SocketException exception)
  199. {
  200. receiveSize = -1;
  201. result = WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  202. }
  203. if (shouldBlockAfterOperation)
  204. {
  205. Blocking = true;
  206. }
  207. return result;
  208. }
  209. public LinuxError Send(out int sendSize, ReadOnlySpan<byte> buffer, BsdSocketFlags flags)
  210. {
  211. try
  212. {
  213. sendSize = Socket.Send(buffer, ConvertBsdSocketFlags(flags));
  214. return LinuxError.SUCCESS;
  215. }
  216. catch (SocketException exception)
  217. {
  218. sendSize = -1;
  219. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  220. }
  221. }
  222. public LinuxError SendTo(out int sendSize, ReadOnlySpan<byte> buffer, int size, BsdSocketFlags flags, IPEndPoint remoteEndPoint)
  223. {
  224. try
  225. {
  226. sendSize = Socket.SendTo(buffer[..size], ConvertBsdSocketFlags(flags), remoteEndPoint);
  227. return LinuxError.SUCCESS;
  228. }
  229. catch (SocketException exception)
  230. {
  231. sendSize = -1;
  232. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  233. }
  234. }
  235. public LinuxError GetSocketOption(BsdSocketOption option, SocketOptionLevel level, Span<byte> optionValue)
  236. {
  237. try
  238. {
  239. if (!WinSockHelper.TryConvertSocketOption(option, level, out SocketOptionName optionName))
  240. {
  241. Logger.Warning?.Print(LogClass.ServiceBsd, $"Unsupported GetSockOpt Option: {option} Level: {level}");
  242. return LinuxError.EOPNOTSUPP;
  243. }
  244. byte[] tempOptionValue = new byte[optionValue.Length];
  245. Socket.GetSocketOption(level, optionName, tempOptionValue);
  246. tempOptionValue.AsSpan().CopyTo(optionValue);
  247. return LinuxError.SUCCESS;
  248. }
  249. catch (SocketException exception)
  250. {
  251. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  252. }
  253. }
  254. public LinuxError SetSocketOption(BsdSocketOption option, SocketOptionLevel level, ReadOnlySpan<byte> optionValue)
  255. {
  256. try
  257. {
  258. if (!WinSockHelper.TryConvertSocketOption(option, level, out SocketOptionName optionName))
  259. {
  260. Logger.Warning?.Print(LogClass.ServiceBsd, $"Unsupported SetSockOpt Option: {option} Level: {level}");
  261. return LinuxError.EOPNOTSUPP;
  262. }
  263. int value = optionValue.Length >= 4 ? MemoryMarshal.Read<int>(optionValue) : MemoryMarshal.Read<byte>(optionValue);
  264. if (level == SocketOptionLevel.Socket && option == BsdSocketOption.SoLinger)
  265. {
  266. int value2 = 0;
  267. if (optionValue.Length >= 8)
  268. {
  269. value2 = MemoryMarshal.Read<int>(optionValue[4..]);
  270. }
  271. Socket.SetSocketOption(level, SocketOptionName.Linger, new LingerOption(value != 0, value2));
  272. }
  273. else
  274. {
  275. Socket.SetSocketOption(level, optionName, value);
  276. }
  277. return LinuxError.SUCCESS;
  278. }
  279. catch (SocketException exception)
  280. {
  281. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  282. }
  283. }
  284. public LinuxError Read(out int readSize, Span<byte> buffer)
  285. {
  286. return Receive(out readSize, buffer, BsdSocketFlags.None);
  287. }
  288. public LinuxError Write(out int writeSize, ReadOnlySpan<byte> buffer)
  289. {
  290. return Send(out writeSize, buffer, BsdSocketFlags.None);
  291. }
  292. private bool CanSupportMMsgHdr(BsdMMsgHdr message)
  293. {
  294. for (int i = 0; i < message.Messages.Length; i++)
  295. {
  296. if (message.Messages[i].Name != null ||
  297. message.Messages[i].Control != null)
  298. {
  299. return false;
  300. }
  301. }
  302. return true;
  303. }
  304. private static IList<ArraySegment<byte>> ConvertMessagesToBuffer(BsdMMsgHdr message)
  305. {
  306. int segmentCount = 0;
  307. int index = 0;
  308. foreach (BsdMsgHdr msgHeader in message.Messages)
  309. {
  310. segmentCount += msgHeader.Iov.Length;
  311. }
  312. ArraySegment<byte>[] buffers = new ArraySegment<byte>[segmentCount];
  313. foreach (BsdMsgHdr msgHeader in message.Messages)
  314. {
  315. foreach (byte[] iov in msgHeader.Iov)
  316. {
  317. buffers[index++] = new ArraySegment<byte>(iov);
  318. }
  319. // Clear the length
  320. msgHeader.Length = 0;
  321. }
  322. return buffers;
  323. }
  324. private static void UpdateMessages(out int vlen, BsdMMsgHdr message, int transferedSize)
  325. {
  326. int bytesLeft = transferedSize;
  327. int index = 0;
  328. while (bytesLeft > 0)
  329. {
  330. // First ensure we haven't finished all buffers
  331. if (index >= message.Messages.Length)
  332. {
  333. break;
  334. }
  335. BsdMsgHdr msgHeader = message.Messages[index];
  336. int possiblyTransferedBytes = 0;
  337. foreach (byte[] iov in msgHeader.Iov)
  338. {
  339. possiblyTransferedBytes += iov.Length;
  340. }
  341. int storedBytes;
  342. if (bytesLeft > possiblyTransferedBytes)
  343. {
  344. storedBytes = possiblyTransferedBytes;
  345. index++;
  346. }
  347. else
  348. {
  349. storedBytes = bytesLeft;
  350. }
  351. msgHeader.Length = (uint)storedBytes;
  352. bytesLeft -= storedBytes;
  353. }
  354. Debug.Assert(bytesLeft == 0);
  355. vlen = index + 1;
  356. }
  357. // TODO: Find a way to support passing the timeout somehow without changing the socket ReceiveTimeout.
  358. public LinuxError RecvMMsg(out int vlen, BsdMMsgHdr message, BsdSocketFlags flags, TimeVal timeout)
  359. {
  360. vlen = 0;
  361. if (message.Messages.Length == 0)
  362. {
  363. return LinuxError.SUCCESS;
  364. }
  365. if (!CanSupportMMsgHdr(message))
  366. {
  367. Logger.Warning?.Print(LogClass.ServiceBsd, $"Unsupported BsdMMsgHdr");
  368. return LinuxError.EOPNOTSUPP;
  369. }
  370. if (message.Messages.Length == 0)
  371. {
  372. return LinuxError.SUCCESS;
  373. }
  374. try
  375. {
  376. int receiveSize = Socket.Receive(ConvertMessagesToBuffer(message), ConvertBsdSocketFlags(flags), out SocketError socketError);
  377. if (receiveSize > 0)
  378. {
  379. UpdateMessages(out vlen, message, receiveSize);
  380. }
  381. return WinSockHelper.ConvertError((WsaError)socketError);
  382. }
  383. catch (SocketException exception)
  384. {
  385. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  386. }
  387. }
  388. public LinuxError SendMMsg(out int vlen, BsdMMsgHdr message, BsdSocketFlags flags)
  389. {
  390. vlen = 0;
  391. if (message.Messages.Length == 0)
  392. {
  393. return LinuxError.SUCCESS;
  394. }
  395. if (!CanSupportMMsgHdr(message))
  396. {
  397. Logger.Warning?.Print(LogClass.ServiceBsd, $"Unsupported BsdMMsgHdr");
  398. return LinuxError.EOPNOTSUPP;
  399. }
  400. if (message.Messages.Length == 0)
  401. {
  402. return LinuxError.SUCCESS;
  403. }
  404. try
  405. {
  406. int sendSize = Socket.Send(ConvertMessagesToBuffer(message), ConvertBsdSocketFlags(flags), out SocketError socketError);
  407. if (sendSize > 0)
  408. {
  409. UpdateMessages(out vlen, message, sendSize);
  410. }
  411. return WinSockHelper.ConvertError((WsaError)socketError);
  412. }
  413. catch (SocketException exception)
  414. {
  415. return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
  416. }
  417. }
  418. }
  419. }