~ruther/NosSmooth

ref: 8c094d4604a7c0834cde6c821592beafb844fe0c NosSmooth/Pcap/NosSmooth.Pcap/PcapNostaleManager.cs -rw-r--r-- 7.5 KiB
8c094d46 — Rutherther feat(pcap): delete only not seen connections 2 years ago
                                                                                
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
//
//  PcapNostaleManager.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using PacketDotNet;
using SharpPcap;
using SharpPcap.LibPcap;

namespace NosSmooth.Pcap;

/// <summary>
/// Captures packets, distributes them to Pcap clients.
/// </summary>
public class PcapNostaleManager
{
    private readonly ILogger<PcapNostaleManager> _logger;
    private readonly PcapNostaleOptions _options;
    private readonly ConcurrentDictionary<TcpConnection, ConnectionData> _connections;
    private readonly ConcurrentDictionary<TcpConnection, PcapNostaleClient> _clients;
    private Task? _deletionTask;
    private CancellationTokenSource? _deletionTaskCancellationSource;
    private int _clientsCount;
    private bool _started;

    /// <summary>
    /// Initializes a new instance of the <see cref="PcapNostaleManager"/> class.
    /// </summary>
    /// <param name="logger">The logger.</param>
    /// <param name="options">The options.</param>
    public PcapNostaleManager(ILogger<PcapNostaleManager> logger, IOptions<PcapNostaleOptions> options)
    {
        _logger = logger;
        _options = options.Value;
        _connections = new ConcurrentDictionary<TcpConnection, ConnectionData>();
        _clients = new ConcurrentDictionary<TcpConnection, PcapNostaleClient>();
    }

    /// <summary>
    /// Add a pcap client.
    /// </summary>
    internal void AddClient()
    {
        var count = Interlocked.Increment(ref _clientsCount);

        if (count == 1)
        {
            StartCapturing();
        }
    }

    /// <summary>
    /// Remove a pcap client.
    /// </summary>
    /// <remarks>
    /// When no clients are left, packet capture will be stopped.
    /// </remarks>
    internal void RemoveClient()
    {
        var count = Interlocked.Decrement(ref _clientsCount);

        if (count == 0)
        {
            Stop();
        }
    }

    /// <summary>
    /// Associate the given connection with the given client.
    /// </summary>
    /// <param name="connection">The connection to associate.</param>
    /// <param name="client">The client to associate the connection with.</param>
    internal void RegisterConnection(TcpConnection connection, PcapNostaleClient client)
    {
        _clients.AddOrUpdate(connection, (c) => client, (c1, c2) => client);

        if (_connections.TryGetValue(connection, out var data))
        {
            foreach (var sniffedPacket in data.SniffedData)
            {
                client.OnPacketArrival(null, connection, sniffedPacket);
            }
        }
    }

    /// <summary>
    /// Disassociate the given connection.
    /// </summary>
    /// <param name="connection">The connection to disassociate.</param>
    internal void UnregisterConnection(TcpConnection connection)
    {
        _clients.TryRemove(connection, out _);
    }

    private void Stop()
    {
        if (!_started)
        {
            return;
        }

        _started = false;
        foreach (var device in LibPcapLiveDeviceList.Instance)
        {
            device.StopCapture();
        }

        var task = _deletionTask;
        _deletionTask = null;

        _deletionTaskCancellationSource?.Cancel();
        _deletionTaskCancellationSource?.Dispose();
        _deletionTaskCancellationSource = null;

        task?.GetAwaiter().GetResult();
        task?.Dispose();
        _connections.Clear();
        _clients.Clear();
    }

    /// <summary>
    /// Start capturing packets from all devices.
    /// </summary>
    public void StartCapturing()
    {
        if (_started)
        {
            return;
        }

        _started = true;
        _deletionTaskCancellationSource = new CancellationTokenSource();
        _deletionTask = Task.Run(() => DeletionTask(_deletionTaskCancellationSource.Token));

        foreach (var device in LibPcapLiveDeviceList.Instance)
        {
            if (!device.Opened)
            {
                device.Open();
            }

            device.Filter = "ip and tcp";
            device.OnPacketArrival += DeviceOnOnPacketArrival;
            device.StartCapture();
        }
    }

    private void DeviceOnOnPacketArrival(object sender, PacketCapture e)
    {
        try
        {
            DeviceOnPacketArrivalInner(e);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "OnPacketArrival has produced an exception");
        }
    }

    private void DeviceOnPacketArrivalInner(PacketCapture e)
    {
        var rawPacket = e.GetPacket();
        var packet = PacketDotNet.Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data);

        var tcpPacket = packet.Extract<PacketDotNet.TcpPacket>();
        if (tcpPacket is null)
        {
            return;
        }

        if (!tcpPacket.HasPayloadData || tcpPacket.PayloadData.Length == 0)
        {
            return;
        }

        var ipPacket = (PacketDotNet.IPPacket)tcpPacket.ParentPacket;
        System.Net.IPAddress srcIp = ipPacket.SourceAddress;
        System.Net.IPAddress dstIp = ipPacket.DestinationAddress;
        int srcPort = tcpPacket.SourcePort;
        int dstPort = tcpPacket.DestinationPort;

        var tcpConnection = new TcpConnection(srcIp.Address, srcPort, dstIp.Address, dstPort);

        if (!_connections.ContainsKey(tcpConnection))
        {
            _connections.TryAdd
            (
                tcpConnection,
                new ConnectionData
                (
                    srcIp,
                    srcPort,
                    dstIp,
                    dstPort,
                    new List<byte[]>(),
                    DateTimeOffset.Now
                )
            );
        }

        var data = _connections[tcpConnection];
        data.LastReceivedAt = DateTimeOffset.Now;
        if (data.SniffedData.Count < 5 && tcpPacket.PayloadData.Length < 500
            && data.FirstObservedAt.AddMilliseconds(_options.CleanSniffedDataInterval) > DateTimeOffset.Now)
        {
            data.SniffedData.Add(tcpPacket.PayloadData);
        }

        if (_clients.TryGetValue(tcpConnection, out var client))
        {
            client.OnPacketArrival((LibPcapLiveDevice)e.Device, tcpConnection, tcpPacket.PayloadData);
        }
    }

    private async Task DeletionTask(CancellationToken ct)
    {
        while (!ct.IsCancellationRequested)
        {
            try
            {
                DeleteData();
                await Task.Delay(TimeSpan.FromMilliseconds(_options.CleanSniffedDataInterval * 3), ct);
            }
            catch (OperationCanceledException)
            {
                // ignored
            }
            catch (Exception e)
            {
                _logger.LogError(e, "The pcap manager deletion task has thrown an exception");
            }
        }
    }

    private void DeleteData()
    {
        foreach (var connectionData in _connections)
        {
            if (connectionData.Value.FirstObservedAt.AddMilliseconds
                    (_options.ForgetConnectionInterval) < DateTimeOffset.Now)
            {
                _connections.TryRemove(connectionData);
            }

            if (connectionData.Value.SniffedData.Count > 0 && connectionData.Value.LastReceivedAt.AddMilliseconds
                    (_options.CleanSniffedDataInterval) < DateTimeOffset.Now)
            {
                connectionData.Value.SniffedData.Clear();
            }
        }
    }
}
Do not follow this link