-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecureStreamLogger.cs
More file actions
70 lines (64 loc) · 3.25 KB
/
SecureStreamLogger.cs
File metadata and controls
70 lines (64 loc) · 3.25 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
using M9Studio.SecureStream;
using M9Studio.ShadowTalk.Core;
using Org.BouncyCastle.Utilities;
using System.Net;
using System.Text;
namespace M9Studio.ShadowTalk.Server
{
public class SecureStreamLogger : ISecureTransportAdapter<IPEndPoint>
{
public event Action<IPEndPoint> OnConnected;
public event Action<IPEndPoint> OnDisconnected;
private TcpServerSecureTransportAdapter adapter;
private Logger logger;
public SecureStreamLogger(TcpServerSecureTransportAdapter adapter, Logger logger)
{
this.adapter = adapter;
this.logger = logger;
adapter.OnConnected += (address) => {
logger.Log($"SecureStream [{address}]: Подключился", Logger.Type.SecureStream_Connect);
OnConnected?.Invoke(address);
};
adapter.OnDisconnected += (address) => {
logger.Log($"SecureStream [{address}]: Отключился", Logger.Type.SecureStream_Disconnect);
OnDisconnected?.Invoke(address);
};
}
public byte[] ReceiveFrom(IPEndPoint address)
{
byte[] buffer;
logger.Log($"SecureStream.ReceiveFrom(IPEndPoint {address}): Ожидаем зашифрованный пакет", Logger.Type.SecureStream_Receive);
try
{
buffer = adapter.ReceiveFrom(address);
}
catch (Exception ex)
{
logger.Log($"SecureStream.ReceiveFrom(IPEndPoint {address}): Ошибка при получении: {ex.Message}", Logger.Type.SecureStream_Receive);
throw new Exception(ex.Message);
}
logger.Log($"SecureStream.ReceiveFrom(IPEndPoint {address}): Получен зашифрованный пакет (hash: {buffer.GetHashCode()} size: {buffer.Length}) UTF8[{Encoding.UTF8.GetString(buffer)}] Hex[{BytesToHex(buffer)}]", Logger.Type.SecureStream_Receive);
return buffer;
}
public static string BytesToHex(byte[] bytes)
{
return BitConverter.ToString(bytes).Replace("-", "").ToLowerInvariant();
}
public bool SendTo(byte[] buffer, IPEndPoint address)
{
bool result;
logger.Log($"SecureStream.SendTo(byte[] hash: {buffer.GetHashCode()} size: {buffer.Length}, IPEndPoint {address}): Пытаемся отправить зашифрованный пакет UTF8[{Encoding.UTF8.GetString(buffer)}] Hex[{BytesToHex(buffer)}]", Logger.Type.SecureStream_Send);
try
{
result = adapter.SendTo(buffer, address);
}
catch (Exception ex)
{
logger.Log($"SecureStream.SendTo(byte[] hash: {buffer.GetHashCode()} size: {buffer.Length}, IPEndPoint {address}): Ошибка при отправке: {ex.Message}", Logger.Type.SecureStream_Send);
throw new Exception(ex.Message);
}
logger.Log($"SecureStream.SendTo(byte[] hash: {buffer.GetHashCode()} size: {buffer.Length}, IPEndPoint {address}): Зашифрованный пакет {(result ? "" : "не")} отправлен", Logger.Type.SecureStream_Send);
return result;
}
}
}