• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * @file
3  * Dynamic Host Configuration Protocol client
4  *
5  * @defgroup dhcp4 DHCPv4
6  * @ingroup ip4
7  * DHCP (IPv4) related functions
8  * This is a DHCP client for the lwIP TCP/IP stack. It aims to conform
9  * with RFC 2131 and RFC 2132.
10  *
11  * @todo:
12  * - Support for interfaces other than Ethernet (SLIP, PPP, ...)
13  *
14  * Options:
15  * @ref DHCP_COARSE_TIMER_SECS (recommended 60 which is a minute)
16  * @ref DHCP_FINE_TIMER_MSECS (recommended 500 which equals TCP coarse timer)
17  *
18  * dhcp_start() starts a DHCP client instance which
19  * configures the interface by obtaining an IP address lease and maintaining it.
20  *
21  * Use dhcp_release() to end the lease and use dhcp_stop()
22  * to remove the DHCP client.
23  *
24  * @see LWIP_HOOK_DHCP_APPEND_OPTIONS
25  * @see LWIP_HOOK_DHCP_PARSE_OPTION
26  *
27  * @see netifapi_dhcp4
28  */
29 
30 /*
31  * Copyright (c) 2001-2004 Leon Woestenberg <leon.woestenberg@gmx.net>
32  * Copyright (c) 2001-2004 Axon Digital Design B.V., The Netherlands.
33  * All rights reserved.
34  *
35  * Redistribution and use in source and binary forms, with or without modification,
36  * are permitted provided that the following conditions are met:
37  *
38  * 1. Redistributions of source code must retain the above copyright notice,
39  *    this list of conditions and the following disclaimer.
40  * 2. Redistributions in binary form must reproduce the above copyright notice,
41  *    this list of conditions and the following disclaimer in the documentation
42  *    and/or other materials provided with the distribution.
43  * 3. The name of the author may not be used to endorse or promote products
44  *    derived from this software without specific prior written permission.
45  *
46  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
47  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
48  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
49  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
50  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
51  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
52  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
53  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
54  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
55  * OF SUCH DAMAGE.
56  *
57  * This file is part of the lwIP TCP/IP stack.
58  * The Swedish Institute of Computer Science and Adam Dunkels
59  * are specifically granted permission to redistribute this
60  * source code.
61  *
62  * Author: Leon Woestenberg <leon.woestenberg@gmx.net>
63  *
64  */
65 
66 #include "lwip/opt.h"
67 
68 #if LWIP_IPV4 && LWIP_DHCP /* don't build if not configured for use in lwipopts.h */
69 
70 #include "lwip/stats.h"
71 #include "lwip/mem.h"
72 #include "lwip/udp.h"
73 #include "lwip/ip_addr.h"
74 #include "lwip/netif.h"
75 #include "lwip/def.h"
76 #include "lwip/dhcp.h"
77 #include "lwip/autoip.h"
78 #include "lwip/dns.h"
79 #include "lwip/etharp.h"
80 #include "lwip/prot/dhcp.h"
81 #include "lwip/prot/iana.h"
82 
83 #include <string.h>
84 
85 #ifdef LWIP_HOOK_FILENAME
86 #include LWIP_HOOK_FILENAME
87 #endif
88 #ifndef LWIP_HOOK_DHCP_APPEND_OPTIONS
89 #define LWIP_HOOK_DHCP_APPEND_OPTIONS(netif, dhcp, state, msg, msg_type, options_len_ptr)
90 #endif
91 #ifndef LWIP_HOOK_DHCP_PARSE_OPTION
92 #define LWIP_HOOK_DHCP_PARSE_OPTION(netif, dhcp, state, msg, msg_type, option, len, pbuf, offset) do { LWIP_UNUSED_ARG(msg); } while(0)
93 #endif
94 
95 /** DHCP_CREATE_RAND_XID: if this is set to 1, the xid is created using
96  * LWIP_RAND() (this overrides DHCP_GLOBAL_XID)
97  */
98 #ifndef DHCP_CREATE_RAND_XID
99 #define DHCP_CREATE_RAND_XID        1
100 #endif
101 
102 /** Default for DHCP_GLOBAL_XID is 0xABCD0000
103  * This can be changed by defining DHCP_GLOBAL_XID and DHCP_GLOBAL_XID_HEADER, e.g.
104  *  \#define DHCP_GLOBAL_XID_HEADER "stdlib.h"
105  *  \#define DHCP_GLOBAL_XID rand()
106  */
107 #ifdef DHCP_GLOBAL_XID_HEADER
108 #include DHCP_GLOBAL_XID_HEADER /* include optional starting XID generation prototypes */
109 #endif
110 
111 /** DHCP_OPTION_MAX_MSG_SIZE is set to the MTU
112  * MTU is checked to be big enough in dhcp_start */
113 #define DHCP_MAX_MSG_LEN(netif)        (netif->mtu)
114 #define DHCP_MAX_MSG_LEN_MIN_REQUIRED  576
115 /** Minimum length for reply before packet is parsed */
116 #define DHCP_MIN_REPLY_LEN             44
117 
118 #define REBOOT_TRIES                2
119 #if 0 /* The following codes are moved to dhcp.h for fixing it's todo, kept here just for notice */
120 #if LWIP_DNS && LWIP_DHCP_MAX_DNS_SERVERS
121 #if DNS_MAX_SERVERS > LWIP_DHCP_MAX_DNS_SERVERS
122 #define LWIP_DHCP_PROVIDE_DNS_SERVERS LWIP_DHCP_MAX_DNS_SERVERS
123 #else
124 #define LWIP_DHCP_PROVIDE_DNS_SERVERS DNS_MAX_SERVERS
125 #endif
126 #else
127 #define LWIP_DHCP_PROVIDE_DNS_SERVERS 0
128 #endif
129 
130 /** Option handling: options are parsed in dhcp_parse_reply
131  * and saved in an array where other functions can load them from.
132  * This might be moved into the struct dhcp (not necessarily since
133  * lwIP is single-threaded and the array is only used while in recv
134  * callback). */
135 enum dhcp_option_idx {
136   DHCP_OPTION_IDX_OVERLOAD = 0,
137   DHCP_OPTION_IDX_MSG_TYPE,
138   DHCP_OPTION_IDX_SERVER_ID,
139   DHCP_OPTION_IDX_LEASE_TIME,
140   DHCP_OPTION_IDX_T1,
141   DHCP_OPTION_IDX_T2,
142   DHCP_OPTION_IDX_SUBNET_MASK,
143   DHCP_OPTION_IDX_ROUTER,
144 #if LWIP_DHCP_PROVIDE_DNS_SERVERS
145   DHCP_OPTION_IDX_DNS_SERVER,
146   DHCP_OPTION_IDX_DNS_SERVER_LAST = DHCP_OPTION_IDX_DNS_SERVER + LWIP_DHCP_PROVIDE_DNS_SERVERS - 1,
147 #endif /* LWIP_DHCP_PROVIDE_DNS_SERVERS */
148 #if LWIP_DHCP_GET_NTP_SRV
149   DHCP_OPTION_IDX_NTP_SERVER,
150   DHCP_OPTION_IDX_NTP_SERVER_LAST = DHCP_OPTION_IDX_NTP_SERVER + LWIP_DHCP_MAX_NTP_SERVERS - 1,
151 #endif /* LWIP_DHCP_GET_NTP_SRV */
152   DHCP_OPTION_IDX_MAX
153 };
154 
155 /** Holds the decoded option values, only valid while in dhcp_recv.
156     @todo: move this into struct dhcp? */
157 u32_t dhcp_rx_options_val[DHCP_OPTION_IDX_MAX];
158 /** Holds a flag which option was received and is contained in dhcp_rx_options_val,
159     only valid while in dhcp_recv.
160     @todo: move this into struct dhcp? */
161 u8_t  dhcp_rx_options_given[DHCP_OPTION_IDX_MAX];
162 #endif
163 
164 #ifndef LWIP_DHCP_INPUT_ERROR
165 #define LWIP_DHCP_INPUT_ERROR(message, expression, handler) do { if (!(expression)) { \
166   handler;} } while(0)
167 #endif
168 
169 static u8_t dhcp_discover_request_options[] = {
170   DHCP_OPTION_SUBNET_MASK,
171   DHCP_OPTION_ROUTER,
172   DHCP_OPTION_BROADCAST
173 #if LWIP_DHCP_PROVIDE_DNS_SERVERS
174   , DHCP_OPTION_DNS_SERVER
175 #endif /* LWIP_DHCP_PROVIDE_DNS_SERVERS */
176 #if LWIP_DHCP_GET_NTP_SRV
177   , DHCP_OPTION_NTP
178 #endif /* LWIP_DHCP_GET_NTP_SRV */
179 };
180 
181 #ifdef DHCP_GLOBAL_XID
182 static u32_t xid;
183 static u8_t xid_initialised;
184 #endif /* DHCP_GLOBAL_XID */
185 
186 #define dhcp_option_given(dhcp, idx)          ((dhcp)->rx_options_given[idx] != 0)
187 #define dhcp_got_option(dhcp, idx)            ((dhcp)->rx_options_given[idx] = 1)
188 #define dhcp_clear_option(dhcp, idx)          ((dhcp)->rx_options_given[idx] = 0)
189 #define dhcp_clear_all_options(dhcp)          (memset((dhcp)->rx_options_given, 0, sizeof((dhcp)->rx_options_given)))
190 #define dhcp_get_option_value(dhcp, idx)      ((dhcp)->rx_options_val[idx])
191 #define dhcp_set_option_value(dhcp, idx, val) ((dhcp)->rx_options_val[idx] = (val))
192 
193 static struct udp_pcb *dhcp_pcb;
194 static u8_t dhcp_pcb_refcount;
195 
196 /* DHCP client state machine functions */
197 static err_t dhcp_discover(struct netif *netif);
198 static err_t dhcp_select(struct netif *netif);
199 static void dhcp_bind(struct netif *netif);
200 #if DHCP_DOES_ARP_CHECK
201 static err_t dhcp_decline(struct netif *netif);
202 #endif /* DHCP_DOES_ARP_CHECK */
203 static err_t dhcp_rebind(struct netif *netif);
204 static err_t dhcp_reboot(struct netif *netif);
205 static void dhcp_set_state(struct dhcp *dhcp, u8_t new_state);
206 
207 /* receive, unfold, parse and free incoming messages */
208 static void dhcp_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port);
209 
210 /* set the DHCP timers */
211 static void dhcp_timeout(struct netif *netif);
212 static void dhcp_t1_timeout(struct netif *netif);
213 static void dhcp_t2_timeout(struct netif *netif);
214 
215 /* build outgoing messages */
216 /* create a DHCP message, fill in common headers */
217 static struct pbuf *dhcp_create_msg(struct netif *netif, struct dhcp *dhcp, u8_t message_type, u16_t *options_out_len);
218 /* add a DHCP option (type, then length in bytes) */
219 static u16_t dhcp_option(u16_t options_out_len, u8_t *options, u8_t option_type, u8_t option_len);
220 /* add option values */
221 static u16_t dhcp_option_byte(u16_t options_out_len, u8_t *options, u8_t value);
222 static u16_t dhcp_option_short(u16_t options_out_len, u8_t *options, u16_t value);
223 static u16_t dhcp_option_long(u16_t options_out_len, u8_t *options, u32_t value);
224 #if LWIP_NETIF_HOSTNAME
225 static u16_t dhcp_option_hostname(u16_t options_out_len, u8_t *options, struct netif *netif);
226 #endif /* LWIP_NETIF_HOSTNAME */
227 /* always add the DHCP options trailer to end and pad */
228 static void dhcp_option_trailer(u16_t options_out_len, u8_t *options, struct pbuf *p_out);
229 
230 /** Ensure DHCP PCB is allocated and bound */
231 static err_t
dhcp_inc_pcb_refcount(void)232 dhcp_inc_pcb_refcount(void)
233 {
234   if (dhcp_pcb_refcount == 0) {
235     LWIP_ASSERT("dhcp_inc_pcb_refcount(): memory leak", dhcp_pcb == NULL);
236 
237     /* allocate UDP PCB */
238     dhcp_pcb = udp_new();
239 
240     if (dhcp_pcb == NULL) {
241       return ERR_MEM;
242     }
243 
244     ip_set_option(dhcp_pcb, SOF_BROADCAST);
245 
246     /* set up local and remote port for the pcb -> listen on all interfaces on all src/dest IPs */
247     udp_bind(dhcp_pcb, IP4_ADDR_ANY, LWIP_IANA_PORT_DHCP_CLIENT);
248     udp_connect(dhcp_pcb, IP4_ADDR_ANY, LWIP_IANA_PORT_DHCP_SERVER);
249     udp_recv(dhcp_pcb, dhcp_recv, NULL);
250   }
251 
252   dhcp_pcb_refcount++;
253 
254   return ERR_OK;
255 }
256 
257 /** Free DHCP PCB if the last netif stops using it */
258 static void
dhcp_dec_pcb_refcount(void)259 dhcp_dec_pcb_refcount(void)
260 {
261   LWIP_ASSERT("dhcp_pcb_refcount(): refcount error", (dhcp_pcb_refcount > 0));
262   dhcp_pcb_refcount--;
263 
264   if (dhcp_pcb_refcount == 0) {
265     udp_remove(dhcp_pcb);
266     dhcp_pcb = NULL;
267   }
268 }
269 
270 /**
271  * Back-off the DHCP client (because of a received NAK response).
272  *
273  * Back-off the DHCP client because of a received NAK. Receiving a
274  * NAK means the client asked for something non-sensible, for
275  * example when it tries to renew a lease obtained on another network.
276  *
277  * We clear any existing set IP address and restart DHCP negotiation
278  * afresh (as per RFC2131 3.2.3).
279  *
280  * @param netif the netif under DHCP control
281  */
282 static void
dhcp_handle_nak(struct netif * netif)283 dhcp_handle_nak(struct netif *netif)
284 {
285   struct dhcp *dhcp = netif_dhcp_data(netif);
286 
287   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_handle_nak(netif=%p) %c%c%"U16_F"\n",
288               (void *)netif, netif->name[0], netif->name[1], (u16_t)netif->num));
289   /* Change to a defined state - set this before assigning the address
290      to ensure the callback can use dhcp_supplied_address() */
291   dhcp_set_state(dhcp, DHCP_STATE_BACKING_OFF);
292   /* remove IP address from interface (must no longer be used, as per RFC2131) */
293   netif_set_addr(netif, IP4_ADDR_ANY4, IP4_ADDR_ANY4, IP4_ADDR_ANY4);
294   /* We can immediately restart discovery */
295   dhcp_discover(netif);
296 }
297 
298 #if DHCP_DOES_ARP_CHECK
299 /**
300  * Checks if the offered IP address is already in use.
301  *
302  * It does so by sending an ARP request for the offered address and
303  * entering CHECKING state. If no ARP reply is received within a small
304  * interval, the address is assumed to be free for use by us.
305  *
306  * @param netif the netif under DHCP control
307  */
308 static void
dhcp_check(struct netif * netif)309 dhcp_check(struct netif *netif)
310 {
311   struct dhcp *dhcp = netif_dhcp_data(netif);
312   err_t result;
313   u16_t msecs;
314   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_check(netif=%p) %c%c\n", (void *)netif, (s16_t)netif->name[0],
315               (s16_t)netif->name[1]));
316   dhcp_set_state(dhcp, DHCP_STATE_CHECKING);
317   /* create an ARP query for the offered IP address, expecting that no host
318      responds, as the IP address should not be in use. */
319   result = etharp_query(netif, &dhcp->offered_ip_addr, NULL);
320   if (result != ERR_OK) {
321     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("dhcp_check: could not perform ARP query\n"));
322   }
323   if (dhcp->tries < 255) {
324     dhcp->tries++;
325   }
326   msecs = 500;
327   dhcp->request_timeout = (u16_t)((msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS);
328   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_check(): set request timeout %"U16_F" msecs\n", msecs));
329 }
330 #endif /* DHCP_DOES_ARP_CHECK */
331 
332 /**
333  * Remember the configuration offered by a DHCP server.
334  *
335  * @param netif the netif under DHCP control
336  */
337 static void
dhcp_handle_offer(struct netif * netif,struct dhcp_msg * msg_in)338 dhcp_handle_offer(struct netif *netif, struct dhcp_msg *msg_in)
339 {
340   struct dhcp *dhcp = netif_dhcp_data(netif);
341 
342   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_handle_offer(netif=%p) %c%c%"U16_F"\n",
343               (void *)netif, netif->name[0], netif->name[1], (u16_t)netif->num));
344   /* obtain the server address */
345   if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_SERVER_ID)) {
346     dhcp->request_timeout = 0; /* stop timer */
347 
348     ip_addr_set_ip4_u32(&dhcp->server_ip_addr, lwip_htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_SERVER_ID)));
349     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_STATE, ("dhcp_handle_offer(): server 0x%08"X32_F"\n",
350                 ip4_addr_get_u32(ip_2_ip4(&dhcp->server_ip_addr))));
351     /* remember offered address */
352     ip4_addr_copy(dhcp->offered_ip_addr, msg_in->yiaddr);
353     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_STATE, ("dhcp_handle_offer(): offer for 0x%08"X32_F"\n",
354                 ip4_addr_get_u32(&dhcp->offered_ip_addr)));
355 
356     dhcp_select(netif);
357   } else {
358     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS,
359                 ("dhcp_handle_offer(netif=%p) did not get server ID!\n", (void *)netif));
360   }
361 }
362 
363 /**
364  * Select a DHCP server offer out of all offers.
365  *
366  * Simply select the first offer received.
367  *
368  * @param netif the netif under DHCP control
369  * @return lwIP specific error (see error.h)
370  */
371 static err_t
dhcp_select(struct netif * netif)372 dhcp_select(struct netif *netif)
373 {
374   struct dhcp *dhcp;
375   err_t result;
376   u16_t msecs;
377   u8_t i;
378   struct pbuf *p_out;
379   u16_t options_out_len;
380 
381   LWIP_ERROR("dhcp_select: netif != NULL", (netif != NULL), return ERR_ARG;);
382   dhcp = netif_dhcp_data(netif);
383   LWIP_ERROR("dhcp_select: dhcp != NULL", (dhcp != NULL), return ERR_VAL;);
384 
385   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_select(netif=%p) %c%c%"U16_F"\n", (void *)netif, netif->name[0], netif->name[1], (u16_t)netif->num));
386   dhcp_set_state(dhcp, DHCP_STATE_REQUESTING);
387 
388   /* create and initialize the DHCP message header */
389   p_out = dhcp_create_msg(netif, dhcp, DHCP_REQUEST, &options_out_len);
390   if (p_out != NULL) {
391     struct dhcp_msg *msg_out = (struct dhcp_msg *)p_out->payload;
392     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN);
393     options_out_len = dhcp_option_short(options_out_len, msg_out->options, DHCP_MAX_MSG_LEN(netif));
394 
395     /* MUST request the offered IP address */
396     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_REQUESTED_IP, 4);
397     options_out_len = dhcp_option_long(options_out_len, msg_out->options, lwip_ntohl(ip4_addr_get_u32(&dhcp->offered_ip_addr)));
398 
399     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_SERVER_ID, 4);
400     options_out_len = dhcp_option_long(options_out_len, msg_out->options, lwip_ntohl(ip4_addr_get_u32(ip_2_ip4(&dhcp->server_ip_addr))));
401 
402     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_PARAMETER_REQUEST_LIST, LWIP_ARRAYSIZE(dhcp_discover_request_options));
403     for (i = 0; i < LWIP_ARRAYSIZE(dhcp_discover_request_options); i++) {
404       options_out_len = dhcp_option_byte(options_out_len, msg_out->options, dhcp_discover_request_options[i]);
405     }
406 
407 #if LWIP_NETIF_HOSTNAME
408     options_out_len = dhcp_option_hostname(options_out_len, msg_out->options, netif);
409 #endif /* LWIP_NETIF_HOSTNAME */
410 
411     LWIP_HOOK_DHCP_APPEND_OPTIONS(netif, dhcp, DHCP_STATE_REQUESTING, msg_out, DHCP_REQUEST, &options_out_len);
412     dhcp_option_trailer(options_out_len, msg_out->options, p_out);
413 
414     /* send broadcast to any DHCP server */
415     result = udp_sendto_if_src(dhcp_pcb, p_out, IP_ADDR_BROADCAST, LWIP_IANA_PORT_DHCP_SERVER, netif, IP4_ADDR_ANY);
416     pbuf_free(p_out);
417     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_select: REQUESTING\n"));
418   } else {
419     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("dhcp_select: could not allocate DHCP request\n"));
420     result = ERR_MEM;
421   }
422   if (dhcp->tries < 255) {
423     dhcp->tries++;
424   }
425   msecs = (u16_t)((dhcp->tries < 6 ? 1 << dhcp->tries : 60) * 1000);
426   dhcp->request_timeout = (u16_t)((msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS);
427   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_STATE, ("dhcp_select(): set request timeout %"U16_F" msecs\n", msecs));
428   return result;
429 }
430 
431 /**
432  * The DHCP timer that checks for lease renewal/rebind timeouts.
433  * Must be called once a minute (see @ref DHCP_COARSE_TIMER_SECS).
434  */
435 void
dhcp_coarse_tmr(void)436 dhcp_coarse_tmr(void)
437 {
438   struct netif *netif;
439   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_coarse_tmr()\n"));
440   /* iterate through all network interfaces */
441   NETIF_FOREACH(netif) {
442     /* only act on DHCP configured interfaces */
443     struct dhcp *dhcp = netif_dhcp_data(netif);
444     if ((dhcp != NULL) && (dhcp->state != DHCP_STATE_OFF)) {
445       /* compare lease time to expire timeout */
446       if (dhcp->t0_timeout && (++dhcp->lease_used == dhcp->t0_timeout)) {
447         LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_coarse_tmr(): t0 timeout\n"));
448         /* this clients' lease time has expired */
449         dhcp_release_and_stop(netif);
450         dhcp_start(netif);
451         /* timer is active (non zero), and triggers (zeroes) now? */
452       } else if (dhcp->t2_rebind_time && (dhcp->t2_rebind_time-- == 1)) {
453         LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_coarse_tmr(): t2 timeout\n"));
454         /* this clients' rebind timeout triggered */
455         dhcp_t2_timeout(netif);
456         /* timer is active (non zero), and triggers (zeroes) now */
457       } else if (dhcp->t1_renew_time && (dhcp->t1_renew_time-- == 1)) {
458         LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_coarse_tmr(): t1 timeout\n"));
459         /* this clients' renewal timeout triggered */
460         dhcp_t1_timeout(netif);
461       }
462     }
463   }
464 }
465 
466 /**
467  * DHCP transaction timeout handling (this function must be called every 500ms,
468  * see @ref DHCP_FINE_TIMER_MSECS).
469  *
470  * A DHCP server is expected to respond within a short period of time.
471  * This timer checks whether an outstanding DHCP request is timed out.
472  */
473 void
dhcp_fine_tmr(void)474 dhcp_fine_tmr(void)
475 {
476   struct netif *netif;
477   /* loop through netif's */
478   NETIF_FOREACH(netif) {
479     struct dhcp *dhcp = netif_dhcp_data(netif);
480     /* only act on DHCP configured interfaces */
481     if (dhcp != NULL) {
482       /* timer is active (non zero), and is about to trigger now */
483       if (dhcp->request_timeout > 1) {
484         dhcp->request_timeout--;
485       } else if (dhcp->request_timeout == 1) {
486         dhcp->request_timeout--;
487         /* { dhcp->request_timeout == 0 } */
488         LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_fine_tmr(): request timeout\n"));
489         /* this client's request timeout triggered */
490         dhcp_timeout(netif);
491       }
492     }
493   }
494 }
495 
496 /**
497  * A DHCP negotiation transaction, or ARP request, has timed out.
498  *
499  * The timer that was started with the DHCP or ARP request has
500  * timed out, indicating no response was received in time.
501  *
502  * @param netif the netif under DHCP control
503  */
504 static void
dhcp_timeout(struct netif * netif)505 dhcp_timeout(struct netif *netif)
506 {
507   struct dhcp *dhcp = netif_dhcp_data(netif);
508 
509   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_timeout()\n"));
510   /* back-off period has passed, or server selection timed out */
511   if ((dhcp->state == DHCP_STATE_BACKING_OFF) || (dhcp->state == DHCP_STATE_SELECTING)) {
512     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_timeout(): restarting discovery\n"));
513     dhcp_discover(netif);
514     /* receiving the requested lease timed out */
515   } else if (dhcp->state == DHCP_STATE_REQUESTING) {
516     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_timeout(): REQUESTING, DHCP request timed out\n"));
517     if (dhcp->tries <= 5) {
518       dhcp_select(netif);
519     } else {
520       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_timeout(): REQUESTING, releasing, restarting\n"));
521       dhcp_release_and_stop(netif);
522       dhcp_start(netif);
523     }
524 #if DHCP_DOES_ARP_CHECK
525     /* received no ARP reply for the offered address (which is good) */
526   } else if (dhcp->state == DHCP_STATE_CHECKING) {
527     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_timeout(): CHECKING, ARP request timed out\n"));
528     if (dhcp->tries <= 1) {
529       dhcp_check(netif);
530       /* no ARP replies on the offered address,
531          looks like the IP address is indeed free */
532     } else {
533       /* bind the interface to the offered address */
534       dhcp_bind(netif);
535     }
536 #endif /* DHCP_DOES_ARP_CHECK */
537   } else if (dhcp->state == DHCP_STATE_REBOOTING) {
538     if (dhcp->tries < REBOOT_TRIES) {
539       dhcp_reboot(netif);
540     } else {
541       dhcp_discover(netif);
542     }
543   }
544 }
545 
546 /**
547  * The renewal period has timed out.
548  *
549  * @param netif the netif under DHCP control
550  */
551 static void
dhcp_t1_timeout(struct netif * netif)552 dhcp_t1_timeout(struct netif *netif)
553 {
554   struct dhcp *dhcp = netif_dhcp_data(netif);
555 
556   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_STATE, ("dhcp_t1_timeout()\n"));
557   if ((dhcp->state == DHCP_STATE_REQUESTING) || (dhcp->state == DHCP_STATE_BOUND) ||
558       (dhcp->state == DHCP_STATE_RENEWING)) {
559     /* just retry to renew - note that the rebind timer (t2) will
560      * eventually time-out if renew tries fail. */
561     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
562                 ("dhcp_t1_timeout(): must renew\n"));
563     /* This slightly different to RFC2131: DHCPREQUEST will be sent from state
564        DHCP_STATE_RENEWING, not DHCP_STATE_BOUND */
565     dhcp_renew(netif);
566     /* Calculate next timeout */
567     if (((dhcp->t2_timeout - dhcp->lease_used) / 2) >= ((60 + DHCP_COARSE_TIMER_SECS / 2) / DHCP_COARSE_TIMER_SECS)) {
568       dhcp->t1_renew_time = (u16_t)((dhcp->t2_timeout - dhcp->lease_used) / 2);
569     }
570   }
571 }
572 
573 /**
574  * The rebind period has timed out.
575  *
576  * @param netif the netif under DHCP control
577  */
578 static void
dhcp_t2_timeout(struct netif * netif)579 dhcp_t2_timeout(struct netif *netif)
580 {
581   struct dhcp *dhcp = netif_dhcp_data(netif);
582 
583   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_t2_timeout()\n"));
584   if ((dhcp->state == DHCP_STATE_REQUESTING) || (dhcp->state == DHCP_STATE_BOUND) ||
585       (dhcp->state == DHCP_STATE_RENEWING) || (dhcp->state == DHCP_STATE_REBINDING)) {
586     /* just retry to rebind */
587     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
588                 ("dhcp_t2_timeout(): must rebind\n"));
589     /* This slightly different to RFC2131: DHCPREQUEST will be sent from state
590        DHCP_STATE_REBINDING, not DHCP_STATE_BOUND */
591     dhcp_rebind(netif);
592     /* Calculate next timeout */
593     if (((dhcp->t0_timeout - dhcp->lease_used) / 2) >= ((60 + DHCP_COARSE_TIMER_SECS / 2) / DHCP_COARSE_TIMER_SECS)) {
594       dhcp->t2_rebind_time = (u16_t)((dhcp->t0_timeout - dhcp->lease_used) / 2);
595     }
596   }
597 }
598 
599 /**
600  * Handle a DHCP ACK packet
601  *
602  * @param netif the netif under DHCP control
603  */
604 static void
dhcp_handle_ack(struct netif * netif,struct dhcp_msg * msg_in)605 dhcp_handle_ack(struct netif *netif, struct dhcp_msg *msg_in)
606 {
607   struct dhcp *dhcp = netif_dhcp_data(netif);
608 
609 #if LWIP_DHCP_PROVIDE_DNS_SERVERS || LWIP_DHCP_GET_NTP_SRV
610   u8_t n;
611 #endif /* LWIP_DHCP_PROVIDE_DNS_SERVERS || LWIP_DHCP_GET_NTP_SRV */
612 #if LWIP_DHCP_GET_NTP_SRV
613   ip4_addr_t ntp_server_addrs[LWIP_DHCP_MAX_NTP_SERVERS];
614 #endif
615 
616   /* clear options we might not get from the ACK */
617   ip4_addr_set_zero(&dhcp->offered_sn_mask);
618   ip4_addr_set_zero(&dhcp->offered_gw_addr);
619 #if LWIP_DHCP_BOOTP_FILE
620   ip4_addr_set_zero(&dhcp->offered_si_addr);
621 #endif /* LWIP_DHCP_BOOTP_FILE */
622 
623   /* lease time given? */
624   if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_LEASE_TIME)) {
625     /* remember offered lease time */
626     dhcp->offered_t0_lease = dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_LEASE_TIME);
627   }
628   /* renewal period given? */
629   if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_T1)) {
630     /* remember given renewal period */
631     dhcp->offered_t1_renew = dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_T1);
632   } else {
633     /* calculate safe periods for renewal */
634     dhcp->offered_t1_renew = dhcp->offered_t0_lease / 2;
635   }
636 
637   /* renewal period given? */
638   if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_T2)) {
639     /* remember given rebind period */
640     dhcp->offered_t2_rebind = dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_T2);
641   } else {
642     /* calculate safe periods for rebinding (offered_t0_lease * 0.875 -> 87.5%)*/
643     dhcp->offered_t2_rebind = (dhcp->offered_t0_lease * 7U) / 8U;
644   }
645 
646   /* (y)our internet address */
647   ip4_addr_copy(dhcp->offered_ip_addr, msg_in->yiaddr);
648 
649 #if LWIP_DHCP_BOOTP_FILE
650   /* copy boot server address,
651      boot file name copied in dhcp_parse_reply if not overloaded */
652   ip4_addr_copy(dhcp->offered_si_addr, msg_in->siaddr);
653 #endif /* LWIP_DHCP_BOOTP_FILE */
654 
655   /* subnet mask given? */
656   if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_SUBNET_MASK)) {
657     /* remember given subnet mask */
658     ip4_addr_set_u32(&dhcp->offered_sn_mask, lwip_htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_SUBNET_MASK)));
659     dhcp->subnet_mask_given = 1;
660   } else {
661     dhcp->subnet_mask_given = 0;
662   }
663 
664   /* gateway router */
665   if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_ROUTER)) {
666     ip4_addr_set_u32(&dhcp->offered_gw_addr, lwip_htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_ROUTER)));
667   }
668 
669 #if LWIP_DHCP_GET_NTP_SRV
670   /* NTP servers */
671   for (n = 0; (n < LWIP_DHCP_MAX_NTP_SERVERS) && dhcp_option_given(dhcp, DHCP_OPTION_IDX_NTP_SERVER + n); n++) {
672     ip4_addr_set_u32(&ntp_server_addrs[n], lwip_htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_NTP_SERVER + n)));
673   }
674   dhcp_set_ntp_servers(n, ntp_server_addrs);
675 #endif /* LWIP_DHCP_GET_NTP_SRV */
676 
677 #if LWIP_DHCP_PROVIDE_DNS_SERVERS
678   /* DNS servers */
679   for (n = 0; (n < LWIP_DHCP_PROVIDE_DNS_SERVERS) && dhcp_option_given(dhcp, DHCP_OPTION_IDX_DNS_SERVER + n); n++) {
680     ip_addr_t dns_addr;
681     ip_addr_set_ip4_u32_val(dns_addr, lwip_htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_DNS_SERVER + n)));
682     dns_setserver(n, &dns_addr);
683   }
684 #endif /* LWIP_DHCP_PROVIDE_DNS_SERVERS */
685 }
686 
687 /**
688  * @ingroup dhcp4
689  * Set a statically allocated struct dhcp to work with.
690  * Using this prevents dhcp_start to allocate it using mem_malloc.
691  *
692  * @param netif the netif for which to set the struct dhcp
693  * @param dhcp (uninitialised) dhcp struct allocated by the application
694  */
695 void
dhcp_set_struct(struct netif * netif,struct dhcp * dhcp)696 dhcp_set_struct(struct netif *netif, struct dhcp *dhcp)
697 {
698   LWIP_ASSERT_CORE_LOCKED();
699   LWIP_ASSERT("netif != NULL", netif != NULL);
700   LWIP_ASSERT("dhcp != NULL", dhcp != NULL);
701   LWIP_ASSERT("netif already has a struct dhcp set", netif_dhcp_data(netif) == NULL);
702 
703   /* clear data structure */
704   memset(dhcp, 0, sizeof(struct dhcp));
705   /* dhcp_set_state(&dhcp, DHCP_STATE_OFF); */
706   netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP, dhcp);
707 }
708 
709 /**
710  * @ingroup dhcp4
711  * Removes a struct dhcp from a netif.
712  *
713  * ATTENTION: Only use this when not using dhcp_set_struct() to allocate the
714  *            struct dhcp since the memory is passed back to the heap.
715  *
716  * @param netif the netif from which to remove the struct dhcp
717  */
dhcp_cleanup(struct netif * netif)718 void dhcp_cleanup(struct netif *netif)
719 {
720   LWIP_ASSERT_CORE_LOCKED();
721   LWIP_ASSERT("netif != NULL", netif != NULL);
722 
723   if (netif_dhcp_data(netif) != NULL) {
724     mem_free(netif_dhcp_data(netif));
725     netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP, NULL);
726   }
727 }
728 
729 /**
730  * @ingroup dhcp4
731  * Start DHCP negotiation for a network interface.
732  *
733  * If no DHCP client instance was attached to this interface,
734  * a new client is created first. If a DHCP client instance
735  * was already present, it restarts negotiation.
736  *
737  * @param netif The lwIP network interface
738  * @return lwIP error code
739  * - ERR_OK - No error
740  * - ERR_MEM - Out of memory
741  */
742 err_t
dhcp_start(struct netif * netif)743 dhcp_start(struct netif *netif)
744 {
745   struct dhcp *dhcp;
746   err_t result;
747 
748   LWIP_ASSERT_CORE_LOCKED();
749   LWIP_ERROR("netif != NULL", (netif != NULL), return ERR_ARG;);
750   LWIP_ERROR("netif is not up, old style port?", netif_is_up(netif), return ERR_ARG;);
751   dhcp = netif_dhcp_data(netif);
752   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_start(netif=%p) %c%c%"U16_F"\n", (void *)netif, netif->name[0], netif->name[1], (u16_t)netif->num));
753 
754   /* check MTU of the netif */
755   if (netif->mtu < DHCP_MAX_MSG_LEN_MIN_REQUIRED) {
756     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): Cannot use this netif with DHCP: MTU is too small\n"));
757     return ERR_MEM;
758   }
759 
760   /* no DHCP client attached yet? */
761   if (dhcp == NULL) {
762     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): mallocing new DHCP client\n"));
763     dhcp = (struct dhcp *)mem_malloc(sizeof(struct dhcp));
764     if (dhcp == NULL) {
765       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): could not allocate dhcp\n"));
766       return ERR_MEM;
767     }
768 
769     /* store this dhcp client in the netif */
770     netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP, dhcp);
771     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): allocated dhcp"));
772     /* already has DHCP client attached */
773   } else {
774     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_start(): restarting DHCP configuration\n"));
775 
776     if (dhcp->pcb_allocated != 0) {
777       dhcp_dec_pcb_refcount(); /* free DHCP PCB if not needed any more */
778     }
779     /* dhcp is cleared below, no need to reset flag*/
780   }
781 
782   /* clear data structure */
783   memset(dhcp, 0, sizeof(struct dhcp));
784   /* dhcp_set_state(&dhcp, DHCP_STATE_OFF); */
785 
786   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): starting DHCP configuration\n"));
787 
788   if (dhcp_inc_pcb_refcount() != ERR_OK) { /* ensure DHCP PCB is allocated */
789     return ERR_MEM;
790   }
791   dhcp->pcb_allocated = 1;
792 
793   if (!netif_is_link_up(netif)) {
794     /* set state INIT and wait for dhcp_network_changed() to call dhcp_discover() */
795     dhcp_set_state(dhcp, DHCP_STATE_INIT);
796     return ERR_OK;
797   }
798 
799   /* (re)start the DHCP negotiation */
800   result = dhcp_discover(netif);
801   if (result != ERR_OK) {
802     /* free resources allocated above */
803     dhcp_release_and_stop(netif);
804     return ERR_MEM;
805   }
806   return result;
807 }
808 
809 /**
810  * @ingroup dhcp4
811  * Inform a DHCP server of our manual configuration.
812  *
813  * This informs DHCP servers of our fixed IP address configuration
814  * by sending an INFORM message. It does not involve DHCP address
815  * configuration, it is just here to be nice to the network.
816  *
817  * @param netif The lwIP network interface
818  */
819 void
dhcp_inform(struct netif * netif)820 dhcp_inform(struct netif *netif)
821 {
822   struct dhcp dhcp;
823   struct pbuf *p_out;
824   u16_t options_out_len;
825 
826   LWIP_ASSERT_CORE_LOCKED();
827   LWIP_ERROR("netif != NULL", (netif != NULL), return;);
828 
829   if (dhcp_inc_pcb_refcount() != ERR_OK) { /* ensure DHCP PCB is allocated */
830     return;
831   }
832 
833   memset(&dhcp, 0, sizeof(struct dhcp));
834   dhcp_set_state(&dhcp, DHCP_STATE_INFORMING);
835 
836   /* create and initialize the DHCP message header */
837   p_out = dhcp_create_msg(netif, &dhcp, DHCP_INFORM, &options_out_len);
838   if (p_out != NULL) {
839     struct dhcp_msg *msg_out = (struct dhcp_msg *)p_out->payload;
840     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN);
841     options_out_len = dhcp_option_short(options_out_len, msg_out->options, DHCP_MAX_MSG_LEN(netif));
842 
843     LWIP_HOOK_DHCP_APPEND_OPTIONS(netif, &dhcp, DHCP_STATE_INFORMING, msg_out, DHCP_INFORM, &options_out_len);
844     dhcp_option_trailer(options_out_len, msg_out->options, p_out);
845 
846     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_inform: INFORMING\n"));
847 
848     udp_sendto_if(dhcp_pcb, p_out, IP_ADDR_BROADCAST, LWIP_IANA_PORT_DHCP_SERVER, netif);
849 
850     pbuf_free(p_out);
851   } else {
852     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_inform: could not allocate DHCP request\n"));
853   }
854 
855   dhcp_dec_pcb_refcount(); /* delete DHCP PCB if not needed any more */
856 }
857 
858 /** Handle a possible change in the network configuration.
859  *
860  * This enters the REBOOTING state to verify that the currently bound
861  * address is still valid.
862  */
863 void
dhcp_network_changed(struct netif * netif)864 dhcp_network_changed(struct netif *netif)
865 {
866   struct dhcp *dhcp = netif_dhcp_data(netif);
867 
868   if (!dhcp) {
869     return;
870   }
871   switch (dhcp->state) {
872     case DHCP_STATE_REBINDING:
873     case DHCP_STATE_RENEWING:
874     case DHCP_STATE_BOUND:
875     case DHCP_STATE_REBOOTING:
876       dhcp->tries = 0;
877       dhcp_reboot(netif);
878       break;
879     case DHCP_STATE_OFF:
880       /* stay off */
881       break;
882     default:
883       LWIP_ASSERT("invalid dhcp->state", dhcp->state <= DHCP_STATE_BACKING_OFF);
884       /* INIT/REQUESTING/CHECKING/BACKING_OFF restart with new 'rid' because the
885          state changes, SELECTING: continue with current 'rid' as we stay in the
886          same state */
887 #if LWIP_DHCP_AUTOIP_COOP
888       if (dhcp->autoip_coop_state == DHCP_AUTOIP_COOP_STATE_ON) {
889         autoip_stop(netif);
890         dhcp->autoip_coop_state = DHCP_AUTOIP_COOP_STATE_OFF;
891       }
892 #endif /* LWIP_DHCP_AUTOIP_COOP */
893       /* ensure we start with short timeouts, even if already discovering */
894       dhcp->tries = 0;
895       dhcp_discover(netif);
896       break;
897   }
898 }
899 
900 #if DHCP_DOES_ARP_CHECK
901 /**
902  * Match an ARP reply with the offered IP address:
903  * check whether the offered IP address is not in use using ARP
904  *
905  * @param netif the network interface on which the reply was received
906  * @param addr The IP address we received a reply from
907  */
908 void
dhcp_arp_reply(struct netif * netif,const ip4_addr_t * addr)909 dhcp_arp_reply(struct netif *netif, const ip4_addr_t *addr)
910 {
911   struct dhcp *dhcp;
912 
913   LWIP_ERROR("netif != NULL", (netif != NULL), return;);
914   dhcp = netif_dhcp_data(netif);
915   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_arp_reply()\n"));
916   /* is a DHCP client doing an ARP check? */
917   if ((dhcp != NULL) && (dhcp->state == DHCP_STATE_CHECKING)) {
918     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_arp_reply(): CHECKING, arp reply for 0x%08"X32_F"\n",
919                 ip4_addr_get_u32(addr)));
920     /* did a host respond with the address we
921        were offered by the DHCP server? */
922     if (ip4_addr_cmp(addr, &dhcp->offered_ip_addr)) {
923       /* we will not accept the offered address */
924       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE | LWIP_DBG_LEVEL_WARNING,
925                   ("dhcp_arp_reply(): arp reply matched with offered address, declining\n"));
926       dhcp_decline(netif);
927     }
928   }
929 }
930 
931 /**
932  * Decline an offered lease.
933  *
934  * Tell the DHCP server we do not accept the offered address.
935  * One reason to decline the lease is when we find out the address
936  * is already in use by another host (through ARP).
937  *
938  * @param netif the netif under DHCP control
939  */
940 static err_t
dhcp_decline(struct netif * netif)941 dhcp_decline(struct netif *netif)
942 {
943   struct dhcp *dhcp = netif_dhcp_data(netif);
944   err_t result;
945   u16_t msecs;
946   struct pbuf *p_out;
947   u16_t options_out_len;
948 
949   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_decline()\n"));
950   dhcp_set_state(dhcp, DHCP_STATE_BACKING_OFF);
951   /* create and initialize the DHCP message header */
952   p_out = dhcp_create_msg(netif, dhcp, DHCP_DECLINE, &options_out_len);
953   if (p_out != NULL) {
954     struct dhcp_msg *msg_out = (struct dhcp_msg *)p_out->payload;
955     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_REQUESTED_IP, 4);
956     options_out_len = dhcp_option_long(options_out_len, msg_out->options, lwip_ntohl(ip4_addr_get_u32(&dhcp->offered_ip_addr)));
957 
958     LWIP_HOOK_DHCP_APPEND_OPTIONS(netif, dhcp, DHCP_STATE_BACKING_OFF, msg_out, DHCP_DECLINE, &options_out_len);
959     dhcp_option_trailer(options_out_len, msg_out->options, p_out);
960 
961     /* per section 4.4.4, broadcast DECLINE messages */
962     result = udp_sendto_if_src(dhcp_pcb, p_out, IP_ADDR_BROADCAST, LWIP_IANA_PORT_DHCP_SERVER, netif, IP4_ADDR_ANY);
963     pbuf_free(p_out);
964     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_decline: BACKING OFF\n"));
965   } else {
966     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS,
967                 ("dhcp_decline: could not allocate DHCP request\n"));
968     result = ERR_MEM;
969   }
970   if (dhcp->tries < 255) {
971     dhcp->tries++;
972   }
973   msecs = 10 * 1000;
974   dhcp->request_timeout = (u16_t)((msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS);
975   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_decline(): set request timeout %"U16_F" msecs\n", msecs));
976   return result;
977 }
978 #endif /* DHCP_DOES_ARP_CHECK */
979 
980 
981 /**
982  * Start the DHCP process, discover a DHCP server.
983  *
984  * @param netif the netif under DHCP control
985  */
986 static err_t
dhcp_discover(struct netif * netif)987 dhcp_discover(struct netif *netif)
988 {
989   struct dhcp *dhcp = netif_dhcp_data(netif);
990   err_t result = ERR_OK;
991   u16_t msecs;
992   u8_t i;
993   struct pbuf *p_out;
994   u16_t options_out_len;
995 
996   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_discover()\n"));
997 
998   ip4_addr_set_any(&dhcp->offered_ip_addr);
999   dhcp_set_state(dhcp, DHCP_STATE_SELECTING);
1000   /* create and initialize the DHCP message header */
1001   p_out = dhcp_create_msg(netif, dhcp, DHCP_DISCOVER, &options_out_len);
1002   if (p_out != NULL) {
1003     struct dhcp_msg *msg_out = (struct dhcp_msg *)p_out->payload;
1004     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_discover: making request\n"));
1005 
1006     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN);
1007     options_out_len = dhcp_option_short(options_out_len, msg_out->options, DHCP_MAX_MSG_LEN(netif));
1008 
1009     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_PARAMETER_REQUEST_LIST, LWIP_ARRAYSIZE(dhcp_discover_request_options));
1010     for (i = 0; i < LWIP_ARRAYSIZE(dhcp_discover_request_options); i++) {
1011       options_out_len = dhcp_option_byte(options_out_len, msg_out->options, dhcp_discover_request_options[i]);
1012     }
1013     LWIP_HOOK_DHCP_APPEND_OPTIONS(netif, dhcp, DHCP_STATE_SELECTING, msg_out, DHCP_DISCOVER, &options_out_len);
1014     dhcp_option_trailer(options_out_len, msg_out->options, p_out);
1015 
1016     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_discover: sendto(DISCOVER, IP_ADDR_BROADCAST, LWIP_IANA_PORT_DHCP_SERVER)\n"));
1017     udp_sendto_if_src(dhcp_pcb, p_out, IP_ADDR_BROADCAST, LWIP_IANA_PORT_DHCP_SERVER, netif, IP4_ADDR_ANY);
1018     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_discover: deleting()ing\n"));
1019     pbuf_free(p_out);
1020     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_discover: SELECTING\n"));
1021   } else {
1022     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_discover: could not allocate DHCP request\n"));
1023   }
1024   if (dhcp->tries < 255) {
1025     dhcp->tries++;
1026   }
1027 #if LWIP_DHCP_AUTOIP_COOP
1028   if (dhcp->tries >= LWIP_DHCP_AUTOIP_COOP_TRIES && dhcp->autoip_coop_state == DHCP_AUTOIP_COOP_STATE_OFF) {
1029     dhcp->autoip_coop_state = DHCP_AUTOIP_COOP_STATE_ON;
1030     autoip_start(netif);
1031   }
1032 #endif /* LWIP_DHCP_AUTOIP_COOP */
1033   msecs = (u16_t)((dhcp->tries < 6 ? 1 << dhcp->tries : 60) * 1000);
1034   dhcp->request_timeout = (u16_t)((msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS);
1035   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_discover(): set request timeout %"U16_F" msecs\n", msecs));
1036   return result;
1037 }
1038 
1039 
1040 /**
1041  * Bind the interface to the offered IP address.
1042  *
1043  * @param netif network interface to bind to the offered address
1044  */
1045 static void
dhcp_bind(struct netif * netif)1046 dhcp_bind(struct netif *netif)
1047 {
1048   u32_t timeout;
1049   struct dhcp *dhcp;
1050   ip4_addr_t sn_mask, gw_addr;
1051   LWIP_ERROR("dhcp_bind: netif != NULL", (netif != NULL), return;);
1052   dhcp = netif_dhcp_data(netif);
1053   LWIP_ERROR("dhcp_bind: dhcp != NULL", (dhcp != NULL), return;);
1054   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_bind(netif=%p) %c%c%"U16_F"\n", (void *)netif, netif->name[0], netif->name[1], (u16_t)netif->num));
1055 
1056   /* reset time used of lease */
1057   dhcp->lease_used = 0;
1058 
1059   if (dhcp->offered_t0_lease != 0xffffffffUL) {
1060     /* set renewal period timer */
1061     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_bind(): t0 renewal timer %"U32_F" secs\n", dhcp->offered_t0_lease));
1062     timeout = (dhcp->offered_t0_lease + DHCP_COARSE_TIMER_SECS / 2) / DHCP_COARSE_TIMER_SECS;
1063     if (timeout > 0xffff) {
1064       timeout = 0xffff;
1065     }
1066     dhcp->t0_timeout = (u16_t)timeout;
1067     if (dhcp->t0_timeout == 0) {
1068       dhcp->t0_timeout = 1;
1069     }
1070     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_bind(): set request timeout %"U32_F" msecs\n", dhcp->offered_t0_lease * 1000));
1071   }
1072 
1073   /* temporary DHCP lease? */
1074   if (dhcp->offered_t1_renew != 0xffffffffUL) {
1075     /* set renewal period timer */
1076     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_bind(): t1 renewal timer %"U32_F" secs\n", dhcp->offered_t1_renew));
1077     timeout = (dhcp->offered_t1_renew + DHCP_COARSE_TIMER_SECS / 2) / DHCP_COARSE_TIMER_SECS;
1078     if (timeout > 0xffff) {
1079       timeout = 0xffff;
1080     }
1081     dhcp->t1_timeout = (u16_t)timeout;
1082     if (dhcp->t1_timeout == 0) {
1083       dhcp->t1_timeout = 1;
1084     }
1085     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_bind(): set request timeout %"U32_F" msecs\n", dhcp->offered_t1_renew * 1000));
1086     dhcp->t1_renew_time = dhcp->t1_timeout;
1087   }
1088   /* set renewal period timer */
1089   if (dhcp->offered_t2_rebind != 0xffffffffUL) {
1090     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_bind(): t2 rebind timer %"U32_F" secs\n", dhcp->offered_t2_rebind));
1091     timeout = (dhcp->offered_t2_rebind + DHCP_COARSE_TIMER_SECS / 2) / DHCP_COARSE_TIMER_SECS;
1092     if (timeout > 0xffff) {
1093       timeout = 0xffff;
1094     }
1095     dhcp->t2_timeout = (u16_t)timeout;
1096     if (dhcp->t2_timeout == 0) {
1097       dhcp->t2_timeout = 1;
1098     }
1099     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_bind(): set request timeout %"U32_F" msecs\n", dhcp->offered_t2_rebind * 1000));
1100     dhcp->t2_rebind_time = dhcp->t2_timeout;
1101   }
1102 
1103   /* If we have sub 1 minute lease, t2 and t1 will kick in at the same time. */
1104   if ((dhcp->t1_timeout >= dhcp->t2_timeout) && (dhcp->t2_timeout > 0)) {
1105     dhcp->t1_timeout = 0;
1106   }
1107 
1108   if (dhcp->subnet_mask_given) {
1109     /* copy offered network mask */
1110     ip4_addr_copy(sn_mask, dhcp->offered_sn_mask);
1111   } else {
1112     /* subnet mask not given, choose a safe subnet mask given the network class */
1113     u8_t first_octet = ip4_addr1(&dhcp->offered_ip_addr);
1114     if (first_octet <= 127) {
1115       ip4_addr_set_u32(&sn_mask, PP_HTONL(0xff000000UL));
1116     } else if (first_octet >= 192) {
1117       ip4_addr_set_u32(&sn_mask, PP_HTONL(0xffffff00UL));
1118     } else {
1119       ip4_addr_set_u32(&sn_mask, PP_HTONL(0xffff0000UL));
1120     }
1121   }
1122 
1123   ip4_addr_copy(gw_addr, dhcp->offered_gw_addr);
1124 
1125 #if LWIP_DHCP_AUTOIP_COOP
1126   if (dhcp->autoip_coop_state == DHCP_AUTOIP_COOP_STATE_ON) {
1127     autoip_stop(netif);
1128     dhcp->autoip_coop_state = DHCP_AUTOIP_COOP_STATE_OFF;
1129   }
1130 #endif /* LWIP_DHCP_AUTOIP_COOP */
1131 
1132   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_STATE, ("dhcp_bind(): IP: 0x%08"X32_F" SN: 0x%08"X32_F" GW: 0x%08"X32_F"\n",
1133               ip4_addr_get_u32(&dhcp->offered_ip_addr), ip4_addr_get_u32(&sn_mask), ip4_addr_get_u32(&gw_addr)));
1134   /* netif is now bound to DHCP leased address - set this before assigning the address
1135      to ensure the callback can use dhcp_supplied_address() */
1136   dhcp_set_state(dhcp, DHCP_STATE_BOUND);
1137 
1138   netif_set_addr(netif, &dhcp->offered_ip_addr, &sn_mask, &gw_addr);
1139   /* interface is used by routing now that an address is set */
1140 }
1141 
1142 /**
1143  * @ingroup dhcp4
1144  * Renew an existing DHCP lease at the involved DHCP server.
1145  *
1146  * @param netif network interface which must renew its lease
1147  */
1148 err_t
dhcp_renew(struct netif * netif)1149 dhcp_renew(struct netif *netif)
1150 {
1151   struct dhcp *dhcp = netif_dhcp_data(netif);
1152   err_t result;
1153   u16_t msecs;
1154   u8_t i;
1155   struct pbuf *p_out;
1156   u16_t options_out_len;
1157 
1158   LWIP_ASSERT_CORE_LOCKED();
1159   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_renew()\n"));
1160   dhcp_set_state(dhcp, DHCP_STATE_RENEWING);
1161 
1162   /* create and initialize the DHCP message header */
1163   p_out = dhcp_create_msg(netif, dhcp, DHCP_REQUEST, &options_out_len);
1164   if (p_out != NULL) {
1165     struct dhcp_msg *msg_out = (struct dhcp_msg *)p_out->payload;
1166     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN);
1167     options_out_len = dhcp_option_short(options_out_len, msg_out->options, DHCP_MAX_MSG_LEN(netif));
1168 
1169     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_PARAMETER_REQUEST_LIST, LWIP_ARRAYSIZE(dhcp_discover_request_options));
1170     for (i = 0; i < LWIP_ARRAYSIZE(dhcp_discover_request_options); i++) {
1171       options_out_len = dhcp_option_byte(options_out_len, msg_out->options, dhcp_discover_request_options[i]);
1172     }
1173 
1174 #if LWIP_NETIF_HOSTNAME
1175     options_out_len = dhcp_option_hostname(options_out_len, msg_out->options, netif);
1176 #endif /* LWIP_NETIF_HOSTNAME */
1177 
1178     LWIP_HOOK_DHCP_APPEND_OPTIONS(netif, dhcp, DHCP_STATE_RENEWING, msg_out, DHCP_REQUEST, &options_out_len);
1179     dhcp_option_trailer(options_out_len, msg_out->options, p_out);
1180 
1181     result = udp_sendto_if(dhcp_pcb, p_out, &dhcp->server_ip_addr, LWIP_IANA_PORT_DHCP_SERVER, netif);
1182     pbuf_free(p_out);
1183 
1184     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_renew: RENEWING\n"));
1185   } else {
1186     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_renew: could not allocate DHCP request\n"));
1187     result = ERR_MEM;
1188   }
1189   if (dhcp->tries < 255) {
1190     dhcp->tries++;
1191   }
1192   /* back-off on retries, but to a maximum of 20 seconds */
1193   msecs = (u16_t)(dhcp->tries < 10 ? dhcp->tries * 2000 : 20 * 1000);
1194   dhcp->request_timeout = (u16_t)((msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS);
1195   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_renew(): set request timeout %"U16_F" msecs\n", msecs));
1196   return result;
1197 }
1198 
1199 /**
1200  * Rebind with a DHCP server for an existing DHCP lease.
1201  *
1202  * @param netif network interface which must rebind with a DHCP server
1203  */
1204 static err_t
dhcp_rebind(struct netif * netif)1205 dhcp_rebind(struct netif *netif)
1206 {
1207   struct dhcp *dhcp = netif_dhcp_data(netif);
1208   err_t result;
1209   u16_t msecs;
1210   u8_t i;
1211   struct pbuf *p_out;
1212   u16_t options_out_len;
1213 
1214   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_rebind()\n"));
1215   dhcp_set_state(dhcp, DHCP_STATE_REBINDING);
1216 
1217   /* create and initialize the DHCP message header */
1218   p_out = dhcp_create_msg(netif, dhcp, DHCP_REQUEST, &options_out_len);
1219   if (p_out != NULL) {
1220     struct dhcp_msg *msg_out = (struct dhcp_msg *)p_out->payload;
1221     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN);
1222     options_out_len = dhcp_option_short(options_out_len, msg_out->options, DHCP_MAX_MSG_LEN(netif));
1223 
1224     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_PARAMETER_REQUEST_LIST, LWIP_ARRAYSIZE(dhcp_discover_request_options));
1225     for (i = 0; i < LWIP_ARRAYSIZE(dhcp_discover_request_options); i++) {
1226       options_out_len = dhcp_option_byte(options_out_len, msg_out->options, dhcp_discover_request_options[i]);
1227     }
1228 
1229 #if LWIP_NETIF_HOSTNAME
1230     options_out_len = dhcp_option_hostname(options_out_len, msg_out->options, netif);
1231 #endif /* LWIP_NETIF_HOSTNAME */
1232 
1233     LWIP_HOOK_DHCP_APPEND_OPTIONS(netif, dhcp, DHCP_STATE_REBINDING, msg_out, DHCP_DISCOVER, &options_out_len);
1234     dhcp_option_trailer(options_out_len, msg_out->options, p_out);
1235 
1236     /* broadcast to server */
1237     result = udp_sendto_if(dhcp_pcb, p_out, IP_ADDR_BROADCAST, LWIP_IANA_PORT_DHCP_SERVER, netif);
1238     pbuf_free(p_out);
1239     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_rebind: REBINDING\n"));
1240   } else {
1241     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_rebind: could not allocate DHCP request\n"));
1242     result = ERR_MEM;
1243   }
1244   if (dhcp->tries < 255) {
1245     dhcp->tries++;
1246   }
1247   msecs = (u16_t)(dhcp->tries < 10 ? dhcp->tries * 1000 : 10 * 1000);
1248   dhcp->request_timeout = (u16_t)((msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS);
1249   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_rebind(): set request timeout %"U16_F" msecs\n", msecs));
1250   return result;
1251 }
1252 
1253 /**
1254  * Enter REBOOTING state to verify an existing lease
1255  *
1256  * @param netif network interface which must reboot
1257  */
1258 static err_t
dhcp_reboot(struct netif * netif)1259 dhcp_reboot(struct netif *netif)
1260 {
1261   struct dhcp *dhcp = netif_dhcp_data(netif);
1262   err_t result;
1263   u16_t msecs;
1264   u8_t i;
1265   struct pbuf *p_out;
1266   u16_t options_out_len;
1267 
1268   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_reboot()\n"));
1269   dhcp_set_state(dhcp, DHCP_STATE_REBOOTING);
1270 
1271   /* create and initialize the DHCP message header */
1272   p_out = dhcp_create_msg(netif, dhcp, DHCP_REQUEST, &options_out_len);
1273   if (p_out != NULL) {
1274     struct dhcp_msg *msg_out = (struct dhcp_msg *)p_out->payload;
1275     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN);
1276     options_out_len = dhcp_option_short(options_out_len, msg_out->options, DHCP_MAX_MSG_LEN_MIN_REQUIRED);
1277 
1278     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_REQUESTED_IP, 4);
1279     options_out_len = dhcp_option_long(options_out_len, msg_out->options, lwip_ntohl(ip4_addr_get_u32(&dhcp->offered_ip_addr)));
1280 
1281     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_PARAMETER_REQUEST_LIST, LWIP_ARRAYSIZE(dhcp_discover_request_options));
1282     for (i = 0; i < LWIP_ARRAYSIZE(dhcp_discover_request_options); i++) {
1283       options_out_len = dhcp_option_byte(options_out_len, msg_out->options, dhcp_discover_request_options[i]);
1284     }
1285 
1286 #if LWIP_NETIF_HOSTNAME
1287     options_out_len = dhcp_option_hostname(options_out_len, msg_out->options, netif);
1288 #endif /* LWIP_NETIF_HOSTNAME */
1289 
1290     LWIP_HOOK_DHCP_APPEND_OPTIONS(netif, dhcp, DHCP_STATE_REBOOTING, msg_out, DHCP_REQUEST, &options_out_len);
1291     dhcp_option_trailer(options_out_len, msg_out->options, p_out);
1292 
1293     /* broadcast to server */
1294     result = udp_sendto_if(dhcp_pcb, p_out, IP_ADDR_BROADCAST, LWIP_IANA_PORT_DHCP_SERVER, netif);
1295     pbuf_free(p_out);
1296     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_reboot: REBOOTING\n"));
1297   } else {
1298     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_reboot: could not allocate DHCP request\n"));
1299     result = ERR_MEM;
1300   }
1301   if (dhcp->tries < 255) {
1302     dhcp->tries++;
1303   }
1304   msecs = (u16_t)(dhcp->tries < 10 ? dhcp->tries * 1000 : 10 * 1000);
1305   dhcp->request_timeout = (u16_t)((msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS);
1306   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_reboot(): set request timeout %"U16_F" msecs\n", msecs));
1307   return result;
1308 }
1309 
1310 /**
1311  * @ingroup dhcp4
1312  * Release a DHCP lease and stop DHCP statemachine (and AUTOIP if LWIP_DHCP_AUTOIP_COOP).
1313  *
1314  * @param netif network interface
1315  */
1316 void
dhcp_release_and_stop(struct netif * netif)1317 dhcp_release_and_stop(struct netif *netif)
1318 {
1319   struct dhcp *dhcp = netif_dhcp_data(netif);
1320   ip_addr_t server_ip_addr;
1321 
1322   LWIP_ASSERT_CORE_LOCKED();
1323   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_release_and_stop()\n"));
1324   if (dhcp == NULL) {
1325     return;
1326   }
1327 
1328   /* already off? -> nothing to do */
1329   if (dhcp->state == DHCP_STATE_OFF) {
1330     return;
1331   }
1332 
1333   ip_addr_copy(server_ip_addr, dhcp->server_ip_addr);
1334 
1335   /* clean old DHCP offer */
1336   ip_addr_set_zero_ip4(&dhcp->server_ip_addr);
1337   ip4_addr_set_zero(&dhcp->offered_ip_addr);
1338   ip4_addr_set_zero(&dhcp->offered_sn_mask);
1339   ip4_addr_set_zero(&dhcp->offered_gw_addr);
1340 #if LWIP_DHCP_BOOTP_FILE
1341   ip4_addr_set_zero(&dhcp->offered_si_addr);
1342 #endif /* LWIP_DHCP_BOOTP_FILE */
1343   dhcp->offered_t0_lease = dhcp->offered_t1_renew = dhcp->offered_t2_rebind = 0;
1344   dhcp->t1_renew_time = dhcp->t2_rebind_time = dhcp->lease_used = dhcp->t0_timeout = 0;
1345 
1346   /* send release message when current IP was assigned via DHCP */
1347   if (dhcp_supplied_address(netif)) {
1348     /* create and initialize the DHCP message header */
1349     struct pbuf *p_out;
1350     u16_t options_out_len;
1351     dhcp_set_state(dhcp, DHCP_STATE_OFF);
1352     p_out = dhcp_create_msg(netif, dhcp, DHCP_RELEASE, &options_out_len);
1353     if (p_out != NULL) {
1354       struct dhcp_msg *msg_out = (struct dhcp_msg *)p_out->payload;
1355       options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_SERVER_ID, 4);
1356       options_out_len = dhcp_option_long(options_out_len, msg_out->options, lwip_ntohl(ip4_addr_get_u32(ip_2_ip4(&server_ip_addr))));
1357 
1358       LWIP_HOOK_DHCP_APPEND_OPTIONS(netif, dhcp, dhcp->state, msg_out, DHCP_RELEASE, &options_out_len);
1359       dhcp_option_trailer(options_out_len, msg_out->options, p_out);
1360 
1361       udp_sendto_if(dhcp_pcb, p_out, &server_ip_addr, LWIP_IANA_PORT_DHCP_SERVER, netif);
1362       pbuf_free(p_out);
1363       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_release: RELEASED, DHCP_STATE_OFF\n"));
1364     } else {
1365       /* sending release failed, but that's not a problem since the correct behaviour of dhcp does not rely on release */
1366       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_release: could not allocate DHCP request\n"));
1367     }
1368 
1369     /* remove IP address from interface (prevents routing from selecting this interface) */
1370     netif_set_addr(netif, IP4_ADDR_ANY4, IP4_ADDR_ANY4, IP4_ADDR_ANY4);
1371   } else {
1372      dhcp_set_state(dhcp, DHCP_STATE_OFF);
1373   }
1374 
1375 #if LWIP_DHCP_AUTOIP_COOP
1376   if (dhcp->autoip_coop_state == DHCP_AUTOIP_COOP_STATE_ON) {
1377     autoip_stop(netif);
1378     dhcp->autoip_coop_state = DHCP_AUTOIP_COOP_STATE_OFF;
1379   }
1380 #endif /* LWIP_DHCP_AUTOIP_COOP */
1381 
1382   if (dhcp->pcb_allocated != 0) {
1383     dhcp_dec_pcb_refcount(); /* free DHCP PCB if not needed any more */
1384     dhcp->pcb_allocated = 0;
1385   }
1386 }
1387 
1388 /**
1389  * @ingroup dhcp4
1390  * This function calls dhcp_release_and_stop() internally.
1391  * @deprecated Use dhcp_release_and_stop() instead.
1392  */
1393 err_t
dhcp_release(struct netif * netif)1394 dhcp_release(struct netif *netif)
1395 {
1396   dhcp_release_and_stop(netif);
1397   return ERR_OK;
1398 }
1399 
1400 /**
1401  * @ingroup dhcp4
1402  * This function calls dhcp_release_and_stop() internally.
1403  * @deprecated Use dhcp_release_and_stop() instead.
1404  */
1405 void
dhcp_stop(struct netif * netif)1406 dhcp_stop(struct netif *netif)
1407 {
1408   dhcp_release_and_stop(netif);
1409 }
1410 
1411 /*
1412  * Set the DHCP state of a DHCP client.
1413  *
1414  * If the state changed, reset the number of tries.
1415  */
1416 static void
dhcp_set_state(struct dhcp * dhcp,u8_t new_state)1417 dhcp_set_state(struct dhcp *dhcp, u8_t new_state)
1418 {
1419   if (new_state != dhcp->state) {
1420     dhcp->state = new_state;
1421     dhcp->tries = 0;
1422     dhcp->request_timeout = 0;
1423   }
1424 }
1425 
1426 /*
1427  * Concatenate an option type and length field to the outgoing
1428  * DHCP message.
1429  *
1430  */
1431 static u16_t
dhcp_option(u16_t options_out_len,u8_t * options,u8_t option_type,u8_t option_len)1432 dhcp_option(u16_t options_out_len, u8_t *options, u8_t option_type, u8_t option_len)
1433 {
1434   LWIP_ASSERT("dhcp_option: options_out_len + 2 + option_len <= DHCP_OPTIONS_LEN", options_out_len + 2U + option_len <= DHCP_OPTIONS_LEN);
1435   options[options_out_len++] = option_type;
1436   options[options_out_len++] = option_len;
1437   return options_out_len;
1438 }
1439 /*
1440  * Concatenate a single byte to the outgoing DHCP message.
1441  *
1442  */
1443 static u16_t
dhcp_option_byte(u16_t options_out_len,u8_t * options,u8_t value)1444 dhcp_option_byte(u16_t options_out_len, u8_t *options, u8_t value)
1445 {
1446   LWIP_ASSERT("dhcp_option_byte: options_out_len < DHCP_OPTIONS_LEN", options_out_len < DHCP_OPTIONS_LEN);
1447   options[options_out_len++] = value;
1448   return options_out_len;
1449 }
1450 
1451 static u16_t
dhcp_option_short(u16_t options_out_len,u8_t * options,u16_t value)1452 dhcp_option_short(u16_t options_out_len, u8_t *options, u16_t value)
1453 {
1454   LWIP_ASSERT("dhcp_option_short: options_out_len + 2 <= DHCP_OPTIONS_LEN", options_out_len + 2U <= DHCP_OPTIONS_LEN);
1455   options[options_out_len++] = (u8_t)((value & 0xff00U) >> 8);
1456   options[options_out_len++] = (u8_t) (value & 0x00ffU);
1457   return options_out_len;
1458 }
1459 
1460 static u16_t
dhcp_option_long(u16_t options_out_len,u8_t * options,u32_t value)1461 dhcp_option_long(u16_t options_out_len, u8_t *options, u32_t value)
1462 {
1463   LWIP_ASSERT("dhcp_option_long: options_out_len + 4 <= DHCP_OPTIONS_LEN", options_out_len + 4U <= DHCP_OPTIONS_LEN);
1464   options[options_out_len++] = (u8_t)((value & 0xff000000UL) >> 24);
1465   options[options_out_len++] = (u8_t)((value & 0x00ff0000UL) >> 16);
1466   options[options_out_len++] = (u8_t)((value & 0x0000ff00UL) >> 8);
1467   options[options_out_len++] = (u8_t)((value & 0x000000ffUL));
1468   return options_out_len;
1469 }
1470 
1471 #if LWIP_NETIF_HOSTNAME
1472 static u16_t
dhcp_option_hostname(u16_t options_out_len,u8_t * options,struct netif * netif)1473 dhcp_option_hostname(u16_t options_out_len, u8_t *options, struct netif *netif)
1474 {
1475   if (netif->hostname != NULL) {
1476     size_t namelen = strlen(netif->hostname);
1477     if (namelen > 0) {
1478       size_t len;
1479       const char *p = netif->hostname;
1480       /* Shrink len to available bytes (need 2 bytes for OPTION_HOSTNAME
1481          and 1 byte for trailer) */
1482       size_t available = DHCP_OPTIONS_LEN - options_out_len - 3;
1483       LWIP_ASSERT("DHCP: hostname is too long!", namelen <= available);
1484       len = LWIP_MIN(namelen, available);
1485       LWIP_ASSERT("DHCP: hostname is too long!", len <= 0xFF);
1486       options_out_len = dhcp_option(options_out_len, options, DHCP_OPTION_HOSTNAME, (u8_t)len);
1487       while (len--) {
1488         options_out_len = dhcp_option_byte(options_out_len, options, *p++);
1489       }
1490     }
1491   }
1492   return options_out_len;
1493 }
1494 #endif /* LWIP_NETIF_HOSTNAME */
1495 
1496 /**
1497  * Extract the DHCP message and the DHCP options.
1498  *
1499  * Extract the DHCP message and the DHCP options, each into a contiguous
1500  * piece of memory. As a DHCP message is variable sized by its options,
1501  * and also allows overriding some fields for options, the easy approach
1502  * is to first unfold the options into a contiguous piece of memory, and
1503  * use that further on.
1504  *
1505  */
1506 static err_t
dhcp_parse_reply(struct pbuf * p,struct dhcp * dhcp)1507 dhcp_parse_reply(struct pbuf *p, struct dhcp *dhcp)
1508 {
1509   u8_t *options;
1510   u16_t offset;
1511   u16_t offset_max;
1512   u16_t options_offset;
1513   u16_t options_idx;
1514   u16_t options_idx_max;
1515   struct pbuf *q;
1516   int parse_file_as_options = 0;
1517   int parse_sname_as_options = 0;
1518   struct dhcp_msg *msg_in;
1519 #if LWIP_DHCP_BOOTP_FILE
1520   int file_overloaded = 0;
1521 #endif
1522 
1523   LWIP_UNUSED_ARG(dhcp);
1524 
1525   /* clear received options */
1526   dhcp_clear_all_options(dhcp);
1527   /* check that beginning of dhcp_msg (up to and including chaddr) is in first pbuf */
1528   if (p->len < DHCP_SNAME_OFS) {
1529     return ERR_BUF;
1530   }
1531   msg_in = (struct dhcp_msg *)p->payload;
1532 #if LWIP_DHCP_BOOTP_FILE
1533   /* clear boot file name */
1534   dhcp->boot_file_name[0] = 0;
1535 #endif /* LWIP_DHCP_BOOTP_FILE */
1536 
1537   /* parse options */
1538 
1539   /* start with options field */
1540   options_idx = DHCP_OPTIONS_OFS;
1541   /* parse options to the end of the received packet */
1542   options_idx_max = p->tot_len;
1543 again:
1544   q = p;
1545   options_offset = options_idx;
1546   while ((q != NULL) && (options_idx >= q->len)) {
1547     options_idx = (u16_t)(options_idx - q->len);
1548     options_idx_max = (u16_t)(options_idx_max - q->len);
1549     q = q->next;
1550   }
1551   if (q == NULL) {
1552     return ERR_BUF;
1553   }
1554   offset = options_idx;
1555   offset_max = options_idx_max;
1556   options = (u8_t *)q->payload;
1557   /* at least 1 byte to read and no end marker, then at least 3 bytes to read? */
1558   while ((q != NULL) && (offset < offset_max) && (options[offset] != DHCP_OPTION_END)) {
1559     u8_t op = options[offset];
1560     u8_t len;
1561     u8_t decode_len = 0;
1562     int decode_idx = -1;
1563     u16_t val_offset = (u16_t)(offset + 2);
1564     if (val_offset < offset) {
1565       /* overflow */
1566       return ERR_BUF;
1567     }
1568     /* len byte might be in the next pbuf */
1569     if ((offset + 1) < q->len) {
1570       len = options[offset + 1];
1571     } else {
1572       len = (q->next != NULL ? ((u8_t *)q->next->payload)[0] : 0);
1573     }
1574     /* LWIP_DEBUGF(DHCP_DEBUG, ("msg_offset=%"U16_F", q->len=%"U16_F, msg_offset, q->len)); */
1575     decode_len = len;
1576     switch (op) {
1577       /* case(DHCP_OPTION_END): handled above */
1578       case (DHCP_OPTION_PAD):
1579         /* special option: no len encoded */
1580         decode_len = len = 0;
1581         /* will be increased below */
1582         break;
1583       case (DHCP_OPTION_SUBNET_MASK):
1584         LWIP_DHCP_INPUT_ERROR("len == 4", len == 4, return ERR_VAL;);
1585         decode_idx = DHCP_OPTION_IDX_SUBNET_MASK;
1586         break;
1587       case (DHCP_OPTION_ROUTER):
1588         decode_len = 4; /* only copy the first given router */
1589         LWIP_DHCP_INPUT_ERROR("len >= decode_len", len >= decode_len, return ERR_VAL;);
1590         decode_idx = DHCP_OPTION_IDX_ROUTER;
1591         break;
1592 #if LWIP_DHCP_PROVIDE_DNS_SERVERS
1593       case (DHCP_OPTION_DNS_SERVER):
1594         /* special case: there might be more than one server */
1595         LWIP_DHCP_INPUT_ERROR("len %% 4 == 0", len % 4 == 0, return ERR_VAL;);
1596         /* limit number of DNS servers */
1597         decode_len = LWIP_MIN(len, 4 * DNS_MAX_SERVERS);
1598         LWIP_DHCP_INPUT_ERROR("len >= decode_len", len >= decode_len, return ERR_VAL;);
1599         decode_idx = DHCP_OPTION_IDX_DNS_SERVER;
1600         break;
1601 #endif /* LWIP_DHCP_PROVIDE_DNS_SERVERS */
1602       case (DHCP_OPTION_LEASE_TIME):
1603         LWIP_DHCP_INPUT_ERROR("len == 4", len == 4, return ERR_VAL;);
1604         decode_idx = DHCP_OPTION_IDX_LEASE_TIME;
1605         break;
1606 #if LWIP_DHCP_GET_NTP_SRV
1607       case (DHCP_OPTION_NTP):
1608         /* special case: there might be more than one server */
1609         LWIP_DHCP_INPUT_ERROR("len %% 4 == 0", len % 4 == 0, return ERR_VAL;);
1610         /* limit number of NTP servers */
1611         decode_len = LWIP_MIN(len, 4 * LWIP_DHCP_MAX_NTP_SERVERS);
1612         LWIP_DHCP_INPUT_ERROR("len >= decode_len", len >= decode_len, return ERR_VAL;);
1613         decode_idx = DHCP_OPTION_IDX_NTP_SERVER;
1614         break;
1615 #endif /* LWIP_DHCP_GET_NTP_SRV*/
1616       case (DHCP_OPTION_OVERLOAD):
1617         LWIP_DHCP_INPUT_ERROR("len == 1", len == 1, return ERR_VAL;);
1618         /* decode overload only in options, not in file/sname: invalid packet */
1619         LWIP_DHCP_INPUT_ERROR("overload in file/sname", options_offset == DHCP_OPTIONS_OFS, return ERR_VAL;);
1620         decode_idx = DHCP_OPTION_IDX_OVERLOAD;
1621         break;
1622       case (DHCP_OPTION_MESSAGE_TYPE):
1623         LWIP_DHCP_INPUT_ERROR("len == 1", len == 1, return ERR_VAL;);
1624         decode_idx = DHCP_OPTION_IDX_MSG_TYPE;
1625         break;
1626       case (DHCP_OPTION_SERVER_ID):
1627         LWIP_DHCP_INPUT_ERROR("len == 4", len == 4, return ERR_VAL;);
1628         decode_idx = DHCP_OPTION_IDX_SERVER_ID;
1629         break;
1630       case (DHCP_OPTION_T1):
1631         LWIP_DHCP_INPUT_ERROR("len == 4", len == 4, return ERR_VAL;);
1632         decode_idx = DHCP_OPTION_IDX_T1;
1633         break;
1634       case (DHCP_OPTION_T2):
1635         LWIP_DHCP_INPUT_ERROR("len == 4", len == 4, return ERR_VAL;);
1636         decode_idx = DHCP_OPTION_IDX_T2;
1637         break;
1638       default:
1639         decode_len = 0;
1640         LWIP_DEBUGF(DHCP_DEBUG, ("skipping option %"U16_F" in options\n", (u16_t)op));
1641         LWIP_HOOK_DHCP_PARSE_OPTION(ip_current_netif(), dhcp, dhcp->state, msg_in,
1642                                     dhcp_option_given(dhcp, DHCP_OPTION_IDX_MSG_TYPE) ? (u8_t)dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_MSG_TYPE) : 0,
1643                                     op, len, q, val_offset);
1644         break;
1645     }
1646     if (op == DHCP_OPTION_PAD) {
1647       offset++;
1648     } else {
1649       if (offset + len + 2 > 0xFFFF) {
1650         /* overflow */
1651         return ERR_BUF;
1652       }
1653       offset = (u16_t)(offset + len + 2);
1654       if (decode_len > 0) {
1655         u32_t value = 0;
1656         u16_t copy_len;
1657 decode_next:
1658         LWIP_ASSERT("check decode_idx", decode_idx >= 0 && decode_idx < DHCP_OPTION_IDX_MAX);
1659         if (!dhcp_option_given(dhcp, decode_idx)) {
1660           copy_len = LWIP_MIN(decode_len, 4);
1661           if (pbuf_copy_partial(q, &value, copy_len, val_offset) != copy_len) {
1662             return ERR_BUF;
1663           }
1664           if (decode_len > 4) {
1665             /* decode more than one u32_t */
1666             u16_t next_val_offset;
1667             LWIP_DHCP_INPUT_ERROR("decode_len %% 4 == 0", decode_len % 4 == 0, return ERR_VAL;);
1668             dhcp_got_option(dhcp, decode_idx);
1669             dhcp_set_option_value(dhcp, decode_idx, lwip_htonl(value));
1670             decode_len = (u8_t)(decode_len - 4);
1671             next_val_offset = (u16_t)(val_offset + 4);
1672             if (next_val_offset < val_offset) {
1673               /* overflow */
1674               return ERR_BUF;
1675             }
1676             val_offset = next_val_offset;
1677             decode_idx++;
1678             goto decode_next;
1679           } else if (decode_len == 4) {
1680             value = lwip_ntohl(value);
1681           } else {
1682             LWIP_DHCP_INPUT_ERROR("invalid decode_len", decode_len == 1, return ERR_VAL;);
1683             value = ((u8_t *)&value)[0];
1684           }
1685           dhcp_got_option(dhcp, decode_idx);
1686           dhcp_set_option_value(dhcp, decode_idx, value);
1687         }
1688       }
1689     }
1690     if (offset >= q->len) {
1691       offset = (u16_t)(offset - q->len);
1692       offset_max = (u16_t)(offset_max - q->len);
1693       if (offset < offset_max) {
1694         q = q->next;
1695         LWIP_DHCP_INPUT_ERROR("next pbuf was null", q != NULL, return ERR_VAL;);
1696         options = (u8_t *)q->payload;
1697       } else {
1698         /* We've run out of bytes, probably no end marker. Don't proceed. */
1699         return ERR_BUF;
1700       }
1701     }
1702   }
1703   /* is this an overloaded message? */
1704   if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_OVERLOAD)) {
1705     u32_t overload = dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_OVERLOAD);
1706     dhcp_clear_option(dhcp, DHCP_OPTION_IDX_OVERLOAD);
1707     if (overload == DHCP_OVERLOAD_FILE) {
1708       parse_file_as_options = 1;
1709       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("overloaded file field\n"));
1710     } else if (overload == DHCP_OVERLOAD_SNAME) {
1711       parse_sname_as_options = 1;
1712       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("overloaded sname field\n"));
1713     } else if (overload == DHCP_OVERLOAD_SNAME_FILE) {
1714       parse_sname_as_options = 1;
1715       parse_file_as_options = 1;
1716       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("overloaded sname and file field\n"));
1717     } else {
1718       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("invalid overload option: %d\n", (int)overload));
1719     }
1720   }
1721   if (parse_file_as_options) {
1722     /* if both are overloaded, parse file first and then sname (RFC 2131 ch. 4.1) */
1723     parse_file_as_options = 0;
1724     options_idx = DHCP_FILE_OFS;
1725     options_idx_max = DHCP_FILE_OFS + DHCP_FILE_LEN;
1726 #if LWIP_DHCP_BOOTP_FILE
1727     file_overloaded = 1;
1728 #endif
1729     goto again;
1730   } else if (parse_sname_as_options) {
1731     parse_sname_as_options = 0;
1732     options_idx = DHCP_SNAME_OFS;
1733     options_idx_max = DHCP_SNAME_OFS + DHCP_SNAME_LEN;
1734     goto again;
1735   }
1736 #if LWIP_DHCP_BOOTP_FILE
1737   if (!file_overloaded) {
1738     /* only do this for ACK messages */
1739     if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_MSG_TYPE) &&
1740       (dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_MSG_TYPE) == DHCP_ACK))
1741     /* copy bootp file name, don't care for sname (server hostname) */
1742     if (pbuf_copy_partial(p, dhcp->boot_file_name, DHCP_FILE_LEN-1, DHCP_FILE_OFS) != (DHCP_FILE_LEN-1)) {
1743       return ERR_BUF;
1744     }
1745     /* make sure the string is really NULL-terminated */
1746     dhcp->boot_file_name[DHCP_FILE_LEN-1] = 0;
1747   }
1748 #endif /* LWIP_DHCP_BOOTP_FILE */
1749   return ERR_OK;
1750 }
1751 
1752 /**
1753  * If an incoming DHCP message is in response to us, then trigger the state machine
1754  */
1755 static void
dhcp_recv(void * arg,struct udp_pcb * pcb,struct pbuf * p,const ip_addr_t * addr,u16_t port)1756 dhcp_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
1757 {
1758   struct netif *netif = ip_current_input_netif();
1759   struct dhcp *dhcp = netif_dhcp_data(netif);
1760   struct dhcp_msg *reply_msg = (struct dhcp_msg *)p->payload;
1761   u8_t msg_type;
1762   u8_t i;
1763   struct dhcp_msg *msg_in;
1764 
1765   LWIP_UNUSED_ARG(arg);
1766 
1767   /* Caught DHCP message from netif that does not have DHCP enabled? -> not interested */
1768   if ((dhcp == NULL) || (dhcp->pcb_allocated == 0)) {
1769     goto free_pbuf_and_return;
1770   }
1771 
1772   LWIP_ASSERT("invalid server address type", IP_IS_V4(addr));
1773 
1774   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_recv(pbuf = %p) from DHCP server %"U16_F".%"U16_F".%"U16_F".%"U16_F" port %"U16_F"\n", (void *)p,
1775               ip4_addr1_16(ip_2_ip4(addr)), ip4_addr2_16(ip_2_ip4(addr)), ip4_addr3_16(ip_2_ip4(addr)), ip4_addr4_16(ip_2_ip4(addr)), port));
1776   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("pbuf->len = %"U16_F"\n", p->len));
1777   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("pbuf->tot_len = %"U16_F"\n", p->tot_len));
1778   /* prevent warnings about unused arguments */
1779   LWIP_UNUSED_ARG(pcb);
1780   LWIP_UNUSED_ARG(addr);
1781   LWIP_UNUSED_ARG(port);
1782 
1783   if (p->len < DHCP_MIN_REPLY_LEN) {
1784     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("DHCP reply message or pbuf too short\n"));
1785     goto free_pbuf_and_return;
1786   }
1787 
1788   if (reply_msg->op != DHCP_BOOTREPLY) {
1789     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("not a DHCP reply message, but type %"U16_F"\n", (u16_t)reply_msg->op));
1790     goto free_pbuf_and_return;
1791   }
1792   /* iterate through hardware address and match against DHCP message */
1793   for (i = 0; i < netif->hwaddr_len && i < LWIP_MIN(DHCP_CHADDR_LEN, NETIF_MAX_HWADDR_LEN); i++) {
1794     if (netif->hwaddr[i] != reply_msg->chaddr[i]) {
1795       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING,
1796                   ("netif->hwaddr[%"U16_F"]==%02"X16_F" != reply_msg->chaddr[%"U16_F"]==%02"X16_F"\n",
1797                    (u16_t)i, (u16_t)netif->hwaddr[i], (u16_t)i, (u16_t)reply_msg->chaddr[i]));
1798       goto free_pbuf_and_return;
1799     }
1800   }
1801   /* match transaction ID against what we expected */
1802   if (lwip_ntohl(reply_msg->xid) != dhcp->xid) {
1803     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING,
1804                 ("transaction id mismatch reply_msg->xid(%"X32_F")!=dhcp->xid(%"X32_F")\n", lwip_ntohl(reply_msg->xid), dhcp->xid));
1805     goto free_pbuf_and_return;
1806   }
1807   /* option fields could be unfold? */
1808   if (dhcp_parse_reply(p, dhcp) != ERR_OK) {
1809     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS,
1810                 ("problem unfolding DHCP message - too short on memory?\n"));
1811     goto free_pbuf_and_return;
1812   }
1813 
1814   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("searching DHCP_OPTION_MESSAGE_TYPE\n"));
1815   /* obtain pointer to DHCP message type */
1816   if (!dhcp_option_given(dhcp, DHCP_OPTION_IDX_MSG_TYPE)) {
1817     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("DHCP_OPTION_MESSAGE_TYPE option not found\n"));
1818     goto free_pbuf_and_return;
1819   }
1820 
1821   msg_in = (struct dhcp_msg *)p->payload;
1822   /* read DHCP message type */
1823   msg_type = (u8_t)dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_MSG_TYPE);
1824   /* message type is DHCP ACK? */
1825   if (msg_type == DHCP_ACK) {
1826     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("DHCP_ACK received\n"));
1827     /* in requesting state? */
1828     if (dhcp->state == DHCP_STATE_REQUESTING) {
1829       dhcp_handle_ack(netif, msg_in);
1830 #if DHCP_DOES_ARP_CHECK
1831       if ((netif->flags & NETIF_FLAG_ETHARP) != 0) {
1832         /* check if the acknowledged lease address is already in use */
1833         dhcp_check(netif);
1834       } else {
1835         /* bind interface to the acknowledged lease address */
1836         dhcp_bind(netif);
1837       }
1838 #else
1839       /* bind interface to the acknowledged lease address */
1840       dhcp_bind(netif);
1841 #endif
1842     }
1843     /* already bound to the given lease address? */
1844     else if ((dhcp->state == DHCP_STATE_REBOOTING) || (dhcp->state == DHCP_STATE_REBINDING) ||
1845              (dhcp->state == DHCP_STATE_RENEWING)) {
1846       dhcp_handle_ack(netif, msg_in);
1847       dhcp_bind(netif);
1848     }
1849   }
1850   /* received a DHCP_NAK in appropriate state? */
1851   else if ((msg_type == DHCP_NAK) &&
1852            ((dhcp->state == DHCP_STATE_REBOOTING) || (dhcp->state == DHCP_STATE_REQUESTING) ||
1853             (dhcp->state == DHCP_STATE_REBINDING) || (dhcp->state == DHCP_STATE_RENEWING  ))) {
1854     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("DHCP_NAK received\n"));
1855     dhcp_handle_nak(netif);
1856   }
1857   /* received a DHCP_OFFER in DHCP_STATE_SELECTING state? */
1858   else if ((msg_type == DHCP_OFFER) && (dhcp->state == DHCP_STATE_SELECTING)) {
1859     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("DHCP_OFFER received in DHCP_STATE_SELECTING state\n"));
1860     /* remember offered lease */
1861     dhcp_handle_offer(netif, msg_in);
1862   }
1863 
1864 free_pbuf_and_return:
1865   pbuf_free(p);
1866 }
1867 
1868 /**
1869  * Create a DHCP request, fill in common headers
1870  *
1871  * @param netif the netif under DHCP control
1872  * @param dhcp dhcp control struct
1873  * @param message_type message type of the request
1874  */
1875 static struct pbuf *
dhcp_create_msg(struct netif * netif,struct dhcp * dhcp,u8_t message_type,u16_t * options_out_len)1876 dhcp_create_msg(struct netif *netif, struct dhcp *dhcp, u8_t message_type, u16_t *options_out_len)
1877 {
1878   u16_t i;
1879   struct pbuf *p_out;
1880   struct dhcp_msg *msg_out;
1881   u16_t options_out_len_loc;
1882 
1883 #ifndef DHCP_GLOBAL_XID
1884   /** default global transaction identifier starting value (easy to match
1885    *  with a packet analyser). We simply increment for each new request.
1886    *  Predefine DHCP_GLOBAL_XID to a better value or a function call to generate one
1887    *  at runtime, any supporting function prototypes can be defined in DHCP_GLOBAL_XID_HEADER */
1888 #if DHCP_CREATE_RAND_XID && defined(LWIP_RAND)
1889   static u32_t xid;
1890 #else /* DHCP_CREATE_RAND_XID && defined(LWIP_RAND) */
1891   static u32_t xid = 0xABCD0000;
1892 #endif /* DHCP_CREATE_RAND_XID && defined(LWIP_RAND) */
1893 #else
1894   if (!xid_initialised) {
1895     xid = DHCP_GLOBAL_XID;
1896     xid_initialised = !xid_initialised;
1897   }
1898 #endif
1899   LWIP_ERROR("dhcp_create_msg: netif != NULL", (netif != NULL), return NULL;);
1900   LWIP_ERROR("dhcp_create_msg: dhcp != NULL", (dhcp != NULL), return NULL;);
1901   p_out = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct dhcp_msg), PBUF_RAM);
1902   if (p_out == NULL) {
1903     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS,
1904                 ("dhcp_create_msg(): could not allocate pbuf\n"));
1905     return NULL;
1906   }
1907   LWIP_ASSERT("dhcp_create_msg: check that first pbuf can hold struct dhcp_msg",
1908               (p_out->len >= sizeof(struct dhcp_msg)));
1909 
1910   /* DHCP_REQUEST should reuse 'xid' from DHCPOFFER */
1911   if ((message_type != DHCP_REQUEST) || (dhcp->state == DHCP_STATE_REBOOTING)) {
1912     /* reuse transaction identifier in retransmissions */
1913     if (dhcp->tries == 0) {
1914 #if DHCP_CREATE_RAND_XID && defined(LWIP_RAND)
1915       xid = LWIP_RAND();
1916 #else /* DHCP_CREATE_RAND_XID && defined(LWIP_RAND) */
1917       xid++;
1918 #endif /* DHCP_CREATE_RAND_XID && defined(LWIP_RAND) */
1919     }
1920     dhcp->xid = xid;
1921   }
1922   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE,
1923               ("transaction id xid(%"X32_F")\n", xid));
1924 
1925   msg_out = (struct dhcp_msg *)p_out->payload;
1926   memset(msg_out, 0, sizeof(struct dhcp_msg));
1927 
1928   msg_out->op = DHCP_BOOTREQUEST;
1929   /* @todo: make link layer independent */
1930   msg_out->htype = LWIP_IANA_HWTYPE_ETHERNET;
1931   msg_out->hlen = netif->hwaddr_len;
1932   msg_out->xid = lwip_htonl(dhcp->xid);
1933   /* we don't need the broadcast flag since we can receive unicast traffic
1934      before being fully configured! */
1935   /* set ciaddr to netif->ip_addr based on message_type and state */
1936   if ((message_type == DHCP_INFORM) || (message_type == DHCP_DECLINE) || (message_type == DHCP_RELEASE) ||
1937       ((message_type == DHCP_REQUEST) && /* DHCP_STATE_BOUND not used for sending! */
1938        ((dhcp->state == DHCP_STATE_RENEWING) || dhcp->state == DHCP_STATE_REBINDING))) {
1939     ip4_addr_copy(msg_out->ciaddr, *netif_ip4_addr(netif));
1940   }
1941   for (i = 0; i < LWIP_MIN(DHCP_CHADDR_LEN, NETIF_MAX_HWADDR_LEN); i++) {
1942     /* copy netif hardware address (padded with zeroes through memset already) */
1943     msg_out->chaddr[i] = netif->hwaddr[i];
1944   }
1945   msg_out->cookie = PP_HTONL(DHCP_MAGIC_COOKIE);
1946   /* Add option MESSAGE_TYPE */
1947   options_out_len_loc = dhcp_option(0, msg_out->options, DHCP_OPTION_MESSAGE_TYPE, DHCP_OPTION_MESSAGE_TYPE_LEN);
1948   options_out_len_loc = dhcp_option_byte(options_out_len_loc, msg_out->options, message_type);
1949   if (options_out_len) {
1950     *options_out_len = options_out_len_loc;
1951   }
1952   return p_out;
1953 }
1954 
1955 /**
1956  * Add a DHCP message trailer
1957  *
1958  * Adds the END option to the DHCP message, and if
1959  * necessary, up to three padding bytes.
1960  */
1961 static void
dhcp_option_trailer(u16_t options_out_len,u8_t * options,struct pbuf * p_out)1962 dhcp_option_trailer(u16_t options_out_len, u8_t *options, struct pbuf *p_out)
1963 {
1964   options[options_out_len++] = DHCP_OPTION_END;
1965   /* packet is too small, or not 4 byte aligned? */
1966   while (((options_out_len < DHCP_MIN_OPTIONS_LEN) || (options_out_len & 3)) &&
1967          (options_out_len < DHCP_OPTIONS_LEN)) {
1968     /* add a fill/padding byte */
1969     options[options_out_len++] = 0;
1970   }
1971   /* shrink the pbuf to the actual content length */
1972   pbuf_realloc(p_out, (u16_t)(sizeof(struct dhcp_msg) - DHCP_OPTIONS_LEN + options_out_len));
1973 }
1974 
1975 /** check if DHCP supplied netif->ip_addr
1976  *
1977  * @param netif the netif to check
1978  * @return 1 if DHCP supplied netif->ip_addr (states BOUND or RENEWING),
1979  *         0 otherwise
1980  */
1981 u8_t
dhcp_supplied_address(const struct netif * netif)1982 dhcp_supplied_address(const struct netif *netif)
1983 {
1984   if ((netif != NULL) && (netif_dhcp_data(netif) != NULL)) {
1985     struct dhcp *dhcp = netif_dhcp_data(netif);
1986     return (dhcp->state == DHCP_STATE_BOUND) || (dhcp->state == DHCP_STATE_RENEWING) ||
1987            (dhcp->state == DHCP_STATE_REBINDING);
1988   }
1989   return 0;
1990 }
1991 
1992 #endif /* LWIP_IPV4 && LWIP_DHCP */
1993