-
Notifications
You must be signed in to change notification settings - Fork 273
/
Copy pathLibPcapLiveDevice.cs
380 lines (339 loc) · 13.8 KB
/
LibPcapLiveDevice.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/*
This file is part of SharpPcap.
SharpPcap is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SharpPcap is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with SharpPcap. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Copyright 2005 Tamir Gal <[email protected]>
* Copyright 2008-2010 Phillip Lemon <[email protected]>
* Copyright 2008-2021 Chris Morgan <[email protected]>
*/
using System;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using System.Text;
namespace SharpPcap.LibPcap
{
/// <summary>
/// Capture live packets from a network device
/// </summary>
public class LibPcapLiveDevice : PcapDevice, ILiveDevice
{
/// <summary>
/// Constructs a new PcapDevice based on a 'pcapIf' struct
/// </summary>
/// <param name="pcapIf">A 'pcapIf' struct representing
/// the pcap device</param>
public LibPcapLiveDevice(PcapInterface pcapIf)
{
m_pcapIf = pcapIf;
}
/// <summary>
/// Default contructor for subclasses
/// </summary>
protected LibPcapLiveDevice()
{
}
/// <summary>
/// PcapDevice finalizer. Ensure PcapDevices are stopped and closed before exit.
/// </summary>
~LibPcapLiveDevice()
{
this.Close();
}
/// <summary>
/// Gets the pcap name of this network device
/// </summary>
public override string Name
{
get { return m_pcapIf.Name; }
}
/// <summary>
/// Addresses that represent this device
/// </summary>
public virtual ReadOnlyCollection<PcapAddress> Addresses
{
get { return new ReadOnlyCollection<PcapAddress>(m_pcapIf.Addresses); }
}
/// <summary>
/// Gets the pcap description of this device
/// </summary>
public override string Description
{
get { return m_pcapIf.Description; }
}
/// <summary>
/// Interface flags, see pcap_findalldevs() man page for more info
/// </summary>
public virtual uint Flags
{
get { return m_pcapIf.Flags; }
}
/// <summary>
/// True if device is a loopback interface, false if not
/// </summary>
public virtual bool Loopback
{
get { return (Flags & Pcap.PCAP_IF_LOOPBACK) == 1; }
}
/// <summary>
/// Open the device. To start capturing call the 'StartCapture' function
/// </summary>
/// <param name="configuration">
/// A <see cref="DeviceConfiguration"/>
/// </param>
public override void Open(DeviceConfiguration configuration)
{
if (Opened)
{
return;
}
var credentials = configuration.Credentials ?? Interface.Credentials;
var mode = configuration.Mode;
// Check if immediate is supported
var immediate_supported = Pcap.LibpcapVersion >= new Version(1, 5, 0);
// Check if we can do immediate by setting mintocopy to 0
// See https://www.tcpdump.org/manpages/pcap_set_immediate_mode.3pcap.html
var mintocopy_supported =
#if NET6_0_OR_GREATER
OperatingSystem.IsWindows()
#else
RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
#endif
;
var errbuf = new StringBuilder(Pcap.PCAP_ERRBUF_SIZE); //will hold errors
// set the StopCaptureTimeout value to twice the read timeout to ensure that
// we wait long enough before considering the capture thread to be stuck when stopping
// a background capture via StopCapture()
//
// NOTE: Doesn't affect Mono if unix poll is available, doesn't affect Linux because
// Linux devices have no timeout, they always block. Only affects Windows devices.
StopCaptureTimeout = new TimeSpan(0, 0, 0, 0, configuration.ReadTimeout * 2);
// modes other than OpenFlags.Promiscuous require pcap_open()
var otherModes = mode & ~DeviceModes.Promiscuous;
if (immediate_supported || mintocopy_supported)
{
// We can do MaxResponsiveness through Immediate mode
otherModes &= ~DeviceModes.MaxResponsiveness;
}
var immediateMode = configuration.Immediate;
if (mode.HasFlag(DeviceModes.MaxResponsiveness))
{
immediateMode = true;
}
// Some configurations can only be used with pcap_create
var use_pcap_create = credentials == null && (short)otherModes == 0;
if (use_pcap_create)
{
Handle = LibPcapSafeNativeMethods.pcap_create(
Name, // name of the device
errbuf); // error buffer
if (Handle.IsInvalid)
{
var err = $"Unable to open the adapter '{Name}'. {errbuf}";
throw new PcapException(err);
}
// Those are configurations that pcap_open can handle differently
Configure(
configuration, nameof(configuration.Snaplen),
LibPcapSafeNativeMethods.pcap_set_snaplen, configuration.Snaplen
);
Configure(
configuration, "Promiscuous",
LibPcapSafeNativeMethods.pcap_set_promisc, (int)(mode & DeviceModes.Promiscuous)
);
Configure(
configuration, nameof(configuration.ReadTimeout),
LibPcapSafeNativeMethods.pcap_set_timeout, configuration.ReadTimeout
);
}
else
{
// We got authentication, so this is an rpcap device
var auth = RemoteAuthentication.CreateAuth(credentials);
// Immediate and MaxResponsiveness are the same thing
if (immediateMode == true)
{
mode |= DeviceModes.MaxResponsiveness;
}
// No need to worry about it anymore
immediateMode = null;
try
{
Handle = LibPcapSafeNativeMethods.pcap_open(
Name, // name of the device
configuration.Snaplen, // portion of the packet to capture.
(short)mode, // flags
(short)configuration.ReadTimeout, // read timeout
ref auth, // authentication
errbuf); // error buffer
}
catch (TypeLoadException)
{
var reason = credentials != null ? "Remote PCAP" : "Requested DeviceModes";
var err = $"Unable to open the adapter '{Name}'. {reason} not supported";
throw new PcapException(err, PcapError.PlatformNotSupported);
}
}
if (Handle.IsInvalid)
{
var err = $"Unable to open the adapter '{Name}'. {errbuf}";
throw new PcapException(err);
}
ConfigureIfCompatible(use_pcap_create,
configuration, nameof(configuration.TimestampResolution),
LibPcapSafeNativeMethods.pcap_set_tstamp_precision, (int?)configuration.TimestampResolution
);
ConfigureIfCompatible(use_pcap_create,
configuration, nameof(configuration.TimestampType),
LibPcapSafeNativeMethods.pcap_set_tstamp_type, (int?)configuration.TimestampType
);
ConfigureIfCompatible(use_pcap_create,
configuration, nameof(configuration.Monitor),
LibPcapSafeNativeMethods.pcap_set_rfmon, (int?)configuration.Monitor
);
ConfigureIfCompatible(use_pcap_create,
configuration, nameof(configuration.BufferSize),
LibPcapSafeNativeMethods.pcap_set_buffer_size, configuration.BufferSize
);
if (immediateMode.HasValue)
{
if (!immediate_supported && !mintocopy_supported)
{
configuration.RaiseConfigurationFailed(
nameof(configuration.Immediate),
PcapError.PlatformNotSupported,
"Immediate mode not available"
);
}
else if (immediate_supported)
{
var immediate = immediateMode.Value ? 1 : 0;
Configure(
configuration, nameof(configuration.Immediate),
LibPcapSafeNativeMethods.pcap_set_immediate_mode, immediate
);
}
}
// pcap_open returns an already activated device
if (use_pcap_create)
{
var activationResult = LibPcapSafeNativeMethods.pcap_activate(Handle);
if (activationResult < 0)
{
string err = "Unable to activate the adapter (" + Name + ").";
throw new PcapException(err, activationResult);
}
}
base.Open(configuration);
// retrieve the file descriptor of the adapter for use with poll()
if (
#if NET6_0_OR_GREATER
OperatingSystem.IsLinux()
#else
RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
#endif
)
{
FileDescriptor = LibPcapSafeNativeMethods.pcap_get_selectable_fd(Handle);
}
// Below configurations must be done after the device gets activated
Configure(
configuration, nameof(configuration.KernelBufferSize),
LibPcapSafeNativeMethods.pcap_setbuff, configuration.KernelBufferSize
);
if (immediateMode == true && mintocopy_supported && !immediate_supported)
{
Configure(
configuration, nameof(configuration.Immediate),
LibPcapSafeNativeMethods.pcap_setmintocopy, 0
);
}
Configure(
configuration, nameof(configuration.MinToCopy),
LibPcapSafeNativeMethods.pcap_setmintocopy, configuration.MinToCopy
);
}
private const int disableBlocking = 0;
private const int enableBlocking = 1;
/// <summary>
/// Set/Get Non-Blocking Mode. returns allways false for savefiles.
/// </summary>
public bool NonBlockingMode
{
get
{
ThrowIfNotOpen("Can't get blocking mode, the device is closed");
var errbuf = new StringBuilder(Pcap.PCAP_ERRBUF_SIZE); //will hold errors
int ret = LibPcapSafeNativeMethods.pcap_getnonblock(Handle, errbuf);
// Errorbuf is only filled when ret = -1
if (ret == -1)
{
string err = "Unable to set get blocking" + errbuf.ToString();
throw new PcapException(err);
}
if (ret == enableBlocking)
return true;
return false;
}
set
{
ThrowIfNotOpen("Can't set blocking mode, the device is closed");
var errbuf = new StringBuilder(Pcap.PCAP_ERRBUF_SIZE); //will hold errors
int block = disableBlocking;
if (value)
block = enableBlocking;
int ret = LibPcapSafeNativeMethods.pcap_setnonblock(Handle, block, errbuf);
// Errorbuf is only filled when ret = -1
if (ret == -1)
{
string err = "Unable to set non blocking" + errbuf.ToString();
throw new PcapException(err);
}
}
}
/// <summary>
/// Sends a raw packet through this device
/// </summary>
/// <param name="p">The packet bytes to send</param>
public void SendPacket(ReadOnlySpan<byte> p, ICaptureHeader header = null)
{
ThrowIfNotOpen("Can't send packet, the device is closed");
int res;
unsafe
{
fixed (byte* p_packet = p)
{
res = LibPcapSafeNativeMethods.pcap_sendpacket(Handle, new IntPtr(p_packet), p.Length);
}
}
if (res < 0)
{
throw new PcapException("Can't send packet: " + LastError);
}
}
/// <summary>
/// Retrieves pcap statistics
/// </summary>
/// <returns>
/// A <see cref="PcapStatistics"/>
/// </returns>
public override ICaptureStatistics Statistics
{
get
{
// can only call PcapStatistics on an open device
ThrowIfNotOpen("device not open");
return new PcapStatistics(Handle);
}
}
}
}