SessionManager.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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.Threading;
  10. using Utilities;
  11. namespace ISCSI.Server
  12. {
  13. internal class SessionManager
  14. {
  15. private object m_nextTSIHLock = new object();
  16. private ushort m_nextTSIH = 1; // Next Target Session Identifying Handle
  17. private List<ISCSISession> m_activeSessions = new List<ISCSISession>();
  18. public ISCSISession StartSession(ulong isid)
  19. {
  20. ushort tsih = GetNextTSIH();
  21. ISCSISession session = new ISCSISession(isid, tsih);
  22. lock (m_activeSessions)
  23. {
  24. m_activeSessions.Add(session);
  25. }
  26. return session;
  27. }
  28. public ISCSISession FindSession(ulong isid)
  29. {
  30. lock (m_activeSessions)
  31. {
  32. int index = GetSessionIndex(isid);
  33. if (index >= 0)
  34. {
  35. return m_activeSessions[index];
  36. }
  37. }
  38. return null;
  39. }
  40. public void RemoveSession(ISCSISession session)
  41. {
  42. lock (m_activeSessions)
  43. {
  44. int index = GetSessionIndex(session.ISID);
  45. if (index >= 0)
  46. {
  47. m_activeSessions.RemoveAt(index);
  48. }
  49. }
  50. }
  51. public bool IsTargetInUse(string targetName)
  52. {
  53. lock (m_activeSessions)
  54. {
  55. foreach (ISCSISession session in m_activeSessions)
  56. {
  57. if (session.Target != null)
  58. {
  59. if (String.Equals(session.Target.TargetName, targetName, StringComparison.OrdinalIgnoreCase))
  60. {
  61. return true;
  62. }
  63. }
  64. }
  65. }
  66. return false;
  67. }
  68. private int GetSessionIndex(ulong isid)
  69. {
  70. for (int index = 0; index < m_activeSessions.Count; index++)
  71. {
  72. if (m_activeSessions[index].ISID == isid)
  73. {
  74. return index;
  75. }
  76. }
  77. return -1;
  78. }
  79. private ushort GetNextTSIH()
  80. {
  81. // The iSCSI Target selects a non-zero value for the TSIH at
  82. // session creation (when an initiator presents a 0 value at Login).
  83. // After being selected, the same TSIH value MUST be used whenever the
  84. // initiator or target refers to the session and a TSIH is required.
  85. lock (m_nextTSIHLock)
  86. {
  87. ushort nextTSIH = m_nextTSIH;
  88. m_nextTSIH++;
  89. if (m_nextTSIH == 0)
  90. {
  91. m_nextTSIH++;
  92. }
  93. return nextTSIH;
  94. }
  95. }
  96. }
  97. }