-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecureChannelManager.cs
More file actions
82 lines (69 loc) · 2.68 KB
/
SecureChannelManager.cs
File metadata and controls
82 lines (69 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System.Collections.Concurrent;
namespace M9Studio.SecureStream
{
public class SecureChannelManager<TAddress>
{
private readonly ISecureTransportAdapter<TAddress> _adapter;
private readonly ConcurrentDictionary<TAddress, SecureSession<TAddress>> _sessions = new();
public event Action<SecureSession<TAddress>>? OnConnected;
public event Action<SecureSession<TAddress>>? OnDisconnected;
public SecureChannelManager(ISecureTransportAdapter<TAddress> adapter)
{
_adapter = adapter;
_adapter.OnConnected += HandleConnection;
_adapter.OnDisconnected += Disconnected;
}
private void HandleConnection(TAddress address)
{
if (_sessions.ContainsKey(address))
{
Console.WriteLine($"[SecureChannelManager] Session with {address} already exists. Ignoring duplicate.");
return;
}
Task.Run(() =>
{
try
{
byte[] firstPacket = _adapter.ReceiveFrom(address);
if (IsX25519PublicKey(firstPacket))
{
var session = new SecureSession<TAddress>(_adapter, address);
_sessions[address] = session;
session.PerformHandshakeAsServer(firstPacket);
OnConnected?.Invoke(session);
}
else
{
// Лог: некорректный формат handshake
}
}
catch (Exception ex)
{
// Лог ошибок (опционально)
}
});
}
private void Disconnected(TAddress address)
{
SecureSession<TAddress>? session = null;
if(_sessions.TryRemove(address, out session))
{
session._IsLive = false;
OnDisconnected?.Invoke(session);
}
}
public SecureSession<TAddress> Connect(TAddress address)
{
//Console.WriteLine($"[SecureChannelManager] Connecting to {address}...");
var session = new SecureSession<TAddress>(_adapter, address);
_sessions[address] = session;
session.PerformHandshakeAsClient();
//Console.WriteLine($"[SecureChannelManager] Handshake complete with {address}");
return session;
}
private bool IsX25519PublicKey(byte[] data)
{
return data != null && data.Length == 32; // X25519 pubkey = 32 bytes
}
}
}