3      Copyright (C) Dean Camera, 2010. 
   5   dean [at] fourwalledcubicle [dot] com 
  10   Copyright 2010  Dean Camera (dean [at] fourwalledcubicle [dot] com) 
  12   Permission to use, copy, modify, distribute, and sell this 
  13   software and its documentation for any purpose is hereby granted 
  14   without fee, provided that the above copyright notice appear in 
  15   all copies and that both that the copyright notice and this 
  16   permission notice and warranty disclaimer appear in supporting 
  17   documentation, and that the name of the author not be used in 
  18   advertising or publicity pertaining to distribution of the 
  19   software without specific, written prior permission. 
  21   The author disclaim all warranties with regard to this 
  22   software, including all implied warranties of merchantability 
  23   and fitness.  In no event shall the author be liable for any 
  24   special, indirect or consequential damages or any damages 
  25   whatsoever resulting from loss of use, data or profits, whether 
  26   in an action of contract, negligence or other tortious action, 
  27   arising out of or in connection with the use or performance of 
  31 #if defined(ENABLE_DHCP_CLIENT) || defined(__DOXYGEN__) 
  35  *  DHCP Client Application. When connected to the uIP stack, this will retrieve IP configuration settings from the 
  36  *  DHCP server on the network. 
  39 #define  INCLUDE_FROM_DHCPCLIENTAPP_C 
  40 #include "DHCPClientApp.h" 
  42 /** Initialization function for the DHCP client. */ 
  43 void DHCPClientApp_Init(void) 
  45         /* Create a new UDP connection to the DHCP server port for the DHCP solicitation */ 
  46         struct uip_udp_conn
* Connection 
= uip_udp_new(&uip_broadcast_addr
, HTONS(DHCPC_SERVER_PORT
)); 
  48         /* If the connection was successfully created, bind it to the local DHCP client port */ 
  49         if (Connection 
!= NULL
) 
  51                 uip_udp_appstate_t
* const AppState 
= &Connection
->appstate
; 
  52                 uip_udp_bind(Connection
, HTONS(DHCPC_CLIENT_PORT
)); 
  54                 /* Set the initial client state */ 
  55                 AppState
->DHCPClient
.CurrentState 
= DHCP_STATE_SendDiscover
; 
  57                 /* Set timeout period to half a second for a DHCP server to respond */ 
  58                 timer_set(&AppState
->DHCPClient
.Timeout
, CLOCK_SECOND 
/ 2); 
  62 /** uIP stack application callback for the DHCP client. This function must be called each time the TCP/IP stack 
  63  *  needs a UDP packet to be processed. 
  65 void DHCPClientApp_Callback(void) 
  67         uip_udp_appstate_t
* const AppState    
= &uip_udp_conn
->appstate
; 
  68         DHCP_Header_t
*      const AppData     
= (DHCP_Header_t
*)uip_appdata
; 
  69         uint16_t                  AppDataSize 
= 0; 
  71         switch (AppState
->DHCPClient
.CurrentState
) 
  73                 case DHCP_STATE_SendDiscover
: 
  74                         /* Clear all DHCP settings, reset client IP address */ 
  75                         memset(&AppState
->DHCPClient
.DHCPOffer_Data
, 0x00, sizeof(AppState
->DHCPClient
.DHCPOffer_Data
)); 
  76                         uip_sethostaddr((uip_ipaddr_t
*)&AppState
->DHCPClient
.DHCPOffer_Data
.AllocatedIP
); 
  78                         /* Fill out the DHCP response header */ 
  79                         AppDataSize 
+= DHCPClientApp_FillDHCPHeader(AppData
, DHCP_DISCOVER
, AppState
); 
  81                         /* Add the required DHCP options list to the packet */ 
  82                         uint8_t RequiredOptionList
[] = {DHCP_OPTION_SUBNET_MASK
, DHCP_OPTION_ROUTER
, DHCP_OPTION_DNS_SERVER
}; 
  83                         AppDataSize 
