-
Notifications
You must be signed in to change notification settings - Fork 273
/
Copy pathSendQueue.cs
315 lines (292 loc) · 11.6 KB
/
SendQueue.cs
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// Copyright 2005 Tamir Gal <[email protected]>
// Copyright 2008-2009 Chris Morgan <[email protected]>
// Copyright 2008-2009 Phillip Lemon <[email protected]>
//
// SPDX-License-Identifier: MIT
using PacketDotNet;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using static SharpPcap.LibPcap.PcapUnmanagedStructures;
namespace SharpPcap.LibPcap
{
public class SendQueue : IDisposable
{
public static readonly bool IsHardwareAccelerated = GetIsHardwareAccelerated();
private static bool GetIsHardwareAccelerated()
{
using (var handle = LibPcapSafeNativeMethods.pcap_open_dead(1, 60))
{
try
{
pcap_send_queue queue = default;
LibPcapSafeNativeMethods.pcap_sendqueue_transmit(handle, ref queue, 0);
return true;
}
catch (TypeLoadException)
{
// Function pcap_sendqueue_transmit not found
return false;
}
}
}
private byte[] buffer;
private readonly TimestampResolution TimeResolution;
/// <summary>
/// Number of bytes in the queue that are pending transmission
/// </summary>
public int CurrentLength { get; private set; }
public SendQueue(int memSize, TimestampResolution timeResolution = TimestampResolution.Microsecond)
{
buffer = new byte[memSize];
TimeResolution = timeResolution;
}
/// <summary>
/// Add a packet to this send queue. The PcapHeader defines the packet length.
/// </summary>
/// <param name="header">The pcap header of the packet</param>
/// <param name="packet">The packet bytes to add</param>
/// <returns>True if success, else false</returns>
public bool Add(PcapHeader header, byte[] packet)
{
if (buffer == null)
{
throw new ObjectDisposedException(nameof(SendQueue));
}
var hdrSize = PcapHeader.MemorySize;
var pktSize = (int)header.CaptureLength;
// the header defines the size to send
if (pktSize > packet.Length)
{
var error = string.Format("pcapHdr.CaptureLength of {0} > packet.Length {1}",
pktSize, packet.Length);
throw new InvalidOperationException(error);
}
if (hdrSize + pktSize > buffer.Length - CurrentLength)
{
return false;
}
//Marshal header
IntPtr hdrPtr = header.MarshalToIntPtr(TimeResolution);
Marshal.Copy(hdrPtr, buffer, CurrentLength, hdrSize);
Marshal.FreeHGlobal(hdrPtr);
Buffer.BlockCopy(packet, 0, buffer, CurrentLength + hdrSize, pktSize);
CurrentLength += hdrSize + pktSize;
return true;
}
/// <summary>
/// Send a queue of raw packets to the network.
/// </summary>
/// <param name="device">
/// The device on which to send the queue
/// A <see cref="PcapDevice"/>
/// </param>
/// <param name="synchronized">
/// Should the timestamps be respected
/// </param>
/// <returns>
/// The number of bytes sent as an <see cref="int"/>
/// </returns>
public int Transmit(PcapDevice device, bool synchronized)
{
return Transmit(device, (synchronized == true) ? SendQueueTransmitModes.Synchronized : SendQueueTransmitModes.Normal);
}
/// <summary>
/// Send a queue of raw packets to the network.
/// </summary>
/// <param name="device">
/// The device on which to send the queue
/// A <see cref="PcapDevice"/>
/// </param>
/// <param name="synchronized">
/// Should the timestamps be respected
/// </param>
/// <param name="token">
/// transmission cancellation token
/// </param>
/// <returns>
/// The number of bytes sent as an <see cref="int"/>
/// </returns>
public int Transmit(PcapDevice device, bool synchronized, CancellationToken token)
{
return Transmit(device, (synchronized == true) ? SendQueueTransmitModes.Synchronized : SendQueueTransmitModes.Normal, token);
}
/// <summary>
/// Send a queue of raw packets to the network.
/// </summary>
/// <param name="device">
/// The device on which to send the queue
/// A <see cref="PcapDevice"/>
/// </param>
/// <param name="transmitMode">
/// Should the timestamps be respected
/// </param>
/// <returns>
/// The number of bytes sent as an <see cref="int"/>
/// </returns>
public int Transmit(PcapDevice device, SendQueueTransmitModes transmitMode)
{
return Transmit(device, transmitMode, CancellationToken.None);
}
/// <summary>
/// Send a queue of raw packets to the network.
/// </summary>
/// <param name="device">
/// The device on which to send the queue
/// A <see cref="PcapDevice"/>
/// </param>
/// <param name="transmitMode">
/// Should the timestamps be respected
/// </param>
/// <param name="token">
/// transmission cancellation token
/// </param>
/// <returns>
/// The number of bytes sent as an <see cref="int"/>
/// </returns>
public int Transmit(PcapDevice device, SendQueueTransmitModes transmitMode, CancellationToken token)
{
if (buffer == null)
{
throw new ObjectDisposedException(nameof(SendQueue));
}
if (!device.Opened)
{
throw new DeviceNotReadyException("Can't transmit queue, the pcap device is closed");
}
if (IsHardwareAccelerated && token == CancellationToken.None)
{
return NativeTransmit(device, transmitMode);
}
return ManagedTransmit(device, transmitMode, token);
}
protected unsafe int ManagedTransmit(PcapDevice device, SendQueueTransmitModes transmitMode, CancellationToken token)
{
if (CurrentLength == 0)
{
return 0;
}
var position = 0;
var hdrSize = PcapHeader.MemorySize;
var sw = new Stopwatch();
fixed (byte* buf = buffer)
{
var bufPtr = new IntPtr(buf);
var firstTimestamp = TimeSpan.FromTicks(PcapHeader.FromPointer(bufPtr, TimeResolution).Timeval.Date.Ticks);
while ((position < CurrentLength) && (!token.IsCancellationRequested))
{
// Extract packet from buffer
var header = PcapHeader.FromPointer(bufPtr + position, TimeResolution);
var pktSize = (int)header.CaptureLength;
var p = new ReadOnlySpan<byte>(buffer, position + hdrSize, pktSize);
if (transmitMode == SendQueueTransmitModes.Synchronized)
{
var timestamp = TimeSpan.FromTicks(header.Timeval.Date.Ticks);
var remainingTime = timestamp.Subtract(firstTimestamp);
while (sw.Elapsed < remainingTime)
{
// Wait for packet time
if (remainingTime.TotalMilliseconds > 50)
{
Thread.Yield();
} else
{
Thread.SpinWait(1);
}
}
}
// Send the packet
int res;
unsafe
{
fixed (byte* p_packet = p)
{
res = LibPcapSafeNativeMethods.pcap_sendpacket(device.Handle, new IntPtr(p_packet), p.Length);
}
}
// Start Stopwatch after sending first packet
sw.Start();
if (res < 0)
{
break;
}
position += hdrSize + pktSize;
}
}
return position;
}
protected unsafe int NativeTransmit(PcapDevice device, SendQueueTransmitModes transmitMode)
{
if (CurrentLength == 0)
{
// Npcap does not properly check for 0 packets queue
// See https://github.com/nmap/npcap/issues/287
return 0;
}
int sync = (transmitMode == SendQueueTransmitModes.Synchronized) ? 1 : 0;
fixed (byte* buf = buffer)
{
var pcap_queue = new pcap_send_queue
{
maxlen = (uint)buffer.Length,
len = (uint)CurrentLength,
ptrBuff = new IntPtr(buf)
};
return LibPcapSafeNativeMethods.pcap_sendqueue_transmit(device.Handle, ref pcap_queue, sync);
}
}
public void Dispose()
{
buffer = null;
}
}
public static class SendQueueExtensions
{
/// <summary>
/// Add a packet to this send queue.
/// </summary>
/// <param name="packet">The packet bytes to add</param>
/// <returns>True if success, else false</returns>
public static bool Add(this SendQueue queue, byte[] packet)
{
var header = new PcapHeader(0, 0, (uint)packet.Length, (uint)packet.Length);
return queue.Add(header, packet);
}
/// <summary>
/// Add a packet to this send queue.
/// </summary>
/// <param name="packet">The packet bytes to add</param>
/// <returns>True if success, else false</returns>
public static bool Add(this SendQueue queue, Packet packet)
{
return queue.Add(packet.Bytes);
}
/// <summary>
/// Add a packet to this send queue.
/// </summary>
/// <param name="packet">The packet to add</param>
/// <returns>True if success, else false</returns>
public static bool Add(this SendQueue queue, RawCapture packet)
{
var data = packet.Data;
var timeval = packet.Timeval;
var header = new PcapHeader((uint)timeval.Seconds, (uint)timeval.MicroSeconds,
(uint)data.Length, (uint)data.Length);
return queue.Add(header, data);
}
/// <summary>
/// Add a packet to this send queue.
/// </summary>
/// <param name="packet">The packet to add</param>
/// <param name="seconds">The 'seconds' part of the packet's timestamp</param>
/// <param name="microseconds">The 'microseconds' part of the packet's timestamp</param>
/// <returns>True if success, else false</returns>
public static bool Add(this SendQueue queue, byte[] packet, int seconds, int microseconds)
{
var header = new PcapHeader((uint)seconds, (uint)microseconds,
(uint)packet.Length, (uint)packet.Length);
return queue.Add(header, packet);
}
}
}