ConnectionManager.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /* Copyright (C) 2017 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.Net;
  10. using Utilities;
  11. namespace SMBLibrary.Server
  12. {
  13. internal class ConnectionManager
  14. {
  15. private List<ConnectionState> m_activeConnections = new List<ConnectionState>();
  16. public void AddConnection(ConnectionState connection)
  17. {
  18. lock (m_activeConnections)
  19. {
  20. m_activeConnections.Add(connection);
  21. }
  22. }
  23. public bool RemoveConnection(ConnectionState connection)
  24. {
  25. lock (m_activeConnections)
  26. {
  27. int connectionIndex = m_activeConnections.IndexOf(connection);
  28. if (connectionIndex >= 0)
  29. {
  30. m_activeConnections.RemoveAt(connectionIndex);
  31. return true;
  32. }
  33. return false;
  34. }
  35. }
  36. public void ReleaseConnection(ConnectionState connection)
  37. {
  38. connection.SendQueue.Stop();
  39. SocketUtils.ReleaseSocket(connection.ClientSocket);
  40. connection.CloseSessions();
  41. RemoveConnection(connection);
  42. }
  43. public void ReleaseConnection(IPEndPoint clientEndPoint)
  44. {
  45. ConnectionState connection = FindConnection(clientEndPoint);
  46. if (connection != null)
  47. {
  48. ReleaseConnection(connection);
  49. }
  50. }
  51. public void ReleaseAllConnections()
  52. {
  53. List<ConnectionState> connections = new List<ConnectionState>(m_activeConnections);
  54. foreach (ConnectionState connection in connections)
  55. {
  56. ReleaseConnection(connection);
  57. }
  58. }
  59. private ConnectionState FindConnection(IPEndPoint clientEndPoint)
  60. {
  61. lock (m_activeConnections)
  62. {
  63. for (int index = 0; index < m_activeConnections.Count; index++)
  64. {
  65. if (m_activeConnections[index].ClientEndPoint.Equals(clientEndPoint))
  66. {
  67. return m_activeConnections[index];
  68. }
  69. }
  70. }
  71. return null;
  72. }
  73. public List<SessionInformation> GetSessionsInformation()
  74. {
  75. List<SessionInformation> result = new List<SessionInformation>();
  76. lock (m_activeConnections)
  77. {
  78. foreach (ConnectionState connection in m_activeConnections)
  79. {
  80. List<SessionInformation> sessions = connection.GetSessionsInformation();
  81. result.AddRange(sessions);
  82. }
  83. }
  84. return result;
  85. }
  86. }
  87. }