DhcpServer.cs 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2020 Shreyas Zare (shreyas@technitium.com)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. using DnsServerCore.Dhcp.Options;
  16. using DnsServerCore.Dns.ZoneManagers;
  17. using DnsServerCore.Dns.Zones;
  18. using System;
  19. using System.Collections.Concurrent;
  20. using System.Collections.Generic;
  21. using System.IO;
  22. using System.Net;
  23. using System.Net.Sockets;
  24. using System.Threading;
  25. using System.Threading.Tasks;
  26. using TechnitiumLibrary.Net;
  27. using TechnitiumLibrary.Net.Dns;
  28. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  29. namespace DnsServerCore.Dhcp
  30. {
  31. //Dynamic Host Configuration Protocol
  32. //https://tools.ietf.org/html/rfc2131
  33. //DHCP Options and BOOTP Vendor Extensions
  34. //https://tools.ietf.org/html/rfc2132
  35. //Encoding Long Options in the Dynamic Host Configuration Protocol (DHCPv4)
  36. //https://tools.ietf.org/html/rfc3396
  37. //Client Fully Qualified Domain Name(FQDN) Option
  38. //https://tools.ietf.org/html/rfc4702
  39. public sealed class DhcpServer : IDisposable
  40. {
  41. #region enum
  42. enum ServiceState
  43. {
  44. Stopped = 0,
  45. Starting = 1,
  46. Running = 2,
  47. Stopping = 3
  48. }
  49. #endregion
  50. #region variables
  51. readonly string _scopesFolder;
  52. LogManager _log;
  53. readonly ConcurrentDictionary<IPAddress, UdpListener> _udpListeners = new ConcurrentDictionary<IPAddress, UdpListener>();
  54. readonly ConcurrentDictionary<string, Scope> _scopes = new ConcurrentDictionary<string, Scope>();
  55. AuthZoneManager _authZoneManager;
  56. volatile ServiceState _state = ServiceState.Stopped;
  57. readonly IPEndPoint _dhcpDefaultEP = new IPEndPoint(IPAddress.Any, 67);
  58. Timer _maintenanceTimer;
  59. const int MAINTENANCE_TIMER_INTERVAL = 10000;
  60. DateTime _lastModifiedScopesSavedOn;
  61. #endregion
  62. #region constructor
  63. public DhcpServer(string scopesFolder, LogManager log = null)
  64. {
  65. _scopesFolder = scopesFolder;
  66. _log = log;
  67. if (!Directory.Exists(_scopesFolder))
  68. {
  69. Directory.CreateDirectory(_scopesFolder);
  70. //create default scope
  71. Scope scope = new Scope("Default", false, IPAddress.Parse("192.168.1.1"), IPAddress.Parse("192.168.1.254"), IPAddress.Parse("255.255.255.0"));
  72. scope.Exclusions = new Exclusion[] { new Exclusion(IPAddress.Parse("192.168.1.1"), IPAddress.Parse("192.168.1.10")) };
  73. scope.RouterAddress = IPAddress.Parse("192.168.1.1");
  74. scope.UseThisDnsServer = true;
  75. scope.DomainName = "local";
  76. scope.LeaseTimeDays = 7;
  77. SaveScopeFile(scope);
  78. }
  79. }
  80. #endregion
  81. #region IDisposable
  82. private bool _disposed = false;
  83. private void Dispose(bool disposing)
  84. {
  85. if (_disposed)
  86. return;
  87. if (disposing)
  88. {
  89. Stop();
  90. if (_maintenanceTimer != null)
  91. _maintenanceTimer.Dispose();
  92. SaveModifiedScopes();
  93. }
  94. _disposed = true;
  95. }
  96. public void Dispose()
  97. {
  98. Dispose(true);
  99. }
  100. #endregion
  101. #region private
  102. private void ReadUdpRequestAsync(object parameter)
  103. {
  104. Socket udpListener = parameter as Socket;
  105. EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
  106. byte[] recvBuffer = new byte[576];
  107. int bytesRecv;
  108. try
  109. {
  110. bool processOnlyUnicastMessages = !(udpListener.LocalEndPoint as IPEndPoint).Address.Equals(IPAddress.Any); //only 0.0.0.0 ip should process broadcast to avoid duplicate offers on Windows
  111. while (true)
  112. {
  113. SocketFlags flags = SocketFlags.None;
  114. IPPacketInformation ipPacketInformation;
  115. try
  116. {
  117. bytesRecv = udpListener.ReceiveMessageFrom(recvBuffer, 0, recvBuffer.Length, ref flags, ref remoteEP, out ipPacketInformation);
  118. }
  119. catch (SocketException ex)
  120. {
  121. switch (ex.SocketErrorCode)
  122. {
  123. case SocketError.ConnectionReset:
  124. case SocketError.HostUnreachable:
  125. case SocketError.MessageSize:
  126. case SocketError.NetworkReset:
  127. bytesRecv = 0;
  128. break;
  129. default:
  130. throw;
  131. }
  132. }
  133. if (bytesRecv > 0)
  134. {
  135. if (processOnlyUnicastMessages && ipPacketInformation.Address.Equals(IPAddress.Broadcast))
  136. continue;
  137. try
  138. {
  139. DhcpMessage request = new DhcpMessage(new MemoryStream(recvBuffer, 0, bytesRecv, false));
  140. _ = ProcessDhcpRequestAsync(request, remoteEP as IPEndPoint, ipPacketInformation, udpListener);
  141. }
  142. catch (Exception ex)
  143. {
  144. LogManager log = _log;
  145. if (log != null)
  146. log.Write(remoteEP as IPEndPoint, ex);
  147. }
  148. }
  149. }
  150. }
  151. catch (ObjectDisposedException)
  152. {
  153. //socket disposed
  154. }
  155. catch (SocketException ex)
  156. {
  157. switch (ex.SocketErrorCode)
  158. {
  159. case SocketError.Interrupted:
  160. break; //server stopping
  161. default:
  162. LogManager log = _log;
  163. if (log != null)
  164. log.Write(remoteEP as IPEndPoint, ex);
  165. throw;
  166. }
  167. }
  168. catch (Exception ex)
  169. {
  170. if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
  171. return; //server stopping
  172. LogManager log = _log;
  173. if (log != null)
  174. log.Write(remoteEP as IPEndPoint, ex);
  175. throw;
  176. }
  177. }
  178. private async Task ProcessDhcpRequestAsync(DhcpMessage request, IPEndPoint remoteEP, IPPacketInformation ipPacketInformation, Socket udpListener)
  179. {
  180. try
  181. {
  182. DhcpMessage response = await ProcessDhcpMessageAsync(request, remoteEP, ipPacketInformation);
  183. //send response
  184. if (response != null)
  185. {
  186. byte[] sendBuffer = new byte[1024];
  187. MemoryStream sendBufferStream = new MemoryStream(sendBuffer);
  188. response.WriteTo(sendBufferStream);
  189. //send dns datagram
  190. if (!request.RelayAgentIpAddress.Equals(IPAddress.Any))
  191. {
  192. //received request via relay agent so send unicast response to relay agent on port 67
  193. await udpListener.SendToAsync(sendBuffer, 0, (int)sendBufferStream.Position, new IPEndPoint(request.RelayAgentIpAddress, 67));
  194. }
  195. else if (!request.ClientIpAddress.Equals(IPAddress.Any))
  196. {
  197. //client is already configured and renewing lease so send unicast response on port 68
  198. await udpListener.SendToAsync(sendBuffer, 0, (int)sendBufferStream.Position, new IPEndPoint(request.ClientIpAddress, 68));
  199. }
  200. else
  201. {
  202. Socket udpSocket;
  203. //send response as broadcast on port 68 on appropriate interface bound socket
  204. if (_udpListeners.TryGetValue(response.NextServerIpAddress, out UdpListener listener))
  205. udpSocket = listener.Socket; //found scope specific socket
  206. else
  207. udpSocket = udpListener; //no appropriate socket found so use default socket
  208. await udpSocket.SendToAsync(sendBuffer, 0, (int)sendBufferStream.Position, new IPEndPoint(IPAddress.Broadcast, 68), SocketFlags.DontRoute); //no routing for broadcast
  209. }
  210. }
  211. }
  212. catch (ObjectDisposedException)
  213. {
  214. //socket disposed
  215. }
  216. catch (Exception ex)
  217. {
  218. if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
  219. return; //server stopping
  220. LogManager log = _log;
  221. if (log != null)
  222. log.Write(remoteEP, ex);
  223. }
  224. }
  225. private async Task<DhcpMessage> ProcessDhcpMessageAsync(DhcpMessage request, IPEndPoint remoteEP, IPPacketInformation ipPacketInformation)
  226. {
  227. if (request.OpCode != DhcpMessageOpCode.BootRequest)
  228. return null;
  229. switch (request.DhcpMessageType?.Type)
  230. {
  231. case DhcpMessageType.Discover:
  232. {
  233. Scope scope = FindScope(request, remoteEP.Address, ipPacketInformation);
  234. if (scope == null)
  235. return null; //no scope available; do nothing
  236. if (scope.OfferDelayTime > 0)
  237. await Task.Delay(scope.OfferDelayTime); //delay sending offer
  238. Lease offer = scope.GetOffer(request);
  239. if (offer == null)
  240. return null; //no offer available, do nothing
  241. IPAddress serverIdentifierAddress = scope.InterfaceAddress.Equals(IPAddress.Any) ? ipPacketInformation.Address : scope.InterfaceAddress;
  242. List<DhcpOption> options = scope.GetOptions(request, serverIdentifierAddress);
  243. if (options == null)
  244. return null;
  245. //log ip offer
  246. LogManager log = _log;
  247. if (log != null)
  248. log.Write(remoteEP, "DHCP Server offered IP address [" + offer.Address.ToString() + "] to " + request.GetClientFullIdentifier() + ".");
  249. return new DhcpMessage(request, offer.Address, serverIdentifierAddress, options);
  250. }
  251. case DhcpMessageType.Request:
  252. {
  253. //request ip address lease or extend existing lease
  254. Scope scope = FindScope(request, remoteEP.Address, ipPacketInformation);
  255. if (scope == null)
  256. return null; //no scope available; do nothing
  257. IPAddress serverIdentifierAddress = scope.InterfaceAddress.Equals(IPAddress.Any) ? ipPacketInformation.Address : scope.InterfaceAddress;
  258. Lease leaseOffer;
  259. if (request.ServerIdentifier == null)
  260. {
  261. if (request.RequestedIpAddress == null)
  262. {
  263. //renewing or rebinding
  264. if (request.ClientIpAddress.Equals(IPAddress.Any))
  265. return null; //client must set IP address in ciaddr; do nothing
  266. leaseOffer = scope.GetExistingLeaseOrOffer(request);
  267. if (leaseOffer == null)
  268. {
  269. //no existing lease or offer available for client
  270. //send nak
  271. return new DhcpMessage(request, IPAddress.Any, IPAddress.Any, new DhcpOption[] { new DhcpMessageTypeOption(DhcpMessageType.Nak), new ServerIdentifierOption(scope.InterfaceAddress), DhcpOption.CreateEndOption() });
  272. }
  273. if (!request.ClientIpAddress.Equals(leaseOffer.Address))
  274. {
  275. //client ip is incorrect
  276. //send nak
  277. return new DhcpMessage(request, IPAddress.Any, IPAddress.Any, new DhcpOption[] { new DhcpMessageTypeOption(DhcpMessageType.Nak), new ServerIdentifierOption(scope.InterfaceAddress), DhcpOption.CreateEndOption() });
  278. }
  279. }
  280. else
  281. {
  282. //init-reboot
  283. leaseOffer = scope.GetExistingLeaseOrOffer(request);
  284. if (leaseOffer == null)
  285. {
  286. //no existing lease or offer available for client
  287. //send nak
  288. return new DhcpMessage(request, IPAddress.Any, IPAddress.Any, new DhcpOption[] { new DhcpMessageTypeOption(DhcpMessageType.Nak), new ServerIdentifierOption(scope.InterfaceAddress), DhcpOption.CreateEndOption() });
  289. }
  290. if (!request.RequestedIpAddress.Address.Equals(leaseOffer.Address))
  291. {
  292. //the client's notion of its IP address is not correct - RFC 2131
  293. //send nak
  294. return new DhcpMessage(request, IPAddress.Any, IPAddress.Any, new DhcpOption[] { new DhcpMessageTypeOption(DhcpMessageType.Nak), new ServerIdentifierOption(scope.InterfaceAddress), DhcpOption.CreateEndOption() });
  295. }
  296. }
  297. }
  298. else
  299. {
  300. //selecting offer
  301. if (request.RequestedIpAddress == null)
  302. return null; //client MUST include this option; do nothing
  303. if (!request.ServerIdentifier.Address.Equals(serverIdentifierAddress))
  304. return null; //offer declined by client; do nothing
  305. leaseOffer = scope.GetExistingLeaseOrOffer(request);
  306. if (leaseOffer == null)
  307. {
  308. //no existing lease or offer available for client
  309. //send nak
  310. return new DhcpMessage(request, IPAddress.Any, IPAddress.Any, new DhcpOption[] { new DhcpMessageTypeOption(DhcpMessageType.Nak), new ServerIdentifierOption(scope.InterfaceAddress), DhcpOption.CreateEndOption() });
  311. }
  312. if (!request.RequestedIpAddress.Address.Equals(leaseOffer.Address))
  313. {
  314. //requested ip is incorrect
  315. //send nak
  316. return new DhcpMessage(request, IPAddress.Any, IPAddress.Any, new DhcpOption[] { new DhcpMessageTypeOption(DhcpMessageType.Nak), new ServerIdentifierOption(scope.InterfaceAddress), DhcpOption.CreateEndOption() });
  317. }
  318. }
  319. List<DhcpOption> options = scope.GetOptions(request, serverIdentifierAddress);
  320. if (options == null)
  321. return null;
  322. scope.CommitLease(leaseOffer);
  323. //log ip lease
  324. LogManager log = _log;
  325. if (log != null)
  326. log.Write(remoteEP, "DHCP Server leased IP address [" + leaseOffer.Address.ToString() + "] to " + request.GetClientFullIdentifier() + ".");
  327. //update hostname in reserved leases
  328. if (request.HostName != null)
  329. {
  330. Lease reservedLease = scope.GetReservedLease(leaseOffer.ClientIdentifier);
  331. if (reservedLease != null)
  332. reservedLease.SetHostName(request.HostName.HostName);
  333. }
  334. if (string.IsNullOrWhiteSpace(scope.DomainName))
  335. {
  336. //update lease hostname
  337. leaseOffer.SetHostName(request.HostName?.HostName);
  338. }
  339. else
  340. {
  341. //update dns
  342. string clientDomainName = null;
  343. foreach (DhcpOption option in options)
  344. {
  345. if (option.Code == DhcpOptionCode.ClientFullyQualifiedDomainName)
  346. {
  347. clientDomainName = (option as ClientFullyQualifiedDomainNameOption).DomainName;
  348. break;
  349. }
  350. }
  351. if (string.IsNullOrWhiteSpace(clientDomainName))
  352. {
  353. if (request.HostName != null)
  354. clientDomainName = request.HostName.HostName.Replace(' ', '-') + "." + scope.DomainName;
  355. }
  356. if (!string.IsNullOrWhiteSpace(clientDomainName))
  357. {
  358. leaseOffer.SetHostName(clientDomainName.ToLower());
  359. UpdateDnsAuthZone(true, scope, leaseOffer);
  360. }
  361. }
  362. return new DhcpMessage(request, leaseOffer.Address, serverIdentifierAddress, options);
  363. }
  364. case DhcpMessageType.Decline:
  365. {
  366. //ip address is already in use as detected by client via ARP
  367. if ((request.ServerIdentifier == null) || (request.RequestedIpAddress == null))
  368. return null; //client MUST include these option; do nothing
  369. Scope scope = FindScope(request, remoteEP.Address, ipPacketInformation);
  370. if (scope == null)
  371. return null; //no scope available; do nothing
  372. IPAddress serverIdentifierAddress = scope.InterfaceAddress.Equals(IPAddress.Any) ? ipPacketInformation.Address : scope.InterfaceAddress;
  373. if (!request.ServerIdentifier.Address.Equals(serverIdentifierAddress))
  374. return null; //request not for this server; do nothing
  375. Lease lease = scope.GetExistingLeaseOrOffer(request);
  376. if (lease == null)
  377. return null; //no existing lease or offer available for client; do nothing
  378. if (!lease.Address.Equals(request.RequestedIpAddress.Address))
  379. return null; //the client's notion of its IP address is not correct; do nothing
  380. //remove lease since the IP address is used by someone else
  381. scope.ReleaseLease(lease);
  382. //log issue
  383. LogManager log = _log;
  384. if (log != null)
  385. log.Write(remoteEP, "DHCP Server received DECLINE message: " + lease.GetClientFullIdentifier() + " detected that IP address [" + lease.Address + "] is already in use.");
  386. //update dns
  387. UpdateDnsAuthZone(false, scope, lease);
  388. //do nothing
  389. return null;
  390. }
  391. case DhcpMessageType.Release:
  392. {
  393. //cancel ip address lease
  394. if (request.ServerIdentifier == null)
  395. return null; //client MUST include this option; do nothing
  396. Scope scope = FindScope(request, remoteEP.Address, ipPacketInformation);
  397. if (scope == null)
  398. return null; //no scope available; do nothing
  399. IPAddress serverIdentifierAddress = scope.InterfaceAddress.Equals(IPAddress.Any) ? ipPacketInformation.Address : scope.InterfaceAddress;
  400. if (!request.ServerIdentifier.Address.Equals(serverIdentifierAddress))
  401. return null; //request not for this server; do nothing
  402. Lease lease = scope.GetExistingLeaseOrOffer(request);
  403. if (lease == null)
  404. return null; //no existing lease or offer available for client; do nothing
  405. if (!lease.Address.Equals(request.ClientIpAddress))
  406. return null; //the client's notion of its IP address is not correct; do nothing
  407. //release lease
  408. scope.ReleaseLease(lease);
  409. //log ip lease release
  410. LogManager log = _log;
  411. if (log != null)
  412. log.Write(remoteEP, "DHCP Server released IP address [" + lease.Address.ToString() + "] that was leased to " + lease.GetClientFullIdentifier() + ".");
  413. //update dns
  414. UpdateDnsAuthZone(false, scope, lease);
  415. //do nothing
  416. return null;
  417. }
  418. case DhcpMessageType.Inform:
  419. {
  420. //need only local config; already has ip address assigned externally/manually
  421. Scope scope = FindScope(request, remoteEP.Address, ipPacketInformation);
  422. if (scope == null)
  423. return null; //no scope available; do nothing
  424. IPAddress serverIdentifierAddress = scope.InterfaceAddress.Equals(IPAddress.Any) ? ipPacketInformation.Address : scope.InterfaceAddress;
  425. //log inform
  426. LogManager log = _log;
  427. if (log != null)
  428. log.Write(remoteEP, "DHCP Server received INFORM message from " + request.GetClientFullIdentifier() + ".");
  429. List<DhcpOption> options = scope.GetOptions(request, serverIdentifierAddress);
  430. if (options == null)
  431. return null;
  432. if (!string.IsNullOrWhiteSpace(scope.DomainName))
  433. {
  434. //update dns
  435. string clientDomainName = null;
  436. foreach (DhcpOption option in options)
  437. {
  438. if (option.Code == DhcpOptionCode.ClientFullyQualifiedDomainName)
  439. {
  440. clientDomainName = (option as ClientFullyQualifiedDomainNameOption).DomainName;
  441. break;
  442. }
  443. }
  444. if (string.IsNullOrWhiteSpace(clientDomainName))
  445. {
  446. if (request.HostName != null)
  447. clientDomainName = request.HostName.HostName.Replace(' ', '-') + "." + scope.DomainName;
  448. }
  449. if (!string.IsNullOrWhiteSpace(clientDomainName))
  450. UpdateDnsAuthZone(true, scope, clientDomainName, request.ClientIpAddress);
  451. }
  452. return new DhcpMessage(request, IPAddress.Any, serverIdentifierAddress, options);
  453. }
  454. default:
  455. return null;
  456. }
  457. }
  458. private Scope FindScope(DhcpMessage request, IPAddress remoteAddress, IPPacketInformation ipPacketInformation)
  459. {
  460. if (request.RelayAgentIpAddress.Equals(IPAddress.Any))
  461. {
  462. //no relay agent
  463. if (request.ClientIpAddress.Equals(IPAddress.Any))
  464. {
  465. if (!ipPacketInformation.Address.Equals(IPAddress.Broadcast))
  466. return null; //message destination address must be broadcast address
  467. //broadcast request
  468. Scope foundScope = null;
  469. foreach (Scope scope in _scopes.Values)
  470. {
  471. if (scope.Enabled && (scope.InterfaceIndex == ipPacketInformation.Interface))
  472. {
  473. if (scope.GetReservedLease(request) != null)
  474. return scope; //found reserved lease on this scope
  475. if ((foundScope == null) && !scope.AllowOnlyReservedLeases)
  476. foundScope = scope;
  477. }
  478. }
  479. return foundScope;
  480. }
  481. else
  482. {
  483. if (!remoteAddress.Equals(request.ClientIpAddress))
  484. return null; //client ip must match udp src addr
  485. //unicast request
  486. foreach (Scope scope in _scopes.Values)
  487. {
  488. if (scope.Enabled && scope.IsAddressInRange(remoteAddress))
  489. return scope;
  490. }
  491. return null;
  492. }
  493. }
  494. else
  495. {
  496. //relay agent unicast
  497. Scope foundScope = null;
  498. foreach (Scope scope in _scopes.Values)
  499. {
  500. if (scope.Enabled && scope.InterfaceAddress.Equals(IPAddress.Any))
  501. {
  502. if (scope.GetReservedLease(request) != null)
  503. return scope; //found reserved lease on this scope
  504. if (!request.ClientIpAddress.Equals(IPAddress.Any) && scope.IsAddressInRange(request.ClientIpAddress))
  505. foundScope = scope; //client IP address is in scope range
  506. else if ((foundScope == null) && scope.IsAddressInRange(request.RelayAgentIpAddress))
  507. foundScope = scope; //relay agent IP address is in scope range
  508. }
  509. }
  510. return foundScope;
  511. }
  512. }
  513. private void UpdateDnsAuthZone(bool add, Scope scope, Lease lease)
  514. {
  515. UpdateDnsAuthZone(add, scope, lease.HostName, lease.Address);
  516. }
  517. private void UpdateDnsAuthZone(bool add, Scope scope, string domain, IPAddress address)
  518. {
  519. if (_authZoneManager == null)
  520. return;
  521. if (string.IsNullOrWhiteSpace(scope.DomainName))
  522. return;
  523. if (string.IsNullOrWhiteSpace(domain))
  524. return;
  525. if (!DnsClient.IsDomainNameValid(domain))
  526. return;
  527. try
  528. {
  529. if (add)
  530. {
  531. //update forward zone
  532. _authZoneManager.CreatePrimaryZone(scope.DomainName, _authZoneManager.ServerDomain, false);
  533. _authZoneManager.SetRecords(domain, DnsResourceRecordType.A, scope.DnsTtl, new DnsResourceRecordData[] { new DnsARecord(address) });
  534. //update reverse zone
  535. _authZoneManager.CreatePrimaryZone(Zone.GetReverseZone(address, scope.SubnetMask), _authZoneManager.ServerDomain, false);
  536. _authZoneManager.SetRecords(Zone.GetReverseZone(address, 32), DnsResourceRecordType.PTR, scope.DnsTtl, new DnsResourceRecordData[] { new DnsPTRRecord(domain) });
  537. }
  538. else
  539. {
  540. //remove from forward zone
  541. _authZoneManager.DeleteRecords(domain, DnsResourceRecordType.A);
  542. //remove from reverse zone
  543. _authZoneManager.DeleteRecords(Zone.GetReverseZone(address, 32), DnsResourceRecordType.PTR);
  544. }
  545. }
  546. catch (Exception ex)
  547. {
  548. LogManager log = _log;
  549. if (log != null)
  550. log.Write(ex);
  551. }
  552. }
  553. private void BindUdpListener(IPEndPoint dhcpEP)
  554. {
  555. UdpListener listener = _udpListeners.GetOrAdd(dhcpEP.Address, delegate (IPAddress key)
  556. {
  557. Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  558. try
  559. {
  560. #region this code ignores ICMP port unreachable responses which creates SocketException in ReceiveFrom()
  561. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  562. {
  563. const uint IOC_IN = 0x80000000;
  564. const uint IOC_VENDOR = 0x18000000;
  565. const uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
  566. udpSocket.IOControl((IOControlCode)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
  567. }
  568. #endregion
  569. //bind to interface address
  570. if (Environment.OSVersion.Platform == PlatformID.Unix)
  571. udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); //to allow binding to same port with different addresses
  572. udpSocket.EnableBroadcast = true;
  573. udpSocket.ExclusiveAddressUse = false;
  574. udpSocket.Bind(dhcpEP);
  575. //start reading dhcp packets
  576. Thread thread = new Thread(ReadUdpRequestAsync);
  577. thread.Name = "DHCP Read Request: " + dhcpEP.ToString();
  578. thread.IsBackground = true;
  579. thread.Start(udpSocket);
  580. return new UdpListener(udpSocket);
  581. }
  582. catch
  583. {
  584. udpSocket.Dispose();
  585. throw;
  586. }
  587. });
  588. listener.IncrementScopeCount();
  589. }
  590. private bool UnbindUdpListener(IPEndPoint dhcpEP)
  591. {
  592. if (_udpListeners.TryGetValue(dhcpEP.Address, out UdpListener listener))
  593. {
  594. listener.DecrementScopeCount();
  595. if (listener.ScopeCount < 1)
  596. {
  597. if (_udpListeners.TryRemove(dhcpEP.Address, out _))
  598. {
  599. //issue: https://github.com/dotnet/runtime/issues/37873
  600. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  601. {
  602. listener.Socket.Dispose();
  603. }
  604. else
  605. {
  606. ThreadPool.QueueUserWorkItem(delegate (object state)
  607. {
  608. listener.Socket.Dispose();
  609. });
  610. }
  611. return true;
  612. }
  613. }
  614. }
  615. return false;
  616. }
  617. private async Task<bool> ActivateScopeAsync(Scope scope, bool waitForInterface)
  618. {
  619. IPEndPoint dhcpEP = null;
  620. try
  621. {
  622. //find this dns server address in case the network config has changed
  623. if (scope.UseThisDnsServer)
  624. scope.FindThisDnsServerAddress();
  625. //find scope interface for binding socket
  626. if (waitForInterface)
  627. {
  628. //retry for 30 seconds for interface to come up
  629. int tries = 0;
  630. while (true)
  631. {
  632. if (scope.FindInterface())
  633. break;
  634. if (++tries >= 30)
  635. throw new DhcpServerException("DHCP Server requires static IP address to work correctly but no network interface was found to have any static IP address configured.");
  636. await Task.Delay(1000);
  637. }
  638. }
  639. else
  640. {
  641. if (!scope.FindInterface())
  642. throw new DhcpServerException("DHCP Server requires static IP address to work correctly but no network interface was found to have any static IP address configured.");
  643. }
  644. IPAddress interfaceAddress = scope.InterfaceAddress;
  645. dhcpEP = new IPEndPoint(interfaceAddress, 67);
  646. if (!interfaceAddress.Equals(IPAddress.Any))
  647. BindUdpListener(dhcpEP);
  648. try
  649. {
  650. BindUdpListener(_dhcpDefaultEP);
  651. }
  652. catch
  653. {
  654. if (!interfaceAddress.Equals(IPAddress.Any))
  655. UnbindUdpListener(dhcpEP);
  656. throw;
  657. }
  658. if (_authZoneManager != null)
  659. {
  660. //update valid leases into dns
  661. DateTime utcNow = DateTime.UtcNow;
  662. foreach (Lease lease in scope.Leases)
  663. UpdateDnsAuthZone(utcNow < lease.LeaseExpires, scope, lease); //lease valid
  664. }
  665. LogManager log = _log;
  666. if (log != null)
  667. log.Write(dhcpEP, "DHCP Server successfully activated scope: " + scope.Name);
  668. return true;
  669. }
  670. catch (Exception ex)
  671. {
  672. LogManager log = _log;
  673. if (log != null)
  674. log.Write(dhcpEP, "DHCP Server failed to activate scope: " + scope.Name + "\r\n" + ex.ToString());
  675. }
  676. return false;
  677. }
  678. private bool DeactivateScope(Scope scope)
  679. {
  680. IPEndPoint dhcpEP = null;
  681. try
  682. {
  683. IPAddress interfaceAddress = scope.InterfaceAddress;
  684. dhcpEP = new IPEndPoint(interfaceAddress, 67);
  685. if (!interfaceAddress.Equals(IPAddress.Any))
  686. UnbindUdpListener(dhcpEP);
  687. UnbindUdpListener(_dhcpDefaultEP);
  688. if (_authZoneManager != null)
  689. {
  690. //remove all leases from dns
  691. foreach (Lease lease in scope.Leases)
  692. UpdateDnsAuthZone(false, scope, lease);
  693. }
  694. LogManager log = _log;
  695. if (log != null)
  696. log.Write(dhcpEP, "DHCP Server successfully deactivated scope: " + scope.Name);
  697. return true;
  698. }
  699. catch (Exception ex)
  700. {
  701. LogManager log = _log;
  702. if (log != null)
  703. log.Write(dhcpEP, "DHCP Server failed to deactivate scope: " + scope.Name + "\r\n" + ex.ToString());
  704. }
  705. return false;
  706. }
  707. private async Task LoadScopeAsync(Scope scope, bool waitForInterface)
  708. {
  709. foreach (Scope existingScope in _scopes.Values)
  710. {
  711. if (existingScope.IsAddressInRange(scope.StartingAddress) || existingScope.IsAddressInRange(scope.EndingAddress))
  712. throw new DhcpServerException("Scope with overlapping range already exists: " + existingScope.StartingAddress.ToString() + "-" + existingScope.EndingAddress.ToString());
  713. }
  714. if (!_scopes.TryAdd(scope.Name, scope))
  715. throw new DhcpServerException("Scope with same name already exists.");
  716. if (scope.Enabled)
  717. {
  718. if (!await ActivateScopeAsync(scope, waitForInterface))
  719. scope.SetEnabled(false);
  720. }
  721. LogManager log = _log;
  722. if (log != null)
  723. log.Write("DHCP Server successfully loaded scope: " + scope.Name);
  724. }
  725. private void UnloadScope(Scope scope)
  726. {
  727. if (scope.Enabled)
  728. DeactivateScope(scope);
  729. if (_scopes.TryRemove(scope.Name, out _))
  730. {
  731. LogManager log = _log;
  732. if (log != null)
  733. log.Write("DHCP Server successfully unloaded scope: " + scope.Name);
  734. }
  735. }
  736. private void LoadAllScopeFiles()
  737. {
  738. string[] scopeFiles = Directory.GetFiles(_scopesFolder, "*.scope");
  739. foreach (string scopeFile in scopeFiles)
  740. _ = LoadScopeFileAsync(scopeFile);
  741. _lastModifiedScopesSavedOn = DateTime.UtcNow;
  742. }
  743. private async Task LoadScopeFileAsync(string scopeFile)
  744. {
  745. //load scope file async to allow waiting for interface to come up
  746. try
  747. {
  748. using (FileStream fS = new FileStream(scopeFile, FileMode.Open, FileAccess.Read))
  749. {
  750. await LoadScopeAsync(new Scope(new BinaryReader(fS)), true);
  751. }
  752. LogManager log = _log;
  753. if (log != null)
  754. log.Write("DHCP Server successfully loaded scope file: " + scopeFile);
  755. }
  756. catch (Exception ex)
  757. {
  758. LogManager log = _log;
  759. if (log != null)
  760. log.Write("DHCP Server failed to load scope file: " + scopeFile + "\r\n" + ex.ToString());
  761. }
  762. }
  763. private void SaveScopeFile(Scope scope)
  764. {
  765. string scopeFile = Path.Combine(_scopesFolder, scope.Name + ".scope");
  766. try
  767. {
  768. using (FileStream fS = new FileStream(scopeFile, FileMode.Create, FileAccess.Write))
  769. {
  770. scope.WriteTo(new BinaryWriter(fS));
  771. }
  772. LogManager log = _log;
  773. if (log != null)
  774. log.Write("DHCP Server successfully saved scope file: " + scopeFile);
  775. }
  776. catch (Exception ex)
  777. {
  778. LogManager log = _log;
  779. if (log != null)
  780. log.Write("DHCP Server failed to save scope file: " + scopeFile + "\r\n" + ex.ToString());
  781. }
  782. }
  783. private void DeleteScopeFile(string scopeName)
  784. {
  785. string scopeFile = Path.Combine(_scopesFolder, scopeName + ".scope");
  786. try
  787. {
  788. File.Delete(scopeFile);
  789. LogManager log = _log;
  790. if (log != null)
  791. log.Write("DHCP Server successfully deleted scope file: " + scopeFile);
  792. }
  793. catch (Exception ex)
  794. {
  795. LogManager log = _log;
  796. if (log != null)
  797. log.Write("DHCP Server failed to delete scope file: " + scopeFile + "\r\n" + ex.ToString());
  798. }
  799. }
  800. private void SaveModifiedScopes()
  801. {
  802. DateTime currentDateTime = DateTime.UtcNow;
  803. foreach (KeyValuePair<string, Scope> scope in _scopes)
  804. {
  805. if (scope.Value.LastModified > _lastModifiedScopesSavedOn)
  806. SaveScopeFile(scope.Value);
  807. }
  808. _lastModifiedScopesSavedOn = currentDateTime;
  809. }
  810. private void StartMaintenanceTimer()
  811. {
  812. if (_maintenanceTimer == null)
  813. {
  814. _maintenanceTimer = new Timer(delegate (object state)
  815. {
  816. try
  817. {
  818. foreach (KeyValuePair<string, Scope> scope in _scopes)
  819. {
  820. scope.Value.RemoveExpiredOffers();
  821. List<Lease> expiredLeases = scope.Value.RemoveExpiredLeases();
  822. foreach (Lease expiredLease in expiredLeases)
  823. UpdateDnsAuthZone(false, scope.Value, expiredLease);
  824. }
  825. SaveModifiedScopes();
  826. }
  827. catch (Exception ex)
  828. {
  829. LogManager log = _log;
  830. if (log != null)
  831. log.Write(ex);
  832. }
  833. finally
  834. {
  835. if (!_disposed)
  836. _maintenanceTimer.Change(MAINTENANCE_TIMER_INTERVAL, Timeout.Infinite);
  837. }
  838. }, null, Timeout.Infinite, Timeout.Infinite);
  839. }
  840. _maintenanceTimer.Change(MAINTENANCE_TIMER_INTERVAL, Timeout.Infinite);
  841. }
  842. private void StopMaintenanceTimer()
  843. {
  844. _maintenanceTimer.Change(Timeout.Infinite, Timeout.Infinite);
  845. }
  846. #endregion
  847. #region public
  848. public void Start()
  849. {
  850. if (_disposed)
  851. throw new ObjectDisposedException("DhcpServer");
  852. if (_state != ServiceState.Stopped)
  853. throw new InvalidOperationException("DHCP Server is already running.");
  854. _state = ServiceState.Starting;
  855. LoadAllScopeFiles();
  856. StartMaintenanceTimer();
  857. _state = ServiceState.Running;
  858. }
  859. public void Stop()
  860. {
  861. if (_state != ServiceState.Running)
  862. return;
  863. _state = ServiceState.Stopping;
  864. StopMaintenanceTimer();
  865. foreach (KeyValuePair<string, Scope> scope in _scopes)
  866. UnloadScope(scope.Value);
  867. _udpListeners.Clear();
  868. _state = ServiceState.Stopped;
  869. }
  870. public async Task AddScopeAsync(Scope scope)
  871. {
  872. await LoadScopeAsync(scope, false);
  873. SaveScopeFile(scope);
  874. }
  875. public Scope GetScope(string name)
  876. {
  877. if (_scopes.TryGetValue(name, out Scope scope))
  878. return scope;
  879. return null;
  880. }
  881. public void RenameScope(string oldName, string newName)
  882. {
  883. if (!_scopes.TryGetValue(oldName, out Scope scope))
  884. throw new DhcpServerException("Scope with name '" + oldName + "' does not exists.");
  885. if (!_scopes.TryAdd(newName, scope))
  886. throw new DhcpServerException("Scope with name '" + newName + "' already exists.");
  887. scope.Name = newName;
  888. _scopes.TryRemove(oldName, out _);
  889. SaveScopeFile(scope);
  890. DeleteScopeFile(oldName);
  891. }
  892. public void DeleteScope(string name)
  893. {
  894. if (_scopes.TryGetValue(name, out Scope scope))
  895. {
  896. UnloadScope(scope);
  897. DeleteScopeFile(scope.Name);
  898. }
  899. }
  900. public async Task<bool> EnableScopeAsync(string name)
  901. {
  902. if (_scopes.TryGetValue(name, out Scope scope))
  903. {
  904. if (!scope.Enabled && await ActivateScopeAsync(scope, false))
  905. {
  906. scope.SetEnabled(true);
  907. SaveScopeFile(scope);
  908. return true;
  909. }
  910. }
  911. return false;
  912. }
  913. public bool DisableScope(string name)
  914. {
  915. if (_scopes.TryGetValue(name, out Scope scope))
  916. {
  917. if (scope.Enabled && DeactivateScope(scope))
  918. {
  919. scope.SetEnabled(false);
  920. SaveScopeFile(scope);
  921. return true;
  922. }
  923. }
  924. return false;
  925. }
  926. public void SaveScope(string name)
  927. {
  928. if (_scopes.TryGetValue(name, out Scope scope))
  929. SaveScopeFile(scope);
  930. }
  931. public IDictionary<string, string> GetAddressClientMap()
  932. {
  933. Dictionary<string, string> map = new Dictionary<string, string>();
  934. foreach (KeyValuePair<string, Scope> scope in _scopes)
  935. {
  936. foreach (Lease lease in scope.Value.Leases)
  937. {
  938. if (!string.IsNullOrEmpty(lease.HostName))
  939. map.Add(lease.Address.ToString(), lease.HostName);
  940. }
  941. }
  942. return map;
  943. }
  944. #endregion
  945. #region properties
  946. public ICollection<Scope> Scopes
  947. { get { return _scopes.Values; } }
  948. public AuthZoneManager AuthZoneManager
  949. {
  950. get { return _authZoneManager; }
  951. set { _authZoneManager = value; }
  952. }
  953. public LogManager LogManager
  954. {
  955. get { return _log; }
  956. set { _log = value; }
  957. }
  958. #endregion
  959. class UdpListener
  960. {
  961. #region private
  962. readonly Socket _socket;
  963. volatile int _scopeCount;
  964. #endregion
  965. #region constructor
  966. public UdpListener(Socket socket)
  967. {
  968. _socket = socket;
  969. }
  970. #endregion
  971. #region public
  972. public void IncrementScopeCount()
  973. {
  974. Interlocked.Increment(ref _scopeCount);
  975. }
  976. public void DecrementScopeCount()
  977. {
  978. Interlocked.Decrement(ref _scopeCount);
  979. }
  980. #endregion
  981. #region properties
  982. public Socket Socket
  983. { get { return _socket; } }
  984. public int ScopeCount
  985. { get { return _scopeCount; } }
  986. #endregion
  987. }
  988. }
  989. }