+= DHCPClientApp_SetOption(AppData
->Options
, DHCP_OPTION_REQ_LIST
, sizeof(RequiredOptionList
), 
  86                         /* Send the DHCP DISCOVER packet */ 
  87                         uip_udp_send(AppDataSize
); 
  89                         /* Reset the timeout timer, progress to next state */ 
  90                         timer_reset(&AppState
->DHCPClient
.Timeout
); 
  91                         AppState
->DHCPClient
.CurrentState 
= DHCP_STATE_WaitForOffer
; 
  94                 case DHCP_STATE_WaitForOffer
: 
  97                                 /* Check if the DHCP timeout period has expired while waiting for a response */ 
  98                                 if (timer_expired(&AppState
->DHCPClient
.Timeout
)) 
  99                                   AppState
->DHCPClient
.CurrentState 
= DHCP_STATE_SendDiscover
; 
 104                         uint8_t OfferResponse_MessageType
; 
 105                         if ((AppData
->TransactionID 
== DHCP_TRANSACTION_ID
) && 
 106                             DHCPClientApp_GetOption(AppData
->Options
, DHCP_OPTION_MSG_TYPE
, &OfferResponse_MessageType
) && 
 107                             (OfferResponse_MessageType 
== DHCP_OFFER
)) 
 109                                 /* Received a DHCP offer for an IP address, copy over values for later request */ 
 110                                 memcpy(&AppState
->DHCPClient
.DHCPOffer_Data
.AllocatedIP
, &AppData
->YourIP
, sizeof(uip_ipaddr_t
)); 
 111                                 DHCPClientApp_GetOption(AppData
->Options
, DHCP_OPTION_SUBNET_MASK
, &AppState
->DHCPClient
.DHCPOffer_Data
.Netmask
); 
 112                                 DHCPClientApp_GetOption(AppData
->Options
, DHCP_OPTION_ROUTER
,      &AppState
->DHCPClient
.DHCPOffer_Data
.GatewayIP
); 
 113                                 DHCPClientApp_GetOption(AppData
->Options
, DHCP_OPTION_SERVER_ID
,   &AppState
->DHCPClient
.DHCPOffer_Data
.ServerIP
); 
 115                                 timer_reset(&AppState
->DHCPClient
.Timeout
); 
 116                                 AppState
->DHCPClient
.CurrentState 
= DHCP_STATE_SendRequest
; 
 120                 case DHCP_STATE_SendRequest
: 
 121                         /* Fill out the DHCP response header */ 
 122                         AppDataSize 
+= DHCPClientApp_FillDHCPHeader(AppData
, DHCP_REQUEST
, AppState
); 
 124                         /* Add the DHCP REQUESTED IP ADDRESS option to the packet */ 
 125                         AppDataSize 
+= DHCPClientApp_SetOption(AppData
->Options
, DHCP_OPTION_REQ_IPADDR
, sizeof(uip_ipaddr_t
), 
 126                                                                &AppState
->DHCPClient
.DHCPOffer_Data
.AllocatedIP
); 
 128                         /* Add the DHCP SERVER IP ADDRESS option to the packet */ 
 129                         AppDataSize 
+= DHCPClientApp_SetOption(AppData
->Options
, DHCP_OPTION_SERVER_ID
, sizeof(uip_ipaddr_t
), 
 130                                                                &AppState
->DHCPClient
.DHCPOffer_Data
.ServerIP
); 
 132                         /* Send the DHCP REQUEST packet */ 
 133                         uip_udp_send(AppDataSize
); 
 135                         /* Reset the timeout timer, progress to next state */ 
 136                         timer_reset(&AppState
->DHCPClient
.Timeout
); 
 137                         AppState
->DHCPClient
.CurrentState 
= DHCP_STATE_WaitForACK
; 
 140                 case DHCP_STATE_WaitForACK
: 
 141                         if (!(uip_newdata())) 
 143                                 /* Check if the DHCP timeout period has expired while waiting for a response */ 
 144                                 if (timer_expired(&AppState
->DHCPClient
.Timeout
)) 
 145                                   AppState
->DHCPClient
.CurrentState 
= DHCP_STATE_SendDiscover
; 
 150                         uint8_t RequestResponse_MessageType
; 
 151                         if ((AppData
->TransactionID 
== DHCP_TRANSACTION_ID
) && 
 152                             DHCPClientApp_GetOption(AppData
->Options
, DHCP_OPTION_MSG_TYPE
, &RequestResponse_MessageType
) && 
 153                             (RequestResponse_MessageType 
== DHCP_ACK
)) 
 155                                 /* Set the new network parameters from the DHCP server */ 
 156                                 uip_sethostaddr((uip_ipaddr_t
*)&AppState
->DHCPClient
.DHCPOffer_Data
.AllocatedIP
); 
 157                                 uip_setnetmask((uip_ipaddr_t
*)&AppState
->DHCPClient
.DHCPOffer_Data
.Netmask
); 
 158                                 uip_setdraddr((uip_ipaddr_t
*)&AppState
->DHCPClient
.DHCPOffer_Data
.GatewayIP
); 
 160                                 /* Indicate to the user that we now have a valid IP configuration */ 
 161                                 HaveIPConfiguration 
= true; 
 163                                 AppState
->DHCPClient
.CurrentState 
= DHCP_STATE_AddressLeased
; 
 170 /** Fills the DHCP packet response with the appropriate BOOTP header for DHCP. This fills out all the required 
 171  *  fields, leaving only the additional DHCP options to be added to the packet before it is sent to the DHCP server. 
 173  *  \param[out] DHCPHeader       Location in the packet buffer where the BOOTP header should be written to 
 174  *  \param[in]  DHCPMessageType  DHCP Message type, such as DHCP_DISCOVER 
 175  *  \param[in]  AppState         Application state of the current UDP connection 
 177  *  \return Size in bytes of the created DHCP packet 
 179 static uint16_t DHCPClientApp_FillDHCPHeader(DHCP_Header_t
* const DHCPHeader
, 
 180                                              const uint8_t DHCPMessageType
, 
 181                                              uip_udp_appstate_t
* const AppState
) 
 183         /* Erase existing packet data so that we start will all 0x00 DHCP header data */ 
 184         memset(DHCPHeader
, 0, sizeof(DHCP_Header_t
)); 
 186         /* Fill out the DHCP packet header */ 
 187         DHCPHeader
->Operation             
= DHCP_OP_BOOTREQUEST
; 
 188         DHCPHeader
->HardwareType          
= DHCP_HTYPE_ETHERNET
; 
 189         DHCPHeader
->HardwareAddressLength 
= sizeof(MACAddress
); 
 190         DHCPHeader
->Hops                  
= 0; 
 191         DHCPHeader
->TransactionID         
= DHCP_TRANSACTION_ID
; 
 192         DHCPHeader
->ElapsedSeconds        
= 0; 
 193         DHCPHeader
->Flags                 
= HTONS(BOOTP_BROADCAST
); 
 194         memcpy(&DHCPHeader
->ClientIP
,     &uip_hostaddr
,        sizeof(uip_ipaddr_t
)); 
 195         memcpy(&DHCPHeader
->YourIP
,       &AppState
->DHCPClient
.DHCPOffer_Data
.AllocatedIP
, sizeof(uip_ipaddr_t
)); 
 196         memcpy(&DHCPHeader
->NextServerIP
, &AppState
->DHCPClient
.DHCPOffer_Data
.ServerIP
,    sizeof(uip_ipaddr_t
)); 
 197         memcpy(&DHCPHeader
->ClientHardwareAddress
, &MACAddress
, sizeof(struct uip_eth_addr
)); 
 198         DHCPHeader
->Cookie                
= DHCP_MAGIC_COOKIE
; 
 200         /* Add a DHCP message type and terminator options to the start of the DHCP options field */ 
 201         DHCPHeader
->Options
[0]            = DHCP_OPTION_MSG_TYPE
; 
 202         DHCPHeader
->Options
[1]            = 1; 
 203         DHCPHeader
->Options
[2]            = DHCPMessageType
; 
 204         DHCPHeader
->Options
[3]            = DHCP_OPTION_END
; 
 206         /* Calculate the total number of bytes added to the outgoing packet */ 
 207         return (sizeof(DHCP_Header_t
) + 4); 
 210 /** Sets the given DHCP option in the DHCP packet's option list. This automatically moves the 
 211  *  end of options terminator past the new option in the options list. 
 213  *  \param[in,out] DHCPOptionList  Pointer to the start of the DHCP packet's options list 
 214  *  \param[in]     Option          DHCP option to add to the list 
 215  *  \param[in]     DataLen         Size in bytes of the option data to add 
 216  *  \param[in]     OptionData      Buffer where the option's data is to be sourced from 
 218  *  \return Number of bytes added to the DHCP packet 
 220 static uint8_t DHCPClientApp_SetOption(uint8_t* DHCPOptionList
, 
 221                                        const uint8_t Option
, 
 222                                        const uint8_t DataLen
, 
 223                                        void* const OptionData
) 
 225         /* Skip through the DHCP options list until the terminator option is found */ 
 226         while (*DHCPOptionList 
!= DHCP_OPTION_END
) 
 227           DHCPOptionList 
+= (DHCPOptionList
[1] + 2); 
 229         /* Overwrite the existing terminator with the new option, add a new terminator at the end of the list */ 
 230         DHCPOptionList
[0] = Option
; 
 231         DHCPOptionList
[1] = DataLen
; 
 232         memcpy(&DHCPOptionList
[2], OptionData
, DataLen
); 
 233         DHCPOptionList
[2 + DataLen
] = DHCP_OPTION_END
; 
 235         /* Calculate the total number of bytes added to the outgoing packet */ 
 236         return (2 + DataLen
); 
 239 /** Retrieves the given option's data (if present) from the DHCP packet's options list. 
 241  *  \param[in,out] DHCPOptionList  Pointer to the start of the DHCP packet's options list 
 242  *  \param[in]     Option          DHCP option to retrieve to the list 
 243  *  \param[out]    Destination     Buffer where the option's data is to be written to if found 
 245  *  \return Boolean true if the option was found in the DHCP packet's options list, false otherwise 
 247 static bool DHCPClientApp_GetOption(const uint8_t* DHCPOptionList
, 
 248                                     const uint8_t Option
, 
 249                                     void* const Destination
) 
 251         /* Look through the incoming DHCP packet's options list for the requested option */ 
 252         while (*DHCPOptionList 
!= DHCP_OPTION_END
) 
 254                 /* Check if the current DHCP option in the packet is the one requested */ 
 255                 if (DHCPOptionList
[0] == Option
) 
 257                         /* Copy request option's data to the destination buffer */ 
 258                         memcpy(Destination
, &DHCPOptionList
[2], DHCPOptionList
[1]); 
 260                         /* Indicate that the requested option data was successfully retrieved */ 
 264                 /* Skip to next DHCP option in the options list */ 
 265                 DHCPOptionList 
+= (DHCPOptionList
[1] + 2); 
 268         /* Requested option not found in the incoming packet's DHCP options list */