ISCSIServer.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. /* Copyright (C) 2012-2016 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Net;
  11. using System.Net.Sockets;
  12. using System.Text;
  13. using System.Threading;
  14. using Utilities;
  15. namespace ISCSI.Server
  16. {
  17. /// <summary>
  18. /// an iSCSI server that can serve multiple iSCSI targets
  19. /// </summary>
  20. public partial class ISCSIServer
  21. {
  22. public const int DefaultPort = 3260;
  23. private Socket m_listenerSocket;
  24. private bool m_listening;
  25. private Thread m_keepAliveThread;
  26. private TargetList m_targets = new TargetList();
  27. private SessionManager m_sessionManager = new SessionManager();
  28. private ConnectionManager m_connectionManager = new ConnectionManager();
  29. public event EventHandler<LogEntry> OnLogEntry;
  30. /// <summary>
  31. /// Server needs to be started with Start()
  32. /// </summary>
  33. public ISCSIServer()
  34. {
  35. }
  36. public void AddTarget(ISCSITarget target)
  37. {
  38. m_targets.AddTarget(target);
  39. }
  40. public void AddTargets(List<ISCSITarget> targets)
  41. {
  42. foreach (ISCSITarget target in targets)
  43. {
  44. m_targets.AddTarget(target);
  45. }
  46. }
  47. public bool RemoveTarget(string targetName)
  48. {
  49. // We use m_targets.Lock to synchronize between the login logic and the target removal logic.
  50. // We must obtain the lock before calling IsTargetInUse() to prevent a successful login to a target followed by its removal.
  51. lock (m_targets.Lock)
  52. {
  53. if (!m_sessionManager.IsTargetInUse(targetName))
  54. {
  55. return m_targets.RemoveTarget(targetName);
  56. }
  57. }
  58. return false;
  59. }
  60. public void Start()
  61. {
  62. Start(DefaultPort);
  63. }
  64. /// <param name="listenerPort">The port on which the iSCSI server will listen</param>
  65. public void Start(int listenerPort)
  66. {
  67. Start(new IPEndPoint(IPAddress.Any, listenerPort));
  68. }
  69. public void Start(IPEndPoint listenerEndPoint)
  70. {
  71. Start(listenerEndPoint, TimeSpan.FromMinutes(5));
  72. }
  73. /// <param name="listenerEP">The endpoint on which the iSCSI server will listen</param>
  74. /// <param name="keepAliveTime">The duration between keep-alive transmissions</param>
  75. public void Start(IPEndPoint listenerEndPoint, TimeSpan? keepAliveTime)
  76. {
  77. if (!m_listening)
  78. {
  79. Log(Severity.Information, "Starting Server");
  80. m_listening = true;
  81. m_listenerSocket = new Socket(listenerEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  82. m_listenerSocket.Bind(listenerEndPoint);
  83. m_listenerSocket.Listen(1000);
  84. m_listenerSocket.BeginAccept(ConnectRequestCallback, m_listenerSocket);
  85. if (keepAliveTime.HasValue)
  86. {
  87. m_keepAliveThread = new Thread(delegate()
  88. {
  89. while (m_listening)
  90. {
  91. Thread.Sleep(keepAliveTime.Value);
  92. m_connectionManager.SendKeepAlive();
  93. }
  94. });
  95. m_keepAliveThread.IsBackground = true;
  96. m_keepAliveThread.Start();
  97. }
  98. }
  99. }
  100. // This method accepts new connections
  101. private void ConnectRequestCallback(IAsyncResult ar)
  102. {
  103. Socket listenerSocket = (Socket)ar.AsyncState;
  104. Socket clientSocket;
  105. try
  106. {
  107. clientSocket = listenerSocket.EndAccept(ar);
  108. }
  109. catch (ObjectDisposedException)
  110. {
  111. return;
  112. }
  113. catch (SocketException)
  114. {
  115. return;
  116. }
  117. Log(Severity.Information, "New connection has been accepted");
  118. ConnectionState state = new ConnectionState();
  119. state.ConnectionParameters.InitiatorEndPoint = clientSocket.RemoteEndPoint as IPEndPoint;
  120. state.ReceiveBuffer = new byte[ConnectionState.ReceiveBufferSize];
  121. // Disable the Nagle Algorithm for this tcp socket:
  122. clientSocket.NoDelay = true;
  123. state.ClientSocket = clientSocket;
  124. Thread senderThread = new Thread(delegate()
  125. {
  126. ProcessSendQueue(state);
  127. });
  128. senderThread.IsBackground = true;
  129. senderThread.Start();
  130. try
  131. {
  132. clientSocket.BeginReceive(state.ReceiveBuffer, 0, ConnectionState.ReceiveBufferSize, 0, ReceiveCallback, state);
  133. }
  134. catch (ObjectDisposedException)
  135. {
  136. Log(Severity.Debug, "[OnConnectRequest] BeginReceive ObjectDisposedException");
  137. }
  138. catch (SocketException ex)
  139. {
  140. Log(Severity.Debug, "[OnConnectRequest] BeginReceive SocketException: {0}", ex.Message);
  141. }
  142. m_listenerSocket.BeginAccept(ConnectRequestCallback, m_listenerSocket);
  143. }
  144. public void Stop()
  145. {
  146. Log(Severity.Information, "Stopping Server");
  147. m_listening = false;
  148. if (m_keepAliveThread != null)
  149. {
  150. m_keepAliveThread.Abort();
  151. }
  152. SocketUtils.ReleaseSocket(m_listenerSocket);
  153. lock (m_targets.Lock)
  154. {
  155. List<ISCSITarget> targets = m_targets.GetList();
  156. foreach (ISCSITarget target in targets)
  157. {
  158. ResetTarget(target.TargetName);
  159. }
  160. }
  161. }
  162. /// <summary>
  163. /// Will terminate all TCP connections to all initiators (all sessions will be terminated)
  164. /// </summary>
  165. public void ResetTarget(string targetName)
  166. {
  167. List<ISCSISession> targetSessions = m_sessionManager.FindTargetSessions(targetName);
  168. foreach (ISCSISession session in targetSessions)
  169. {
  170. List<ConnectionState> sessionConnections = m_connectionManager.GetSessionConnections(session);
  171. foreach (ConnectionState sessionConnection in sessionConnections)
  172. {
  173. m_connectionManager.ReleaseConnection(sessionConnection);
  174. }
  175. m_sessionManager.RemoveSession(session, SessionTerminationReason.TargetReset);
  176. }
  177. }
  178. private void ReceiveCallback(IAsyncResult result)
  179. {
  180. if (!m_listening)
  181. {
  182. return;
  183. }
  184. ConnectionState state = (ConnectionState)result.AsyncState;
  185. Socket clientSocket = state.ClientSocket;
  186. if (!clientSocket.Connected)
  187. {
  188. HandleConnectionTermination(state);
  189. return;
  190. }
  191. int numberOfBytesReceived;
  192. try
  193. {
  194. numberOfBytesReceived = clientSocket.EndReceive(result);
  195. }
  196. catch (ObjectDisposedException)
  197. {
  198. HandleConnectionTermination(state);
  199. Log(Severity.Debug, "[ReceiveCallback] EndReceive ObjectDisposedException");
  200. return;
  201. }
  202. catch (SocketException ex)
  203. {
  204. HandleConnectionTermination(state);
  205. Log(Severity.Debug, "[ReceiveCallback] EndReceive SocketException: {0}", ex.Message);
  206. return;
  207. }
  208. if (numberOfBytesReceived == 0)
  209. {
  210. // The other side has closed the connection
  211. Log(Severity.Verbose, "[{0}] The initiator has closed the connection", state.ConnectionIdentifier);
  212. HandleConnectionTermination(state);
  213. return;
  214. }
  215. byte[] currentBuffer = ByteReader.ReadBytes(state.ReceiveBuffer, 0, numberOfBytesReceived);
  216. ProcessCurrentBuffer(currentBuffer, state);
  217. try
  218. {
  219. clientSocket.BeginReceive(state.ReceiveBuffer, 0, ConnectionState.ReceiveBufferSize, 0, ReceiveCallback, state);
  220. }
  221. catch (ObjectDisposedException)
  222. {
  223. HandleConnectionTermination(state);
  224. Log(Severity.Debug, "[ReceiveCallback] BeginReceive ObjectDisposedException");
  225. }
  226. catch (SocketException ex)
  227. {
  228. HandleConnectionTermination(state);
  229. Log(Severity.Debug, "[ReceiveCallback] BeginReceive SocketException: {0}", ex.Message);
  230. }
  231. }
  232. private void HandleConnectionTermination(ConnectionState state)
  233. {
  234. m_connectionManager.ReleaseConnection(state);
  235. if (state.Session != null)
  236. {
  237. List<ConnectionState> connections = m_connectionManager.GetSessionConnections(state.Session);
  238. if (connections.Count == 0)
  239. {
  240. Thread timeoutThread = new Thread(delegate()
  241. {
  242. // Session timeout is an event defined to occur when the last connection [..] timeout expires
  243. int timeout = state.Session.DefaultTime2Wait + state.Session.DefaultTime2Retain;
  244. Thread.Sleep(timeout * 1000);
  245. // Check if there are still no connections in this session
  246. connections = m_connectionManager.GetSessionConnections(state.Session);
  247. if (connections.Count == 0)
  248. {
  249. m_sessionManager.RemoveSession(state.Session, SessionTerminationReason.ConnectionFailure);
  250. }
  251. });
  252. timeoutThread.IsBackground = true;
  253. timeoutThread.Start();
  254. }
  255. }
  256. }
  257. private void ProcessCurrentBuffer(byte[] currentBuffer, ConnectionState state)
  258. {
  259. Socket clientSocket = state.ClientSocket;
  260. if (state.ConnectionBuffer.Length == 0)
  261. {
  262. state.ConnectionBuffer = currentBuffer;
  263. }
  264. else
  265. {
  266. state.ConnectionBuffer = ByteUtils.Concatenate(state.ConnectionBuffer, currentBuffer);
  267. }
  268. // we now have all PDU bytes received so far in state.ConnectionBuffer
  269. int bytesLeftInBuffer = state.ConnectionBuffer.Length;
  270. while (bytesLeftInBuffer >= 8)
  271. {
  272. int bufferOffset = state.ConnectionBuffer.Length - bytesLeftInBuffer;
  273. int pduLength = ISCSIPDU.GetPDULength(state.ConnectionBuffer, bufferOffset);
  274. if (pduLength > bytesLeftInBuffer)
  275. {
  276. Log(Severity.Debug, "[{0}][ProcessCurrentBuffer] Bytes left in receive buffer: {1}", state.ConnectionIdentifier, bytesLeftInBuffer);
  277. break;
  278. }
  279. else
  280. {
  281. byte[] pduBytes = ByteReader.ReadBytes(state.ConnectionBuffer, bufferOffset, pduLength);
  282. bytesLeftInBuffer -= pduLength;
  283. ISCSIPDU pdu = null;
  284. try
  285. {
  286. pdu = ISCSIPDU.GetPDU(pduBytes);
  287. }
  288. catch (Exception ex)
  289. {
  290. Log(Severity.Error, "[{0}] Failed to read PDU (Exception: {1})", state.ConnectionIdentifier, ex.Message);
  291. RejectPDU reject = new RejectPDU();
  292. reject.Reason = RejectReason.InvalidPDUField;
  293. reject.Data = ByteReader.ReadBytes(pduBytes, 0, 48);
  294. state.SendQueue.Enqueue(reject);
  295. }
  296. if (pdu != null)
  297. {
  298. if (pdu.GetType() == typeof(ISCSIPDU))
  299. {
  300. Log(Severity.Error, "[{0}][ProcessCurrentBuffer] Unsupported PDU (0x{1})", state.ConnectionIdentifier, pdu.OpCode.ToString("X"));
  301. // Unsupported PDU
  302. RejectPDU reject = new RejectPDU();
  303. reject.InitiatorTaskTag = pdu.InitiatorTaskTag;
  304. reject.Reason = RejectReason.CommandNotSupported;
  305. reject.Data = ByteReader.ReadBytes(pduBytes, 0, 48);
  306. state.SendQueue.Enqueue(reject);
  307. }
  308. else
  309. {
  310. bool valid = ValidateCommandNumbering(pdu, state);
  311. if (valid)
  312. {
  313. ProcessPDU(pdu, state);
  314. }
  315. else
  316. {
  317. // We ignore this PDU
  318. Log(Severity.Warning, "[{0}] Ignoring PDU with CmdSN outside of expected range", state.ConnectionIdentifier);
  319. }
  320. }
  321. }
  322. if (!clientSocket.Connected)
  323. {
  324. // Do not continue to process the buffer if the other side closed the connection
  325. if (bytesLeftInBuffer > 0)
  326. {
  327. Log(Severity.Debug, "[{0}] Buffer processing aborted, bytes left in receive buffer: {1}", state.ConnectionIdentifier, bytesLeftInBuffer);
  328. }
  329. return;
  330. }
  331. }
  332. }
  333. if (bytesLeftInBuffer > 0)
  334. {
  335. state.ConnectionBuffer = ByteReader.ReadBytes(state.ConnectionBuffer, state.ConnectionBuffer.Length - bytesLeftInBuffer, bytesLeftInBuffer);
  336. }
  337. else
  338. {
  339. state.ConnectionBuffer = new byte[0];
  340. }
  341. }
  342. private void ProcessSendQueue(ConnectionState state)
  343. {
  344. while (true)
  345. {
  346. Log(Severity.Trace, "Entering ProcessSendQueue");
  347. ISCSIPDU response;
  348. bool stopped = !state.SendQueue.TryDequeue(out response);
  349. if (stopped)
  350. {
  351. return;
  352. }
  353. Socket clientSocket = state.ClientSocket;
  354. PDUHelper.SetStatSN(response, state.ConnectionParameters.StatSN);
  355. if (state.Session != null)
  356. {
  357. PDUHelper.SetExpCmdSN(response, state.Session.ExpCmdSN, state.Session.ExpCmdSN + state.Session.CommandQueueSize);
  358. }
  359. if (response is SCSIResponsePDU ||
  360. response is LoginResponsePDU ||
  361. response is TextResponsePDU ||
  362. (response is SCSIDataInPDU && ((SCSIDataInPDU)response).StatusPresent) ||
  363. response is RejectPDU)
  364. {
  365. state.ConnectionParameters.StatSN++;
  366. }
  367. try
  368. {
  369. clientSocket.Send(response.GetBytes());
  370. Log(Severity.Verbose, "[{0}] Sent response to initator, Operation: {1}, Size: {2}", state.ConnectionIdentifier, response.OpCode, response.Length);
  371. if (response is LogoutResponsePDU)
  372. {
  373. clientSocket.Close(); // We can close the connection now
  374. Log(Severity.Trace, "Leaving ProcessSendQueue");
  375. return;
  376. }
  377. else if (response is LoginResponsePDU)
  378. {
  379. if (((LoginResponsePDU)response).Status != LoginResponseStatusName.Success)
  380. {
  381. // Login Response: If the Status Class is not 0, the initiator and target MUST close the TCP connection.
  382. clientSocket.Close(); // We can close the connection now
  383. Log(Severity.Trace, "Leaving ProcessSendQueue");
  384. return;
  385. }
  386. }
  387. }
  388. catch (SocketException ex)
  389. {
  390. Log(Severity.Verbose, "[{0}] Failed to send response to initator. Operation: {1}, Size: {2}, SocketException: {3}", state.ConnectionIdentifier, response.OpCode, response.Length, ex.Message);
  391. Log(Severity.Trace, "Leaving ProcessSendQueue");
  392. return;
  393. }
  394. catch (ObjectDisposedException)
  395. {
  396. Log(Severity.Verbose, "[{0}] Failed to send response to initator. Operation: {1}, Size: {2}. ObjectDisposedException", state.ConnectionIdentifier, response.OpCode, response.Length);
  397. Log(Severity.Trace, "Leaving ProcessSendQueue");
  398. return;
  399. }
  400. }
  401. }
  402. public void Log(Severity severity, string message)
  403. {
  404. // To be thread-safe we must capture the delegate reference first
  405. EventHandler<LogEntry> handler = OnLogEntry;
  406. if (handler != null)
  407. {
  408. handler(this, new LogEntry(DateTime.Now, severity, "iSCSI Server", message));
  409. }
  410. }
  411. public void Log(Severity severity, string message, params object[] args)
  412. {
  413. Log(severity, String.Format(message, args));
  414. }
  415. }
  416. }