-
-
Notifications
You must be signed in to change notification settings - Fork 114
/
Copy pathDhcpServer.cs
326 lines (285 loc) · 12.9 KB
/
DhcpServer.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Iot.Device.DhcpServer.Enums;
namespace Iot.Device.DhcpServer
{
/// <summary>
/// A DHCP Server class.
/// </summary>
public class DhcpServer : IDisposable
{
// Constants
private const int DhcpPort = 67;
private const int DhcpClientPort = 68;
private static Socket _dhcplistener;
private static Socket _sender;
private ArrayList _dhcpIpList;
private ArrayList _dhcpHardwareAddressList;
private ArrayList _dhcpLastRequest;
private Thread _dhcpServerThread;
private bool _islistening;
private IPAddress _ipAddress;
private IPAddress _mask;
private Timer _timer;
private ushort _timeToLeave;
/// <summary>
/// Gets or sets the captive portal URL. If null or empty, this will be ignored.
/// </summary>
public string CaptivePortalUrl { get; set; }
/// <summary>
/// Starts the DHCP Server to start listning.
/// </summary>
/// <returns>Returns false in case of error.</returns>
/// <param name="address">The server IP address.</param>
/// <param name="mask">The mask used for distributing the IP addess.</param>
/// <param name="timeToLeave">Default time to leave for bail expiration.</param>
/// <exception cref="SocketException">Socket exception occurred.</exception>
/// <exception cref="Exception">An exception occured while setting up the DHCP listner or sender.</exception>
public bool Start(IPAddress address, IPAddress mask, ushort timeToLeave = 1200)
{
if (_dhcplistener == null)
{
try
{
// listen socket
_dhcplistener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress dsip = new IPAddress(0xFFFFFFFF);
IPEndPoint ep = new IPEndPoint(dsip, DhcpPort);
_dhcplistener.Bind(ep);
_ipAddress = address;
_mask = mask;
// send socket
_sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_sender.Bind(new IPEndPoint(_ipAddress, 0));
_sender.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.Broadcast, true);
_sender.Connect(new IPEndPoint(IPAddress.Parse("255.255.255.255"), DhcpClientPort));
// make a dynamic ip pool
_dhcpIpList = new ArrayList();
_dhcpIpList.Add(_ipAddress);
_dhcpHardwareAddressList = new ArrayList();
_dhcpHardwareAddressList.Add("ESP32");
_dhcpLastRequest = new ArrayList();
// This one never ever expires
_dhcpLastRequest.Add(DateTime.MaxValue);
_timeToLeave = timeToLeave;
_timer = new Timer(CheckAndCleanList, null, timeToLeave * 1000, timeToLeave * 1000);
// start server thread
_dhcpServerThread = new Thread(RunServer);
_dhcpServerThread.Start();
return true;
}
catch (SocketException ex)
{
Debug.WriteLine($"DHCP: ** Socket exception occurred: {ex.Message} error code {ex.ErrorCode}!**");
}
catch (Exception ex)
{
Debug.WriteLine($"DHCP: ** Exception occurred: {ex.Message}!**");
}
return false;
}
// It's already started
return true;
}
private void CheckAndCleanList(object state)
{
ArrayList toRemove = new ArrayList();
for (int i = 0; i < _dhcpLastRequest.Count; i++)
{
if ((DateTime)_dhcpLastRequest[i] < DateTime.UtcNow)
{
toRemove.Add(i);
}
}
foreach (int val in toRemove)
{
_dhcpIpList.RemoveAt(val);
_dhcpHardwareAddressList.RemoveAt(val);
_dhcpLastRequest.RemoveAt(val);
}
}
/// <summary>
/// Stops the listening.
/// </summary>
public void Stop()
{
_islistening = false;
}
private void RunServer()
{
_islistening = true;
// setup buffer to read data from socket
byte[] buffer = new byte[1024];
while (_islistening)
{
try
{
// check if socket have any bytes to read
int bytes = _dhcplistener.Available;
if (bytes > 0)
{
bytes = _dhcplistener.Receive(buffer);
// Uncomment to get some debug information
// Debug.WriteLine($"DHCP: Have {bytes} bytes");
// Debug.WriteLine($"DHCP: <- Read {bytes} bytes from {(IPEndPoint)_dhcplistener.LocalEndPoint}");
// we have data!
// output as string for debug, uncomment below:
// Debug.WriteLine(BitConverter.ToString(buffer, 0, bytes));
DhcpMessage dhcpReq = new DhcpMessage();
dhcpReq.Parse(ref buffer);
string sname = dhcpReq.HostName;
string macAddress = BitConverter.ToString(dhcpReq.ClientHardwareAddress, 0, dhcpReq.ClientHardwareAddress.Length);
switch (dhcpReq.DhcpMessageType)
{
case DhcpMessageType.Discover:
if (_dhcpIpList.Count > 254)
{
// No more available IP Address
break;
}
byte[] yourIp;
// Do we have an option asking for a specific IP address?
var reqIp = dhcpReq.RequestedIpAddress;
if (reqIp != new IPAddress(0))
{
// We do have a request for an IP, maybe it was connected before
if (_dhcpIpList.Contains(reqIp))
{
yourIp = reqIp.GetAddressBytes();
}
else
{
yourIp = GetFirstAvailableIp();
}
}
else
{
yourIp = GetFirstAvailableIp();
}
// Uncomment to get debug information
// Debug.WriteLine(BitConverter.ToString(offer, 0, offer.Length));
Debug.WriteLine($"DHCP: Discover from host: {sname}");
dhcpReq.SecondsElapsed = _timeToLeave;
var offer = dhcpReq.Offer(new IPAddress(yourIp), _mask, _ipAddress, GetAdditionalOptions());
_sender.Send(offer);
break;
case DhcpMessageType.Request:
// Check the request is for us
var dhcpRequsted = dhcpReq.GetOption(DhcpOptionCode.DhcpAddress);
if ((dhcpRequsted != null) && (dhcpRequsted.ToString() != _ipAddress.GetAddressBytes().ToString()))
{
// Not for us
break;
}
// Uncomment to get debug information
Debug.WriteLine($"DHCP: Request from host: {sname}");
Debug.WriteLine($"DHCP Request: Requested address {dhcpReq.RequestedIpAddress}");
Debug.WriteLine($"DHCP Request: Server Identifier {dhcpReq.DhcpAddress}");
if (!_dhcpIpList.Contains(dhcpReq.RequestedIpAddress))
{
_dhcpIpList.Add(dhcpReq.RequestedIpAddress);
_dhcpHardwareAddressList.Add(macAddress);
_dhcpLastRequest.Add(DateTime.UtcNow);
}
else
{
// Find the requested address in the list
int inc;
for (inc = 0; inc < _dhcpIpList.Count; inc++)
{
if (((IPAddress)_dhcpIpList[inc]).ToString() == dhcpReq.RequestedIpAddress.ToString())
{
break;
}
}
// Check if the hardware address is the same
if ((string)_dhcpHardwareAddressList[inc] == macAddress)
{
_dhcpLastRequest[inc] = DateTime.UtcNow;
}
else
{
// In this case make a Nack
_sender.Send(dhcpReq.NotAcknoledge());
break;
}
}
// Finaly send the acknoledge
_sender.Send(dhcpReq.Acknoledge(dhcpReq.RequestedIpAddress, _mask, _ipAddress, GetAdditionalOptions()));
// Uncommment to see the buffer:
// Debug.WriteLine(BitConverter.ToString(buffer, 0, bytes));
break;
default:
Debug.WriteLine($"DHCP: not handled ({dhcpReq.DhcpMessageType}) from host: {sname}");
break;
}
}
else
{
// free cpu time if no bytes in socket
Thread.Sleep(200);
}
}
catch
{
//// Just pass this, we want to make sure that this loop always works properly.
}
}
try
{
_dhcplistener.Close();
_sender.Close();
}
catch
{
//// Make sure we catch everything coming in
}
_dhcplistener = null;
_sender = null;
Debug.WriteLine($"DHCP: stoped");
}
private byte[] GetAdditionalOptions()
{
byte[] additionalOptions = null;
if (!string.IsNullOrEmpty(CaptivePortalUrl))
{
var encoded = Encoding.UTF8.GetBytes(CaptivePortalUrl);
additionalOptions = new byte[2 + encoded.Length];
additionalOptions[0] = (byte)DhcpOptionCode.CaptivePortal;
additionalOptions[1] = (byte)CaptivePortalUrl.Length;
encoded.CopyTo(additionalOptions, 2);
}
return additionalOptions;
}
private byte[] GetFirstAvailableIp()
{
// increment dynamic ip
byte[] yourIp = ((IPAddress)_dhcpIpList[0]).GetAddressBytes();
foreach (IPAddress ip in _dhcpIpList)
{
yourIp[3]++;
if (ip.GetAddressBytes()[3] == yourIp[3])
{
yourIp[3]++;
}
if (yourIp[3] == 255)
{
yourIp[3] = 1;
}
}
return yourIp;
}
/// <inheritdoc/>
public void Dispose()
{
Stop();
}
}
}