DhcpProgram.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. using DhcpServer.Models;
  2. using DhcpServer.Properties;
  3. using SharpPcap;
  4. using SharpPcap.LibPcap;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Threading;
  11. namespace DhcpServer
  12. {
  13. public static class DhcpProgram
  14. {
  15. private const int PoolEntryKeepHours = 10;
  16. private static bool _isRunning;
  17. private static LibPcapLiveDevice _nic;
  18. private static IPEndPoint _listenOn;
  19. private static IPAddress _poolStart;
  20. private static int _poolSize;
  21. private static IPAddress _subNet;
  22. private static IPAddress _router;
  23. private static IPAddress _broadcastAddress;
  24. private static IPAddress _dns;
  25. private static IPAddress _pxeTftp;
  26. private static string _pxeFileName;
  27. private static string _ipxeScriptUri;
  28. private static string _u64FileName;
  29. private static string _u86FileName;
  30. private static string _uHttpFileName;
  31. private static IReadOnlyCollection<PoolSlot> _pool;
  32. private static IPAddress _ipxeRouter;
  33. private static IPAddress _pxeRouter;
  34. private static void Main(string[] args)
  35. {
  36. Console.WriteLine("Starting...");
  37. var tWorker = new Thread(Working2);
  38. _isRunning = true;
  39. tWorker.Start();
  40. Console.WriteLine("Press ENTER to Stop.");
  41. Console.ReadLine();
  42. Console.Write("Shutting down...");
  43. _isRunning = false;
  44. tWorker.Join();
  45. Console.Write("Stopped.");
  46. Console.WriteLine();
  47. Console.Write("Press ENTER to Exit.");
  48. Console.ReadLine();
  49. }
  50. //-----------------------------
  51. private static void Working2()
  52. {
  53. var upTime = DateTime.Now;
  54. LoadConfig();
  55. InitConfig();
  56. //Listing
  57. var socket = new Socket(_listenOn.AddressFamily, SocketType.Dgram, ProtocolType.Udp)
  58. {
  59. EnableBroadcast = true,
  60. SendBufferSize = 1500,
  61. ReceiveBufferSize = 1500
  62. };
  63. socket.Bind(_listenOn);
  64. var buffer = new byte[1500];
  65. EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 68);
  66. var polling = DateTime.Now;
  67. var pooled = false;
  68. while (_isRunning)
  69. {
  70. Console.CursorLeft = 0;
  71. if (false == socket.Poll(500 * 1000, SelectMode.SelectRead))
  72. {
  73. var timeSpan = DateTime.Now - polling;
  74. var up = DateTime.Now - upTime;
  75. Console.Write("Polling sockets..." +
  76. $" {timeSpan.Days:00}D {timeSpan.Hours:00}H {timeSpan.Minutes:00}M {timeSpan.Seconds:00}S {timeSpan.Milliseconds:000}" +
  77. $" / UP {up.Days:00}D {up.Hours:00}H {up.Minutes:00}M {up.Seconds:00}S {up.Milliseconds:000}");
  78. pooled = true;
  79. }
  80. else // polled
  81. {
  82. if (pooled)
  83. {
  84. pooled = false;
  85. Console.WriteLine();
  86. }
  87. var bytes = socket.ReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEndPoint);
  88. Console.Write($"Receive {bytes} byte From {remoteEndPoint}");
  89. try
  90. {
  91. var reply = ProcessRequest(buffer);
  92. if (reply.MessageType != DhcpMessageType.Unknown)
  93. {
  94. bytes = reply.WriteToBuffer(buffer);
  95. var to = new IPEndPoint(IPAddress.Broadcast, 68);
  96. Console.WriteLine($"Send {bytes} bytes to {to} {reply.MessageType} by {reply.ClientMacAddressHex}");
  97. var sent = socket.SendTo(buffer, 0, bytes, SocketFlags.None, to);
  98. }
  99. }
  100. catch (Exception e)
  101. {
  102. Console.WriteLine(e);
  103. }
  104. polling = DateTime.Now;
  105. }// end if poll
  106. }// end while
  107. socket.Close();
  108. }
  109. private static DhcpPacket ProcessRequest(byte[] buffer)
  110. {
  111. var packet = new DhcpPacket(buffer);
  112. var clientMac = packet.ClientMacAddressHex;
  113. Console.WriteLine($" {packet.MessageType} by {clientMac}");
  114. Console.WriteLine($" {packet.Vendor ?? "Unknown Vendor"} / {packet.UserClass ?? "Unknown Class"} / {packet.HostName ?? "Unknown HostName"}");
  115. DhcpMessageType reply;
  116. switch (packet.MessageType)
  117. {
  118. default:
  119. reply = DhcpMessageType.Unknown;
  120. break;
  121. case DhcpMessageType.Discover:
  122. reply = DhcpMessageType.Offer;
  123. break;
  124. case DhcpMessageType.Request:
  125. reply = DhcpMessageType.Ack;
  126. break;
  127. }
  128. if (reply == DhcpMessageType.Unknown)
  129. {
  130. packet.MessageType = DhcpMessageType.Unknown;
  131. }
  132. else
  133. {
  134. // extract params
  135. var hostName = packet.HostName;
  136. var userClass = packet.UserClass;
  137. var vendor = packet.Vendor;
  138. // Allocate ip address
  139. PoolSlot allocateSlot = null;
  140. {
  141. var mSlot = _pool.FirstOrDefault(p => p.Mac == clientMac);
  142. if (mSlot != null)
  143. {
  144. if (CheckMac(mSlot, clientMac))
  145. {
  146. allocateSlot = mSlot;
  147. Console.WriteLine("Prefer last time address");
  148. }
  149. }
  150. }
  151. if (allocateSlot == null)
  152. {
  153. foreach (var slot in _pool)
  154. {
  155. if (slot.LastConfirm.HasValue && (DateTime.Now - slot.LastConfirm.Value).Hours < PoolEntryKeepHours) continue;
  156. if (CheckMac(slot))
  157. {
  158. allocateSlot = slot;
  159. break;
  160. }
  161. }
  162. }
  163. // ready for reply
  164. packet.Options.Clear();
  165. if (null == allocateSlot)
  166. {
  167. packet.MessageType = DhcpMessageType.Nak;
  168. Console.Write(" *** Allocate fail");
  169. }
  170. else
  171. {
  172. allocateSlot.Mac = clientMac;
  173. allocateSlot.HostName = hostName;
  174. allocateSlot.LastConfirm = DateTime.Now;
  175. packet.OpCode = DhcpOpCode.BootReply;
  176. packet.MessageType = reply;
  177. //fill dynamic params
  178. packet.YourIpAddress = allocateSlot.Address;
  179. //fill static params
  180. packet.Router = _router;
  181. packet.SubNetMask = _subNet;
  182. packet.BroadcastAddress = _broadcastAddress;
  183. packet.DnsServer = _dns;
  184. packet.LeaseTime = TimeSpan.FromDays(8);
  185. packet.RebindingTime = packet.LeaseTime;
  186. packet.RenewalTime = packet.LeaseTime;
  187. packet.DhcpServerIdentifier = _listenOn.Address;
  188. // vendor spec
  189. packet.Router = _pxeRouter;
  190. packet.TftpServer = _pxeTftp.ToString();
  191. packet.NextServerIpAddress = _pxeTftp;
  192. if (userClass == "iPXE")
  193. {
  194. packet.BootFileName = _ipxeScriptUri;
  195. packet.Router = _ipxeRouter;
  196. }
  197. else
  198. {
  199. if (true == vendor?.StartsWith("PXEClient:Arch:00000"))
  200. {
  201. //Legacy
  202. packet.BootFileName = _pxeFileName;
  203. }
  204. else if (true == vendor?.StartsWith("PXEClient:Arch:00002")
  205. || true == vendor?.StartsWith("PXEClient:Arch:00006"))
  206. {
  207. //UEFI x86
  208. packet.BootFileName = _u86FileName;
  209. }
  210. else if (true == vendor?.StartsWith("PXEClient:Arch:00007")
  211. || true == vendor?.StartsWith("PXEClient:Arch:00008")
  212. || true == vendor?.StartsWith("PXEClient:Arch:00009")
  213. )
  214. {
  215. //UEFI x64
  216. packet.BootFileName = _u64FileName;
  217. }
  218. }
  219. }
  220. }
  221. return packet;
  222. }
  223. private static bool CheckMac(PoolSlot slot, string clientMac = null)
  224. {
  225. Console.Write($"Checking mac for {slot.Address}...");
  226. var mac = GetMac(slot.Address, out var err);
  227. if (err != null)
  228. {
  229. Console.WriteLine($"Err:{err}");
  230. return false;
  231. }
  232. if (mac == null)
  233. {
  234. Console.WriteLine("Available");
  235. return true;
  236. }
  237. if (mac == clientMac)
  238. {
  239. Console.WriteLine("DupReq");
  240. return true;
  241. }
  242. slot.Mac = mac;
  243. slot.LastConfirm = DateTime.Now;
  244. Console.WriteLine($"In using by {mac}");
  245. return false;
  246. }
  247. private static void InitConfig()
  248. {
  249. _nic = LibPcapLiveDeviceList.Instance.FirstOrDefault(p => p.Addresses.Any(q => Equals(q.Addr.ipAddress, _listenOn.Address)));
  250. //if (null == _nic) throw new ConfigurationErrorsException("Device not found");
  251. var slots = new PoolSlot[_poolSize];
  252. slots[0] = new PoolSlot(_poolStart);
  253. for (var i = 1; i < _poolSize; i++) slots[i] = new PoolSlot(slots[i - 1].Address.NextAddress());
  254. _pool = slots;
  255. }
  256. private static void LoadConfig()
  257. {
  258. _listenOn = new IPEndPoint(IPAddress.Parse(Settings.Default.ListenOn), 67);
  259. _poolStart = IPAddress.Parse(Settings.Default.PoolStart);
  260. _poolSize = Settings.Default.PoolSize;
  261. _subNet = IPAddress.Parse(Settings.Default.SubNet);
  262. _router = IPAddress.Parse(Settings.Default.Router);
  263. _dns = IPAddress.Parse(Settings.Default.Dns);
  264. _pxeRouter = IPAddress.Parse(Settings.Default.PxeRouter);
  265. _pxeTftp = IPAddress.Parse(Settings.Default.PxeTftp);
  266. _pxeFileName = Settings.Default.FileName;
  267. _u64FileName = Settings.Default.FileName_UEFI_x64;
  268. _u86FileName = Settings.Default.FileName_UEFI_I386;
  269. _ipxeScriptUri = Settings.Default.FileName_iPXE_HTTP;
  270. _ipxeRouter = IPAddress.Parse(Settings.Default.IpxeRouter);
  271. _broadcastAddress = IPAddress.Parse(Settings.Default.BroadcastAddress);
  272. }
  273. public static string GetHostName(IPAddress address, out string error)
  274. {
  275. try
  276. {
  277. var ipHostEntry = Dns.GetHostEntry(address);
  278. error = null;
  279. return ipHostEntry.HostName;
  280. }
  281. catch (Exception e)
  282. {
  283. error = e.GetMessageRecursively();
  284. }
  285. return null;
  286. }
  287. public static string GetMac(IPAddress targetAddress, out string error)
  288. {
  289. try
  290. {
  291. var arp = new ARP(_nic);
  292. var physicalAddress = arp.Resolve(targetAddress);
  293. if (null == physicalAddress)
  294. {
  295. error = null;
  296. return null;
  297. }
  298. var mac = string.Join("-", physicalAddress.GetAddressBytes().Select(p => p.ToString("X2")));
  299. error = null;
  300. return mac;
  301. }
  302. catch (Exception e)
  303. {
  304. error = e.GetMessageRecursively();
  305. }
  306. return null;
  307. }
  308. public static IPAddress NextAddress(this IPAddress address, uint increment = 1)
  309. {
  310. if (address.AddressFamily != AddressFamily.InterNetwork) throw new NotSupportedException();
  311. var bytes = address.GetAddressBytes();
  312. var value =
  313. (uint)bytes[0] << 24 |
  314. (uint)bytes[1] << 16 |
  315. (uint)bytes[2] << 8 |
  316. (uint)bytes[3];
  317. value += increment;
  318. bytes[0] = (byte)(value >> 24);
  319. bytes[1] = (byte)(value >> 16);
  320. bytes[2] = (byte)(value >> 8);
  321. bytes[3] = (byte)value;
  322. return new IPAddress(bytes);
  323. }
  324. public static string GetMessageRecursively(this Exception exception)
  325. {
  326. var msg = exception.Message;
  327. if (null != exception.InnerException) msg += " --> " + exception.InnerException.GetMessageRecursively();
  328. return msg;
  329. }
  330. }
  331. }