Keyboard firmwares for Atmel AVR and Cortex-M
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DHCPServerApp.c 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. /*
  2. LUFA Library
  3. Copyright (C) Dean Camera, 2014.
  4. dean [at] fourwalledcubicle [dot] com
  5. www.lufa-lib.org
  6. */
  7. /*
  8. Copyright 2014 Dean Camera (dean [at] fourwalledcubicle [dot] com)
  9. Permission to use, copy, modify, distribute, and sell this
  10. software and its documentation for any purpose is hereby granted
  11. without fee, provided that the above copyright notice appear in
  12. all copies and that both that the copyright notice and this
  13. permission notice and warranty disclaimer appear in supporting
  14. documentation, and that the name of the author not be used in
  15. advertising or publicity pertaining to distribution of the
  16. software without specific, written prior permission.
  17. The author disclaims all warranties with regard to this
  18. software, including all implied warranties of merchantability
  19. and fitness. In no event shall the author be liable for any
  20. special, indirect or consequential damages or any damages
  21. whatsoever resulting from loss of use, data or profits, whether
  22. in an action of contract, negligence or other tortious action,
  23. arising out of or in connection with the use or performance of
  24. this software.
  25. */
  26. /** \file
  27. *
  28. * DHCP Server Application. When connected to the uIP stack, this will send IP configuration settings to a
  29. * DHCP client on the network.
  30. */
  31. #define INCLUDE_FROM_DHCPSERVERAPP_C
  32. #include "DHCPServerApp.h"
  33. #if defined(ENABLE_DHCP_SERVER) || defined(__DOXYGEN__)
  34. struct uip_conn* BroadcastConnection;
  35. uint8_t LeasedIPs[255 / 8];
  36. /** Initialization function for the DHCP server. */
  37. void DHCPServerApp_Init(void)
  38. {
  39. /* Listen on port 67 for DHCP server connections from hosts */
  40. uip_listen(HTONS(DHCP_SERVER_PORT));
  41. /* Create a new UDP connection to the DHCP server port for the DHCP solicitation */
  42. struct uip_udp_conn* BroadcastConnection = uip_udp_new(&uip_broadcast_addr, HTONS(DHCP_CLIENT_PORT));
  43. /* If the connection was successfully created, bind it to the local DHCP client port */
  44. if (BroadcastConnection != NULL)
  45. uip_udp_bind(BroadcastConnection, HTONS(DHCP_SERVER_PORT));
  46. /* Set all IP addresses as unleased */
  47. memset(LeasedIPs, 0x00, sizeof(LeasedIPs));
  48. }
  49. /** uIP stack application callback for the DHCP server. This function must be called each time the TCP/IP stack
  50. * needs a UDP packet to be processed.
  51. */
  52. void DHCPServerApp_Callback(void)
  53. {
  54. DHCP_Header_t* const AppData = (DHCP_Header_t*)uip_appdata;
  55. uint16_t AppDataSize = 0;
  56. /* Only process when new data arrives - don't retransmit lost packets */
  57. if (uip_newdata())
  58. {
  59. /* Get the DHCP message type (if present), otherwise early-abort */
  60. uint8_t DHCPMessageType;
  61. if (!(DHCPCommon_GetOption(AppData->Options, DHCP_OPTION_MSG_TYPE, &DHCPMessageType)))
  62. return;
  63. uip_ipaddr_t Netmask, GatewayIPAddress, PreferredClientIP;
  64. struct uip_eth_addr RemoteMACAddress;
  65. uint32_t TransactionID;
  66. /* Get configured network mask, gateway IP and extract out DHCP transaction ID and remote IP */
  67. uip_getnetmask(&Netmask);
  68. uip_getdraddr(&GatewayIPAddress);
  69. memcpy(&RemoteMACAddress, &AppData->ClientHardwareAddress, sizeof(struct uip_eth_addr));
  70. TransactionID = AppData->TransactionID;
  71. /* Try to extract out the client's preferred IP address if it is indicated in the packet */
  72. if (!(DHCPCommon_GetOption(AppData->Options, DHCP_OPTION_REQ_IPADDR, &PreferredClientIP)))
  73. memcpy(&PreferredClientIP, &uip_all_zeroes_addr, sizeof(uip_ipaddr_t));
  74. switch (DHCPMessageType)
  75. {
  76. case DHCP_DISCOVER:
  77. /* If no preference was made or the preferred IP is already taken, find a new address */
  78. if (DHCPServerApp_CheckIfIPLeased(&PreferredClientIP))
  79. DHCPServerApp_GetUnleasedIP(&PreferredClientIP);
  80. /* Create a new DHCP OFFER packet with the offered IP address */
  81. AppDataSize += DHCPServerApp_FillDHCPHeader(AppData, DHCP_OFFER, &RemoteMACAddress, &PreferredClientIP, TransactionID);
  82. /* Add network mask and router information to the list of DHCP OFFER packet options */
  83. AppDataSize += DHCPCommon_SetOption(AppData->Options, DHCP_OPTION_SUBNET_MASK,
  84. sizeof(uip_ipaddr_t), &Netmask);
  85. AppDataSize += DHCPCommon_SetOption(AppData->Options, DHCP_OPTION_ROUTER,
  86. sizeof(uip_ipaddr_t), &GatewayIPAddress);
  87. /* Send the DHCP OFFER packet */
  88. uip_poll_conn(BroadcastConnection);
  89. memcpy(&uip_udp_conn->ripaddr, &uip_broadcast_addr, sizeof(uip_ipaddr_t));
  90. uip_udp_send(AppDataSize);
  91. break;
  92. case DHCP_REQUEST:
  93. /* Check to see if the requested IP address has already been leased to a client */
  94. if (!(DHCPServerApp_CheckIfIPLeased(&PreferredClientIP)))
  95. {
  96. /* Create a new DHCP ACK packet to accept the IP address lease */
  97. AppDataSize += DHCPServerApp_FillDHCPHeader(AppData, DHCP_ACK, &RemoteMACAddress, &PreferredClientIP, TransactionID);
  98. /* Add network mask and router information to the list of DHCP ACK packet options */
  99. AppDataSize += DHCPCommon_SetOption(AppData->Options, DHCP_OPTION_SUBNET_MASK,
  100. sizeof(uip_ipaddr_t), &Netmask);
  101. AppDataSize += DHCPCommon_SetOption(AppData->Options, DHCP_OPTION_ROUTER,
  102. sizeof(uip_ipaddr_t), &GatewayIPAddress);
  103. /* Mark the requested IP as leased to a client */
  104. DHCPServerApp_LeaseIP(&PreferredClientIP);
  105. }
  106. else
  107. {
  108. /* Create a new DHCP NAK packet to reject the requested allocation */
  109. AppDataSize += DHCPServerApp_FillDHCPHeader(AppData, DHCP_NAK, &RemoteMACAddress, &uip_all_zeroes_addr, TransactionID);
  110. }
  111. /* Send the DHCP ACK or NAK packet */
  112. uip_poll_conn(BroadcastConnection);
  113. memcpy(&uip_udp_conn->ripaddr, &uip_broadcast_addr, sizeof(uip_ipaddr_t));
  114. uip_udp_send(AppDataSize);
  115. break;
  116. case DHCP_RELEASE:
  117. /* Mark the IP address as released in the allocation table */
  118. DHCPServerApp_UnleaseIP(&uip_udp_conn->ripaddr);
  119. break;
  120. }
  121. }
  122. }
  123. /** Fills the DHCP packet response with the appropriate BOOTP header for DHCP. This fills out all the required
  124. * fields, leaving only the additional DHCP options to be added to the packet before it is sent to the DHCP client.
  125. *
  126. * \param[out] DHCPHeader Location in the packet buffer where the BOOTP header should be written to
  127. * \param[in] DHCPMessageType DHCP Message type, such as DHCP_DISCOVER
  128. * \param[in] ClientHardwareAddress Client MAC address the created transaction should be directed to
  129. * \param[in] PreferredClientIP Preferred IP that should be given to the client if it is unallocated
  130. * \param[in] TransactionID Transaction ID the created transaction should be associated with
  131. *
  132. * \return Size in bytes of the created DHCP packet
  133. */
  134. static uint16_t DHCPServerApp_FillDHCPHeader(DHCP_Header_t* const DHCPHeader,
  135. const uint8_t DHCPMessageType,
  136. const struct uip_eth_addr* const ClientHardwareAddress,
  137. const uip_ipaddr_t* const PreferredClientIP,
  138. const uint32_t TransactionID)
  139. {
  140. /* Erase existing packet data so that we start will all 0x00 DHCP header data */
  141. memset(DHCPHeader, 0, sizeof(DHCP_Header_t));
  142. DHCPHeader->Operation = DHCPMessageType;
  143. DHCPHeader->HardwareType = DHCP_HTYPE_ETHERNET;
  144. DHCPHeader->HardwareAddressLength = sizeof(MACAddress);
  145. DHCPHeader->Hops = 0;
  146. DHCPHeader->TransactionID = TransactionID;
  147. DHCPHeader->ElapsedSeconds = 0;
  148. DHCPHeader->Flags = 0;
  149. memcpy(&DHCPHeader->NextServerIP, &uip_hostaddr, sizeof(uip_ipaddr_t));
  150. memcpy(&DHCPHeader->YourIP, PreferredClientIP, sizeof(uip_ipaddr_t));
  151. memcpy(&DHCPHeader->ClientHardwareAddress, ClientHardwareAddress, sizeof(struct uip_eth_addr));
  152. DHCPHeader->Cookie = DHCP_MAGIC_COOKIE;
  153. /* Add a DHCP message type and terminator options to the start of the DHCP options field */
  154. DHCPHeader->Options[0] = DHCP_OPTION_MSG_TYPE;
  155. DHCPHeader->Options[1] = 1;
  156. DHCPHeader->Options[2] = DHCPMessageType;
  157. DHCPHeader->Options[3] = DHCP_OPTION_END;
  158. /* Calculate the total number of bytes added to the outgoing packet */
  159. return (sizeof(DHCP_Header_t) + 4);
  160. }
  161. /** Checks to see if the nominated IP address has already been allocated to a client.
  162. *
  163. * \param[in] IPAddress IP Address whose lease status should be checked
  164. *
  165. * \pre The IP address must be within the same /24 subnet as the virtual webserver.
  166. *
  167. * \return Boolean \c true if the IP has already been leased to a client, \c false otherwise.
  168. */
  169. static bool DHCPServerApp_CheckIfIPLeased(const uip_ipaddr_t* const IPAddress)
  170. {
  171. uint8_t Byte = (IPAddress->u8[3] / 8);
  172. uint8_t Mask = (1 << (IPAddress->u8[3] % 8));
  173. /* Make sure that the requested IP address isn't already leased to the virtual server or another client */
  174. if (IPAddress->u8[3] && !(IPAddress->u8[3] == uip_hostaddr.u8[3]) && !(LeasedIPs[Byte] & Mask))
  175. return false;
  176. else
  177. return true;
  178. }
  179. /** Retrieves the next unleased IP in the IP address pool.
  180. *
  181. * \param[out] NewIPAddress Location where the generated IP Address should be stored
  182. */
  183. static void DHCPServerApp_GetUnleasedIP(uip_ipaddr_t* const NewIPAddress)
  184. {
  185. uip_ipaddr_copy(NewIPAddress, &uip_hostaddr);
  186. /** Look through the current subnet, skipping the broadcast and zero IP addresses */
  187. for (uint8_t IP = 1; IP < 254; IP++)
  188. {
  189. /* Update new IP address to lease with the current IP address to test */
  190. NewIPAddress->u8[3] = IP;
  191. /* If we've found an unleased IP, abort with the updated IP stored for the called */
  192. if (!(DHCPServerApp_CheckIfIPLeased(NewIPAddress)))
  193. return;
  194. }
  195. }
  196. /** Marks the given IP Address as leased in the address pool, so that it will not be
  197. * allocated to another client unless it is first released.
  198. *
  199. * \param[in] IPAddress IP Address to mark as leased
  200. *
  201. * \pre The IP address must be within the same /24 subnet as the virtual webserver.
  202. */
  203. static void DHCPServerApp_LeaseIP(const uip_ipaddr_t* const IPAddress)
  204. {
  205. uint8_t Byte = (IPAddress->u8[3] / 8);
  206. uint8_t Mask = (1 << (IPAddress->u8[3] % 8));
  207. /* Mark the IP address as leased in the allocation table */
  208. LeasedIPs[Byte] |= Mask;
  209. }
  210. /** Marks the given IP Address as not leased in the address pool, so that it can be
  211. * allocated to another client upon request.
  212. *
  213. * \param[in] IPAddress IP Address to mark as not leased
  214. *
  215. * \pre The IP address must be within the same /24 subnet as the virtual webserver.
  216. */
  217. static void DHCPServerApp_UnleaseIP(const uip_ipaddr_t* const IPAddress)
  218. {
  219. uint8_t Byte = (IPAddress->u8[3] / 8);
  220. uint8_t Mask = (1 << (IPAddress->u8[3] % 8));
  221. /* Mark the IP address as unleased in the allocation table */
  222. LeasedIPs[Byte] &= ~Mask;
  223. }
  224. #endif