This repository has been archived by the owner on Jun 8, 2024. It is now read-only.
forked from alanmcgovern/Mono.Nat
-
Notifications
You must be signed in to change notification settings - Fork 99
/
NatDiscoverer.cs
262 lines (244 loc) · 9.12 KB
/
NatDiscoverer.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
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Open.Nat
{
/// <summary>
///
/// </summary>
public class NatDiscoverer
{
/// <summary>
/// The <see cref="http://msdn.microsoft.com/en-us/library/vstudio/system.diagnostics.tracesource">TraceSource</see> instance
/// used for debugging and <see cref="https://github.com/lontivero/Open.Nat/wiki/Troubleshooting">Troubleshooting</see>
/// </summary>
/// <example>
/// NatUtility.TraceSource.Switch.Level = SourceLevels.Verbose;
/// NatUtility.TraceSource.Listeners.Add(new ConsoleListener());
/// </example>
/// <remarks>
/// At least one trace listener has to be added to the Listeners collection if a trace is required; if no listener is added
/// there will no be tracing to analyse.
/// </remarks>
/// <remarks>
/// Open.NAT only supports SourceLevels.Verbose, SourceLevels.Error, SourceLevels.Warning and SourceLevels.Information.
/// </remarks>
public readonly static TraceSource TraceSource = new TraceSource("Open.NAT");
private static readonly Dictionary<string, NatDevice> Devices = new Dictionary<string, NatDevice>();
// Finalizer is never used however its destructor, that releases the open ports, is invoked by the
// process as part of the shuting down step. So, don't remove it!
private static readonly Finalizer Finalizer = new Finalizer();
internal static readonly Timer RenewTimer = new Timer(RenewMappings, null, 5000, 2000);
/// <summary>
/// Discovers and returns an UPnp or Pmp NAT device; otherwise a <see cref="NatDeviceNotFoundException">NatDeviceNotFoundException</see>
/// exception is thrown after 3 seconds.
/// </summary>
/// <returns>A NAT device</returns>
/// <exception cref="NatDeviceNotFoundException">when no NAT found before 3 seconds.</exception>
#if NET35
public Task<NatDevice> DiscoverDeviceAsync()
{
var cts = new CancellationTokenSource();
cts.CancelAfter(3 * 1000);
return DiscoverDeviceAsync(PortMapper.Pmp | PortMapper.Upnp, cts);
}
#else
public async Task<NatDevice> DiscoverDeviceAsync()
{
var cts = new CancellationTokenSource(3 * 1000);
return await DiscoverDeviceAsync(PortMapper.Pmp | PortMapper.Upnp, cts);
}
#endif
/// <summary>
/// Discovers and returns a NAT device for the specified type; otherwise a <see cref="NatDeviceNotFoundException">NatDeviceNotFoundException</see>
/// exception is thrown when it is cancelled.
/// </summary>
/// <remarks>
/// It allows to specify the NAT type to discover as well as the cancellation token in order.
/// </remarks>
/// <param name="portMapper">Port mapper protocol; Upnp, Pmp or both</param>
/// <param name="cancellationTokenSource">Cancellation token source for cancelling the discovery process</param>
/// <returns>A NAT device</returns>
/// <exception cref="NatDeviceNotFoundException">when no NAT found before cancellation</exception>
#if NET35
public Task<NatDevice> DiscoverDeviceAsync(PortMapper portMapper, CancellationTokenSource cancellationTokenSource)
{
Guard.IsTrue(portMapper.HasFlag(PortMapper.Upnp) || portMapper.HasFlag(PortMapper.Pmp), "portMapper");
Guard.IsNotNull(cancellationTokenSource, "cancellationTokenSource");
return DiscoverAsync(portMapper, true, cancellationTokenSource)
.ContinueWith<NatDevice>(task =>
{
var devices = task.Result;
var device = devices.FirstOrDefault();
if (device == null)
{
TraceSource.LogInfo("Device not found. Common reasons:");
TraceSource.LogInfo("\t* No device is present or,");
TraceSource.LogInfo("\t* Upnp is disabled in the router or");
TraceSource.LogInfo("\t* Antivirus software is filtering SSDP (discovery protocol).");
throw new NatDeviceNotFoundException();
}
return device;
});
}
#else
public async Task<NatDevice> DiscoverDeviceAsync(PortMapper portMapper, CancellationTokenSource cancellationTokenSource)
{
Guard.IsTrue(portMapper.HasFlag(PortMapper.Upnp) || portMapper.HasFlag(PortMapper.Pmp), "portMapper");
Guard.IsNotNull(cancellationTokenSource, "cancellationTokenSource");
var devices = await DiscoverAsync(portMapper, true, cancellationTokenSource);
var device = devices.FirstOrDefault();
if(device==null)
{
TraceSource.LogInfo("Device not found. Common reasons:");
TraceSource.LogInfo("\t* No device is present or,");
TraceSource.LogInfo("\t* Upnp is disabled in the router or");
TraceSource.LogInfo("\t* Antivirus software is filtering SSDP (discovery protocol).");
throw new NatDeviceNotFoundException();
}
return device;
}
#endif
/// <summary>
/// Discovers and returns all NAT devices for the specified type. If no NAT device is found it returns an empty enumerable
/// </summary>
/// <param name="portMapper">Port mapper protocol; Upnp, Pmp or both</param>
/// <param name="cancellationTokenSource">Cancellation token source for cancelling the discovery process</param>
/// <returns>All found NAT devices</returns>
#if NET35
public Task<IEnumerable<NatDevice>> DiscoverDevicesAsync(PortMapper portMapper, CancellationTokenSource cancellationTokenSource)
{
Guard.IsTrue(portMapper.HasFlag(PortMapper.Upnp) || portMapper.HasFlag(PortMapper.Pmp), "portMapper");
Guard.IsNotNull(cancellationTokenSource, "cancellationTokenSource");
return DiscoverAsync(portMapper, false, cancellationTokenSource)
.ContinueWith(t => (IEnumerable<NatDevice>)t.Result.ToArray());
}
#else
public async Task<IEnumerable<NatDevice>> DiscoverDevicesAsync(PortMapper portMapper, CancellationTokenSource cancellationTokenSource)
{
Guard.IsTrue(portMapper.HasFlag(PortMapper.Upnp) || portMapper.HasFlag(PortMapper.Pmp), "portMapper");
Guard.IsNotNull(cancellationTokenSource, "cancellationTokenSource");
var devices = await DiscoverAsync(portMapper, false, cancellationTokenSource);
return devices.ToArray();
}
#endif
#if NET35
private Task<IEnumerable<NatDevice>> DiscoverAsync(PortMapper portMapper, bool onlyOne, CancellationTokenSource cts)
{
TraceSource.LogInfo("Start Discovery");
var searcherTasks = new List<Task<IEnumerable<NatDevice>>>();
if (portMapper.HasFlag(PortMapper.Upnp))
{
var upnpSearcher = new UpnpSearcher(new IPAddressesProvider());
upnpSearcher.DeviceFound += (sender, args) => { if (onlyOne) cts.Cancel(); };
searcherTasks.Add(upnpSearcher.Search(cts.Token));
}
if (portMapper.HasFlag(PortMapper.Pmp))
{
var pmpSearcher = new PmpSearcher(new IPAddressesProvider());
pmpSearcher.DeviceFound += (sender, args) => { if (onlyOne) cts.Cancel(); };
searcherTasks.Add(pmpSearcher.Search(cts.Token));
}
return TaskExtension.WhenAll(searcherTasks.ToArray())
.ContinueWith(t =>
{
TraceSource.LogInfo("Stop Discovery");
var devices = searcherTasks.SelectMany(x => x.Result);
foreach (var device in devices)
{
var key = device.ToString();
NatDevice nat;
if (Devices.TryGetValue(key, out nat))
{
nat.Touch();
}
else
{
Devices.Add(key, device);
}
}
return devices;
});
}
#else
private async Task<IEnumerable<NatDevice>> DiscoverAsync(PortMapper portMapper, bool onlyOne, CancellationTokenSource cts)
{
TraceSource.LogInfo("Start Discovery");
var searcherTasks = new List<Task<IEnumerable<NatDevice>>>();
if(portMapper.HasFlag(PortMapper.Upnp))
{
var upnpSearcher = new UpnpSearcher(new IPAddressesProvider());
upnpSearcher.DeviceFound += (sender, args) => { if (onlyOne) cts.Cancel(); };
searcherTasks.Add(upnpSearcher.Search(cts.Token));
}
if(portMapper.HasFlag(PortMapper.Pmp))
{
var pmpSearcher = new PmpSearcher(new IPAddressesProvider());
pmpSearcher.DeviceFound += (sender, args) => { if (onlyOne) cts.Cancel(); };
searcherTasks.Add(pmpSearcher.Search(cts.Token));
}
await Task.WhenAll(searcherTasks);
TraceSource.LogInfo("Stop Discovery");
var devices = searcherTasks.SelectMany(x => x.Result);
foreach (var device in devices)
{
var key = device.ToString();
NatDevice nat;
if(Devices.TryGetValue(key, out nat))
{
nat.Touch();
}
else
{
Devices.Add(key, device);
}
}
return devices;
}
#endif
/// <summary>
/// Release all ports opened by Open.NAT.
/// </summary>
/// <remarks>
/// If ReleaseOnShutdown value is true, it release all the mappings created through the library.
/// </remarks>
public static void ReleaseAll()
{
foreach (var device in Devices.Values)
{
device.ReleaseAll();
}
}
internal static void ReleaseSessionMappings()
{
foreach (var device in Devices.Values)
{
device.ReleaseSessionMappings();
}
}
private static void RenewMappings(object state)
{
#if NET35
Task.Factory.StartNew(()=>
{
Task task = null;
foreach (var device in Devices.Values)
{
var d = device;
task = (task == null) ? device.RenewMappings() : task.ContinueWith(t => d.RenewMappings());
}
});
#else
Task.Factory.StartNew(async () =>
{
foreach (var device in Devices.Values)
{
await device.RenewMappings();
}
});
#endif
}
}
}