0e51d5707251ea6f0976f73f90bd408b5d02e5e6
[pub/USBasp.git] / Projects / Webserver / Lib / DHCPClientApp.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2010.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
7 */
8
9 /*
10 Copyright 2010 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
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.
20
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
28 this software.
29 */
30
31 /** \file
32 *
33 * DHCP Client Application. When connected to the uIP stack, this will retrieve IP configuration settings from the
34 * DHCP server on the network.
35 */
36
37 #include "DHCPClientApp.h"
38
39 #if defined(ENABLE_DHCP_CLIENT) || defined(__DOXYGEN__)
40 /** Timer for managing the timeout period for a DHCP server to respond */
41 struct timer DHCPTimer;
42
43 /** Initialization function for the DHCP client. */
44 void DHCPClientApp_Init(void)
45 {
46 /* Create an IP address to the broadcast network address */
47 uip_ipaddr_t DHCPServerIPAddress;
48 uip_ipaddr(&DHCPServerIPAddress, 255, 255, 255, 255);
49
50 /* Create a new UDP connection to the DHCP server port for the DHCP solicitation */
51 struct uip_udp_conn* Connection = uip_udp_new(&DHCPServerIPAddress, HTONS(DHCPC_SERVER_PORT));
52
53 /* If the connection was successfully created, bind it to the local DHCP client port */
54 if (Connection != NULL)
55 {
56 uip_udp_appstate_t* const AppState = &Connection->appstate;
57
58 uip_udp_bind(Connection, HTONS(DHCPC_CLIENT_PORT));
59 AppState->DHCPClient.CurrentState = DHCP_STATE_SendDiscover;
60 }
61
62 /* Set timeout period to half a second for a DHCP server to respond */
63 timer_set(&DHCPTimer, CLOCK_SECOND / 2);
64 }
65
66 /** uIP stack application callback for the DHCP client. This function must be called each time the TCP/IP stack
67 * needs a UDP packet to be processed.
68 */
69 void DHCPClientApp_Callback(void)
70 {
71 uip_udp_appstate_t* const AppState = &uip_udp_conn->appstate;
72 DHCP_Header_t* const AppData = (DHCP_Header_t*)uip_appdata;
73 uint16_t AppDataSize = 0;
74
75 switch (AppState->DHCPClient.CurrentState)
76 {
77 case DHCP_STATE_SendDiscover:
78 /* Clear all DHCP settings, reset client IP address */
79 memset(&AppState->DHCPClient.DHCPOffer_Data, 0x00, sizeof(AppState->DHCPClient.DHCPOffer_Data));
80 uip_sethostaddr((uip_ipaddr_t*)&AppState->DHCPClient.DHCPOffer_Data.AllocatedIP);
81
82 /* Fill out the DHCP response header */
83 AppDataSize += DHCPClientApp_FillDHCPHeader(AppData, DHCP_DISCOVER, AppState);
84
85 /* Add the required DHCP options list to the packet */
86 uint8_t RequiredOptionList[] = {DHCP_OPTION_SUBNET_MASK, DHCP_OPTION_ROUTER, DHCP_OPTION_DNS_SERVER};
87 AppDataSize += DHCPClientApp_SetOption(AppData->Options, DHCP_OPTION_REQ_LIST, sizeof(RequiredOptionList),
88 RequiredOptionList);
89
90 /* Send the DHCP DISCOVER packet */
91 uip_udp_send(AppDataSize);
92
93 /* Reset the timeout timer, progress to next state */
94 timer_reset(&DHCPTimer);
95 AppState->DHCPClient.CurrentState = DHCP_STATE_WaitForOffer;
96
97 break;
98 case DHCP_STATE_WaitForOffer:
99 if (!(uip_newdata()))
100 {
101 /* Check if the DHCP timeout period has expired while waiting for a response */
102 if (timer_expired(&DHCPTimer))
103 AppState->DHCPClient.CurrentState = DHCP_STATE_SendDiscover;
104
105 break;
106 }
107
108 uint8_t OfferResponse_MessageType;
109 if ((AppData->TransactionID == DHCP_TRANSACTION_ID) &&
110 DHCPClientApp_GetOption(AppData->Options, DHCP_OPTION_MSG_TYPE, &OfferResponse_MessageType) &&
111 (OfferResponse_MessageType == DHCP_OFFER))
112 {
113 /* Received a DHCP offer for an IP address, copy over values for later request */
114 memcpy(&AppState->DHCPClient.DHCPOffer_Data.AllocatedIP, &AppData->YourIP, sizeof(uip_ipaddr_t));
115 DHCPClientApp_GetOption(AppData->Options, DHCP_OPTION_SUBNET_MASK, &AppState->DHCPClient.DHCPOffer_Data.Netmask);
116 DHCPClientApp_GetOption(AppData->Options, DHCP_OPTION_ROUTER, &AppState->DHCPClient.DHCPOffer_Data.GatewayIP);
117 DHCPClientApp_GetOption(AppData->Options, DHCP_OPTION_SERVER_ID, &AppState->DHCPClient.DHCPOffer_Data.ServerIP);
118
119 timer_reset(&DHCPTimer);
120 AppState->DHCPClient.CurrentState = DHCP_STATE_SendRequest;
121 }
122
123 break;
124 case DHCP_STATE_SendRequest:
125 /* Fill out the DHCP response header */
126 AppDataSize += DHCPClientApp_FillDHCPHeader(AppData, DHCP_REQUEST, AppState);
127
128 /* Add the DHCP REQUESTED IP ADDRESS option to the packet */
129 AppDataSize += DHCPClientApp_SetOption(AppData->Options, DHCP_OPTION_REQ_IPADDR, sizeof(uip_ipaddr_t),
130 &AppState->DHCPClient.DHCPOffer_Data.AllocatedIP);
131
132 /* Add the DHCP SERVER IP ADDRESS option to the packet */
133 AppDataSize += DHCPClientApp_SetOption(AppData->Options, DHCP_OPTION_SERVER_ID, sizeof(uip_ipaddr_t),
134 &AppState->DHCPClient.DHCPOffer_Data.ServerIP);
135
136 /* Send the DHCP REQUEST packet */
137 uip_udp_send(AppDataSize);
138
139 /* Reset the timeout timer, progress to next state */
140 timer_reset(&DHCPTimer);
141 AppState->DHCPClient.CurrentState = DHCP_STATE_WaitForACK;
142
143 break;
144 case DHCP_STATE_WaitForACK:
145 if (!(uip_newdata()))
146 {
147 /* Check if the DHCP timeout period has expired while waiting for a response */
148 if (timer_expired(&DHCPTimer))
149 AppState->DHCPClient.CurrentState = DHCP_STATE_SendDiscover;
150
151 break;
152 }
153
154 uint8_t RequestResponse_MessageType;
155 if ((AppData->TransactionID == DHCP_TRANSACTION_ID) &&
156 DHCPClientApp_GetOption(AppData->Options, DHCP_OPTION_MSG_TYPE, &RequestResponse_MessageType) &&
157 (RequestResponse_MessageType == DHCP_ACK))
158 {
159 /* Set the new network parameters from the DHCP server */
160 uip_sethostaddr((uip_ipaddr_t*)&AppState->DHCPClient.DHCPOffer_Data.AllocatedIP);
161 uip_setnetmask((uip_ipaddr_t*)&AppState->DHCPClient.DHCPOffer_Data.Netmask);
162 uip_setdraddr((uip_ipaddr_t*)&AppState->DHCPClient.DHCPOffer_Data.GatewayIP);
163
164 AppState->DHCPClient.CurrentState = DHCP_STATE_AddressLeased;
165 }
166
167 break;
168 }
169 }
170
171 /** Fills the DHCP packet response with the appropriate BOOTP header for DHCP. This fills out all the required
172 * fields, leaving only the additional DHCP options to be added to the packet before it is sent to the DHCP server.
173 *
174 * \param[out] DHCPHeader Location in the packet buffer where the BOOTP header should be written to
175 * \param[in] DHCPMessageType DHCP Message type, such as DHCP_DISCOVER
176 * \param[in] AppState Application state of the current UDP connection
177 *
178 * \return Size in bytes of the created DHCP packet
179 */
180 uint16_t DHCPClientApp_FillDHCPHeader(DHCP_Header_t* DHCPHeader, uint8_t DHCPMessageType, uip_udp_appstate_t* AppState)
181 {
182 /* Erase existing packet data so that we start will all 0x00 DHCP header data */
183 memset(DHCPHeader, 0, sizeof(DHCP_Header_t));
184
185 /* Fill out the DHCP packet header */
186 DHCPHeader->Operation = DHCP_OP_BOOTREQUEST;
187 DHCPHeader->HardwareType = DHCP_HTYPE_ETHERNET;
188 DHCPHeader->HardwareAddressLength = sizeof(MACAddress);
189 DHCPHeader->Hops = 0;
190 DHCPHeader->TransactionID = DHCP_TRANSACTION_ID;
191 DHCPHeader->ElapsedSeconds = 0;
192 DHCPHeader->Flags = HTONS(BOOTP_BROADCAST);
193 memcpy(&DHCPHeader->ClientIP, &uip_hostaddr, sizeof(uip_ipaddr_t));
194 memcpy(&DHCPHeader->YourIP, &AppState->DHCPClient.DHCPOffer_Data.AllocatedIP, sizeof(uip_ipaddr_t));
195 memcpy(&DHCPHeader->NextServerIP, &AppState->DHCPClient.DHCPOffer_Data.ServerIP, sizeof(uip_ipaddr_t));
196 memcpy(&DHCPHeader->ClientHardwareAddress, &MACAddress, sizeof(struct uip_eth_addr));
197 DHCPHeader->Cookie = DHCP_MAGIC_COOKIE;
198
199 /* Add a DHCP message type and terminator options to the start of the DHCP options field */
200 DHCPHeader->Options[0] = DHCP_OPTION_MSG_TYPE;
201 DHCPHeader->Options[1] = 1;
202 DHCPHeader->Options[2] = DHCPMessageType;
203 DHCPHeader->Options[3] = DHCP_OPTION_END;
204
205 /* Calculate the total number of bytes added to the outgoing packet */
206 return (sizeof(DHCP_Header_t) + 4);
207 }
208
209 /** Sets the given DHCP option in the DHCP packet's option list. This automatically moves the
210 * end of options terminator past the new option in the options list.
211 *
212 * \param[in,out] DHCPOptionList Pointer to the start of the DHCP packet's options list
213 * \param[in] Option DHCP option to add to the list
214 * \param[in] DataLen Size in bytes of the option data to add
215 * \param[in] OptionData Buffer where the option's data is to be sourced from
216 *
217 * \return Number of bytes added to the DHCP packet
218 */
219 uint8_t DHCPClientApp_SetOption(uint8_t* DHCPOptionList, uint8_t Option, uint8_t DataLen, void* OptionData)
220 {
221 /* Skip through the DHCP options list until the terminator option is found */
222 while (*DHCPOptionList != DHCP_OPTION_END)
223 DHCPOptionList += (DHCPOptionList[1] + 2);
224
225 /* Overwrite the existing terminator with the new option, add a new terminator at the end of the list */
226 DHCPOptionList[0] = Option;
227 DHCPOptionList[1] = DataLen;
228 memcpy(&DHCPOptionList[2], OptionData, DataLen);
229 DHCPOptionList[2 + DataLen] = DHCP_OPTION_END;
230
231 /* Calculate the total number of bytes added to the outgoing packet */
232 return (2 + DataLen);
233 }
234
235 /** Retrieves the given option's data (if present) from the DHCP packet's options list.
236 *
237 * \param[in,out] DHCPOptionList Pointer to the start of the DHCP packet's options list
238 * \param[in] Option DHCP option to retrieve to the list
239 * \param[out] Destination Buffer where the option's data is to be written to if found
240 *
241 * \return Boolean true if the option was found in the DHCP packet's options list, false otherwise
242 */
243 bool DHCPClientApp_GetOption(uint8_t* DHCPOptionList, uint8_t Option, void* Destination)
244 {
245 /* Look through the incoming DHCP packet's options list for the requested option */
246 while (*DHCPOptionList != DHCP_OPTION_END)
247 {
248 /* Check if the current DHCP option in the packet is the one requested */
249 if (DHCPOptionList[0] == Option)
250 {
251 /* Copy request option's data to the destination buffer */
252 memcpy(Destination, &DHCPOptionList[2], DHCPOptionList[1]);
253
254 /* Indicate that the requested option data was successfully retrieved */
255 return true;
256 }
257
258 /* Skip to next DHCP option in the options list */
259 DHCPOptionList += (DHCPOptionList[1] + 2);
260 }
261
262 /* Requested option not found in the incoming packet's DHCP options list */
263 return false;
264 }
265 #endif