• 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 #ifdef LOSCFG_NET_CONTAINER
442   NETIF_FOREACH(netif, get_root_net_group()) {
443 #else
444   NETIF_FOREACH(netif) {
445 #endif
446     /* only act on DHCP configured interfaces */
447     struct dhcp *dhcp = netif_dhcp_data(netif);
448     if ((dhcp != NULL) && (dhcp->state != DHCP_STATE_OFF)) {
449       /* compare lease time to expire timeout */
450       if (dhcp->t0_timeout && (++dhcp->lease_used == dhcp->t0_timeout)) {
451         LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_coarse_tmr(): t0 timeout\n"));
452         /* this clients' lease time has expired */
453         dhcp_release_and_stop(netif);
454         dhcp_start(netif);
455         /* timer is active (non zero), and triggers (zeroes) now? */
456       } else if (dhcp->t2_rebind_time && (dhcp->t2_rebind_time-- == 1)) {
457         LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_coarse_tmr(): t2 timeout\n"));
458         /* this clients' rebind timeout triggered */
459         dhcp_t2_timeout(netif);
460         /* timer is active (non zero), and triggers (zeroes) now */
461       } else if (dhcp->t1_renew_time && (dhcp->t1_renew_time-- == 1)) {
462         LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_coarse_tmr(): t1 timeout\n"));
463         /* this clients' renewal timeout triggered */
464         dhcp_t1_timeout(netif);
465       }
466     }
467   }
468 }
469 
470 #if LWIP_LOWPOWER
471 #include "lwip/lowpower.h"
472 
473 u32_t
474 dhcp_coarse_tmr_tick(void)
475 {
476   struct netif *netif;
477   u32_t tick = 0;
478   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_coarse_tmr()\n"));
479   /* iterate through all network interfaces */
480 #ifdef LOSCFG_NET_CONTAINER
481   NETIF_FOREACH(netif, get_root_net_group())
482 #else
483   NETIF_FOREACH(netif)
484 #endif
485   {
486     struct dhcp *dhcp = netif_dhcp_data(netif);
487     if ((dhcp != NULL) && (dhcp->state != DHCP_STATE_OFF)) {
488       if (dhcp->t0_timeout > 0) {
489         if (dhcp->t0_timeout > dhcp->lease_used) {
490           SET_TMR_TICK(tick, dhcp->t0_timeout - dhcp->lease_used);
491         } else {
492           SET_TMR_TICK(tick, 1);
493         }
494       }
495       if (dhcp->t2_rebind_time > 0) {
496         SET_TMR_TICK(tick, dhcp->t2_rebind_time);
497       }
498       if (dhcp->t1_renew_time > 0) {
499         SET_TMR_TICK(tick, dhcp->t1_renew_time);
500       }
501     }
502   }
503   return tick;
504 }
505 
506 u32_t
507 dhcp_fine_tmr_tick(void)
508 {
509   struct netif *netif;
510   u32_t tick = 0;
511   /* loop through netif's */
512 #ifdef LOSCFG_NET_CONTAINER
513   NETIF_FOREACH(netif, get_root_net_group())
514 #else
515   NETIF_FOREACH(netif)
516 #endif
517   {
518     struct dhcp *dhcp = netif_dhcp_data(netif);
519     if (dhcp != NULL) {
520       if (dhcp->request_timeout > 0) {
521         SET_TMR_TICK(tick, dhcp->request_timeout);
522       }
523     }
524   }
525   return tick;
526 }
527 #endif /* LWIP_LOWPOWER */
528 
529 /**
530  * DHCP transaction timeout handling (this function must be called every 500ms,
531  * see @ref DHCP_FINE_TIMER_MSECS).
532  *
533  * A DHCP server is expected to respond within a short period of time.
534  * This timer checks whether an outstanding DHCP request is timed out.
535  */
536 void
537 dhcp_fine_tmr(void)
538 {
539   struct netif *netif;
540   /* loop through netif's */
541 #ifdef LOSCFG_NET_CONTAINER
542   NETIF_FOREACH(netif, get_root_net_group()) {
543 #else
544   NETIF_FOREACH(netif) {
545 #endif
546     struct dhcp *dhcp = netif_dhcp_data(netif);
547     /* only act on DHCP configured interfaces */
548     if (dhcp != NULL) {
549       /* timer is active (non zero), and is about to trigger now */
550       if (dhcp->request_timeout > 1) {
551         dhcp->request_timeout--;
552       } else if (dhcp->request_timeout == 1) {
553         dhcp->request_timeout--;
554         /* { dhcp->request_timeout == 0 } */
555         LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_fine_tmr(): request timeout\n"));
556         /* this client's request timeout triggered */
557         dhcp_timeout(netif);
558       }
559     }
560   }
561 }
562 
563 /**
564  * A DHCP negotiation transaction, or ARP request, has timed out.
565  *
566  * The timer that was started with the DHCP or ARP request has
567  * timed out, indicating no response was received in time.
568  *
569  * @param netif the netif under DHCP control
570  */
571 static void
572 dhcp_timeout(struct netif *netif)
573 {
574   struct dhcp *dhcp = netif_dhcp_data(netif);
575 
576   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_timeout()\n"));
577   /* back-off period has passed, or server selection timed out */
578   if ((dhcp->state == DHCP_STATE_BACKING_OFF) || (dhcp->state == DHCP_STATE_SELECTING)) {
579     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_timeout(): restarting discovery\n"));
580     dhcp_discover(netif);
581     /* receiving the requested lease timed out */
582   } else if (dhcp->state == DHCP_STATE_REQUESTING) {
583     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_timeout(): REQUESTING, DHCP request timed out\n"));
584     if (dhcp->tries <= 5) {
585       dhcp_select(netif);
586     } else {
587       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_timeout(): REQUESTING, releasing, restarting\n"));
588       dhcp_release_and_stop(netif);
589       dhcp_start(netif);
590     }
591 #if DHCP_DOES_ARP_CHECK
592     /* received no ARP reply for the offered address (which is good) */
593   } else if (dhcp->state == DHCP_STATE_CHECKING) {
594     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_timeout(): CHECKING, ARP request timed out\n"));
595     if (dhcp->tries <= 1) {
596       dhcp_check(netif);
597       /* no ARP replies on the offered address,
598          looks like the IP address is indeed free */
599     } else {
600       /* bind the interface to the offered address */
601       dhcp_bind(netif);
602     }
603 #endif /* DHCP_DOES_ARP_CHECK */
604   } else if (dhcp->state == DHCP_STATE_REBOOTING) {
605     if (dhcp->tries < REBOOT_TRIES) {
606       dhcp_reboot(netif);
607     } else {
608       dhcp_discover(netif);
609     }
610   }
611 }
612 
613 /**
614  * The renewal period has timed out.
615  *
616  * @param netif the netif under DHCP control
617  */
618 static void
619 dhcp_t1_timeout(struct netif *netif)
620 {
621   struct dhcp *dhcp = netif_dhcp_data(netif);
622 
623   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_STATE, ("dhcp_t1_timeout()\n"));
624   if ((dhcp->state == DHCP_STATE_REQUESTING) || (dhcp->state == DHCP_STATE_BOUND) ||
625       (dhcp->state == DHCP_STATE_RENEWING)) {
626     /* just retry to renew - note that the rebind timer (t2) will
627      * eventually time-out if renew tries fail. */
628     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
629                 ("dhcp_t1_timeout(): must renew\n"));
630     /* This slightly different to RFC2131: DHCPREQUEST will be sent from state
631        DHCP_STATE_RENEWING, not DHCP_STATE_BOUND */
632     dhcp_renew(netif);
633     /* Calculate next timeout */
634     if (((dhcp->t2_timeout - dhcp->lease_used) / 2) >= ((60 + DHCP_COARSE_TIMER_SECS / 2) / DHCP_COARSE_TIMER_SECS)) {
635       dhcp->t1_renew_time = (u16_t)((dhcp->t2_timeout - dhcp->lease_used) / 2);
636     }
637   }
638 }
639 
640 /**
641  * The rebind period has timed out.
642  *
643  * @param netif the netif under DHCP control
644  */
645 static void
646 dhcp_t2_timeout(struct netif *netif)
647 {
648   struct dhcp *dhcp = netif_dhcp_data(netif);
649 
650   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_t2_timeout()\n"));
651   if ((dhcp->state == DHCP_STATE_REQUESTING) || (dhcp->state == DHCP_STATE_BOUND) ||
652       (dhcp->state == DHCP_STATE_RENEWING) || (dhcp->state == DHCP_STATE_REBINDING)) {
653     /* just retry to rebind */
654     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
655                 ("dhcp_t2_timeout(): must rebind\n"));
656     /* This slightly different to RFC2131: DHCPREQUEST will be sent from state
657        DHCP_STATE_REBINDING, not DHCP_STATE_BOUND */
658     dhcp_rebind(netif);
659     /* Calculate next timeout */
660     if (((dhcp->t0_timeout - dhcp->lease_used) / 2) >= ((60 + DHCP_COARSE_TIMER_SECS / 2) / DHCP_COARSE_TIMER_SECS)) {
661       dhcp->t2_rebind_time = (u16_t)((dhcp->t0_timeout - dhcp->lease_used) / 2);
662     }
663   }
664 }
665 
666 /**
667  * Handle a DHCP ACK packet
668  *
669  * @param netif the netif under DHCP control
670  */
671 static void
672 dhcp_handle_ack(struct netif *netif, struct dhcp_msg *msg_in)
673 {
674   struct dhcp *dhcp = netif_dhcp_data(netif);
675 
676 #if LWIP_DHCP_PROVIDE_DNS_SERVERS || LWIP_DHCP_GET_NTP_SRV
677   u8_t n;
678 #endif /* LWIP_DHCP_PROVIDE_DNS_SERVERS || LWIP_DHCP_GET_NTP_SRV */
679 #if LWIP_DHCP_GET_NTP_SRV
680   ip4_addr_t ntp_server_addrs[LWIP_DHCP_MAX_NTP_SERVERS];
681 #endif
682 
683   /* clear options we might not get from the ACK */
684   ip4_addr_set_zero(&dhcp->offered_sn_mask);
685   ip4_addr_set_zero(&dhcp->offered_gw_addr);
686 #if LWIP_DHCP_BOOTP_FILE
687   ip4_addr_set_zero(&dhcp->offered_si_addr);
688 #endif /* LWIP_DHCP_BOOTP_FILE */
689 
690   /* lease time given? */
691   if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_LEASE_TIME)) {
692     /* remember offered lease time */
693     dhcp->offered_t0_lease = dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_LEASE_TIME);
694   }
695   /* renewal period given? */
696   if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_T1)) {
697     /* remember given renewal period */
698     dhcp->offered_t1_renew = dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_T1);
699   } else {
700     /* calculate safe periods for renewal */
701     dhcp->offered_t1_renew = dhcp->offered_t0_lease / 2;
702   }
703 
704   /* renewal period given? */
705   if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_T2)) {
706     /* remember given rebind period */
707     dhcp->offered_t2_rebind = dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_T2);
708   } else {
709     /* calculate safe periods for rebinding (offered_t0_lease * 0.875 -> 87.5%)*/
710     dhcp->offered_t2_rebind = (dhcp->offered_t0_lease * 7U) / 8U;
711   }
712 
713   /* (y)our internet address */
714   ip4_addr_copy(dhcp->offered_ip_addr, msg_in->yiaddr);
715 
716 #if LWIP_DHCP_BOOTP_FILE
717   /* copy boot server address,
718      boot file name copied in dhcp_parse_reply if not overloaded */
719   ip4_addr_copy(dhcp->offered_si_addr, msg_in->siaddr);
720 #endif /* LWIP_DHCP_BOOTP_FILE */
721 
722   /* subnet mask given? */
723   if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_SUBNET_MASK)) {
724     /* remember given subnet mask */
725     ip4_addr_set_u32(&dhcp->offered_sn_mask, lwip_htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_SUBNET_MASK)));
726     dhcp->subnet_mask_given = 1;
727   } else {
728     dhcp->subnet_mask_given = 0;
729   }
730 
731   /* gateway router */
732   if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_ROUTER)) {
733     ip4_addr_set_u32(&dhcp->offered_gw_addr, lwip_htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_ROUTER)));
734   }
735 
736 #if LWIP_DHCP_GET_NTP_SRV
737   /* NTP servers */
738   for (n = 0; (n < LWIP_DHCP_MAX_NTP_SERVERS) && dhcp_option_given(dhcp, DHCP_OPTION_IDX_NTP_SERVER + n); n++) {
739     ip4_addr_set_u32(&ntp_server_addrs[n], lwip_htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_NTP_SERVER + n)));
740   }
741   dhcp_set_ntp_servers(n, ntp_server_addrs);
742 #endif /* LWIP_DHCP_GET_NTP_SRV */
743 
744 #if LWIP_DHCP_PROVIDE_DNS_SERVERS
745   /* DNS servers */
746   for (n = 0; (n < LWIP_DHCP_PROVIDE_DNS_SERVERS) && dhcp_option_given(dhcp, DHCP_OPTION_IDX_DNS_SERVER + n); n++) {
747     ip_addr_t dns_addr;
748     ip_addr_set_ip4_u32_val(dns_addr, lwip_htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_DNS_SERVER + n)));
749     dns_setserver(n, &dns_addr);
750   }
751 #endif /* LWIP_DHCP_PROVIDE_DNS_SERVERS */
752 }
753 
754 /**
755  * @ingroup dhcp4
756  * Set a statically allocated struct dhcp to work with.
757  * Using this prevents dhcp_start to allocate it using mem_malloc.
758  *
759  * @param netif the netif for which to set the struct dhcp
760  * @param dhcp (uninitialised) dhcp struct allocated by the application
761  */
762 void
763 dhcp_set_struct(struct netif *netif, struct dhcp *dhcp)
764 {
765   LWIP_ASSERT_CORE_LOCKED();
766   LWIP_ASSERT("netif != NULL", netif != NULL);
767   LWIP_ASSERT("dhcp != NULL", dhcp != NULL);
768   LWIP_ASSERT("netif already has a struct dhcp set", netif_dhcp_data(netif) == NULL);
769 
770   /* clear data structure */
771   memset(dhcp, 0, sizeof(struct dhcp));
772   /* dhcp_set_state(&dhcp, DHCP_STATE_OFF); */
773   netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP, dhcp);
774 }
775 
776 /**
777  * @ingroup dhcp4
778  * Removes a struct dhcp from a netif.
779  *
780  * ATTENTION: Only use this when not using dhcp_set_struct() to allocate the
781  *            struct dhcp since the memory is passed back to the heap.
782  *
783  * @param netif the netif from which to remove the struct dhcp
784  */
785 void dhcp_cleanup(struct netif *netif)
786 {
787   LWIP_ASSERT_CORE_LOCKED();
788   LWIP_ASSERT("netif != NULL", netif != NULL);
789 
790   if (netif_dhcp_data(netif) != NULL) {
791     mem_free(netif_dhcp_data(netif));
792     netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP, NULL);
793   }
794 }
795 
796 /**
797  * @ingroup dhcp4
798  * Start DHCP negotiation for a network interface.
799  *
800  * If no DHCP client instance was attached to this interface,
801  * a new client is created first. If a DHCP client instance
802  * was already present, it restarts negotiation.
803  *
804  * @param netif The lwIP network interface
805  * @return lwIP error code
806  * - ERR_OK - No error
807  * - ERR_MEM - Out of memory
808  */
809 err_t
810 dhcp_start(struct netif *netif)
811 {
812   struct dhcp *dhcp;
813   err_t result;
814 
815   LWIP_ASSERT_CORE_LOCKED();
816   LWIP_ERROR("netif != NULL", (netif != NULL), return ERR_ARG;);
817   LWIP_ERROR("netif is not up, old style port?", netif_is_up(netif), return ERR_ARG;);
818   dhcp = netif_dhcp_data(netif);
819   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));
820 
821   /* check MTU of the netif */
822   if (netif->mtu < DHCP_MAX_MSG_LEN_MIN_REQUIRED) {
823     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): Cannot use this netif with DHCP: MTU is too small\n"));
824     return ERR_MEM;
825   }
826 
827   /* no DHCP client attached yet? */
828   if (dhcp == NULL) {
829     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): mallocing new DHCP client\n"));
830     dhcp = (struct dhcp *)mem_malloc(sizeof(struct dhcp));
831     if (dhcp == NULL) {
832       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): could not allocate dhcp\n"));
833       return ERR_MEM;
834     }
835 
836     /* store this dhcp client in the netif */
837     netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP, dhcp);
838     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): allocated dhcp"));
839     /* already has DHCP client attached */
840   } else {
841     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_start(): restarting DHCP configuration\n"));
842 
843     if (dhcp->pcb_allocated != 0) {
844       dhcp_dec_pcb_refcount(); /* free DHCP PCB if not needed any more */
845     }
846     /* dhcp is cleared below, no need to reset flag*/
847   }
848 
849   /* clear data structure */
850   memset(dhcp, 0, sizeof(struct dhcp));
851   /* dhcp_set_state(&dhcp, DHCP_STATE_OFF); */
852 
853   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): starting DHCP configuration\n"));
854 
855   if (dhcp_inc_pcb_refcount() != ERR_OK) { /* ensure DHCP PCB is allocated */
856     return ERR_MEM;
857   }
858   dhcp->pcb_allocated = 1;
859 
860   if (!netif_is_link_up(netif)) {
861     /* set state INIT and wait for dhcp_network_changed() to call dhcp_discover() */
862     dhcp_set_state(dhcp, DHCP_STATE_INIT);
863     return ERR_OK;
864   }
865 
866   /* (re)start the DHCP negotiation */
867   result = dhcp_discover(netif);
868   if (result != ERR_OK) {
869     /* free resources allocated above */
870     dhcp_release_and_stop(netif);
871     return ERR_MEM;
872   }
873   return result;
874 }
875 
876 /**
877  * @ingroup dhcp4
878  * Inform a DHCP server of our manual configuration.
879  *
880  * This informs DHCP servers of our fixed IP address configuration
881  * by sending an INFORM message. It does not involve DHCP address
882  * configuration, it is just here to be nice to the network.
883  *
884  * @param netif The lwIP network interface
885  */
886 void
887 dhcp_inform(struct netif *netif)
888 {
889   struct dhcp dhcp;
890   struct pbuf *p_out;
891   u16_t options_out_len;
892 
893   LWIP_ASSERT_CORE_LOCKED();
894   LWIP_ERROR("netif != NULL", (netif != NULL), return;);
895 
896   if (dhcp_inc_pcb_refcount() != ERR_OK) { /* ensure DHCP PCB is allocated */
897     return;
898   }
899 
900   memset(&dhcp, 0, sizeof(struct dhcp));
901   dhcp_set_state(&dhcp, DHCP_STATE_INFORMING);
902 
903   /* create and initialize the DHCP message header */
904   p_out = dhcp_create_msg(netif, &dhcp, DHCP_INFORM, &options_out_len);
905   if (p_out != NULL) {
906     struct dhcp_msg *msg_out = (struct dhcp_msg *)p_out->payload;
907     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN);
908     options_out_len = dhcp_option_short(options_out_len, msg_out->options, DHCP_MAX_MSG_LEN(netif));
909 
910     LWIP_HOOK_DHCP_APPEND_OPTIONS(netif, &dhcp, DHCP_STATE_INFORMING, msg_out, DHCP_INFORM, &options_out_len);
911     dhcp_option_trailer(options_out_len, msg_out->options, p_out);
912 
913     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_inform: INFORMING\n"));
914 
915     udp_sendto_if(dhcp_pcb, p_out, IP_ADDR_BROADCAST, LWIP_IANA_PORT_DHCP_SERVER, netif);
916 
917     pbuf_free(p_out);
918   } else {
919     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_inform: could not allocate DHCP request\n"));
920   }
921 
922   dhcp_dec_pcb_refcount(); /* delete DHCP PCB if not needed any more */
923 }
924 
925 /** Handle a possible change in the network configuration.
926  *
927  * This enters the REBOOTING state to verify that the currently bound
928  * address is still valid.
929  */
930 void
931 dhcp_network_changed(struct netif *netif)
932 {
933   struct dhcp *dhcp = netif_dhcp_data(netif);
934 
935   if (!dhcp) {
936     return;
937   }
938   switch (dhcp->state) {
939     case DHCP_STATE_REBINDING:
940     case DHCP_STATE_RENEWING:
941     case DHCP_STATE_BOUND:
942     case DHCP_STATE_REBOOTING:
943       dhcp->tries = 0;
944       dhcp_reboot(netif);
945       break;
946     case DHCP_STATE_OFF:
947       /* stay off */
948       break;
949     default:
950       LWIP_ASSERT("invalid dhcp->state", dhcp->state <= DHCP_STATE_BACKING_OFF);
951       /* INIT/REQUESTING/CHECKING/BACKING_OFF restart with new 'rid' because the
952          state changes, SELECTING: continue with current 'rid' as we stay in the
953          same state */
954 #if LWIP_DHCP_AUTOIP_COOP
955       if (dhcp->autoip_coop_state == DHCP_AUTOIP_COOP_STATE_ON) {
956         autoip_stop(netif);
957         dhcp->autoip_coop_state = DHCP_AUTOIP_COOP_STATE_OFF;
958       }
959 #endif /* LWIP_DHCP_AUTOIP_COOP */
960       /* ensure we start with short timeouts, even if already discovering */
961       dhcp->tries = 0;
962       dhcp_discover(netif);
963       break;
964   }
965 }
966 
967 #if DHCP_DOES_ARP_CHECK
968 /**
969  * Match an ARP reply with the offered IP address:
970  * check whether the offered IP address is not in use using ARP
971  *
972  * @param netif the network interface on which the reply was received
973  * @param addr The IP address we received a reply from
974  */
975 void
976 dhcp_arp_reply(struct netif *netif, const ip4_addr_t *addr)
977 {
978   struct dhcp *dhcp;
979 
980   LWIP_ERROR("netif != NULL", (netif != NULL), return;);
981   dhcp = netif_dhcp_data(netif);
982   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_arp_reply()\n"));
983   /* is a DHCP client doing an ARP check? */
984   if ((dhcp != NULL) && (dhcp->state == DHCP_STATE_CHECKING)) {
985     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_arp_reply(): CHECKING, arp reply for 0x%08"X32_F"\n",
986                 ip4_addr_get_u32(addr)));
987     /* did a host respond with the address we
988        were offered by the DHCP server? */
989     if (ip4_addr_cmp(addr, &dhcp->offered_ip_addr)) {
990       /* we will not accept the offered address */
991       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE | LWIP_DBG_LEVEL_WARNING,
992                   ("dhcp_arp_reply(): arp reply matched with offered address, declining\n"));
993       dhcp_decline(netif);
994     }
995   }
996 }
997 
998 /**
999  * Decline an offered lease.
1000  *
1001  * Tell the DHCP server we do not accept the offered address.
1002  * One reason to decline the lease is when we find out the address
1003  * is already in use by another host (through ARP).
1004  *
1005  * @param netif the netif under DHCP control
1006  */
1007 static err_t
1008 dhcp_decline(struct netif *netif)
1009 {
1010   struct dhcp *dhcp = netif_dhcp_data(netif);
1011   err_t result;
1012   u16_t msecs;
1013   struct pbuf *p_out;
1014   u16_t options_out_len;
1015 
1016   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_decline()\n"));
1017   dhcp_set_state(dhcp, DHCP_STATE_BACKING_OFF);
1018   /* create and initialize the DHCP message header */
1019   p_out = dhcp_create_msg(netif, dhcp, DHCP_DECLINE, &options_out_len);
1020   if (p_out != NULL) {
1021     struct dhcp_msg *msg_out = (struct dhcp_msg *)p_out->payload;
1022     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_REQUESTED_IP, 4);
1023     options_out_len = dhcp_option_long(options_out_len, msg_out->options, lwip_ntohl(ip4_addr_get_u32(&dhcp->offered_ip_addr)));
1024 
1025     LWIP_HOOK_DHCP_APPEND_OPTIONS(netif, dhcp, DHCP_STATE_BACKING_OFF, msg_out, DHCP_DECLINE, &options_out_len);
1026     dhcp_option_trailer(options_out_len, msg_out->options, p_out);
1027 
1028     /* per section 4.4.4, broadcast DECLINE messages */
1029     result = udp_sendto_if_src(dhcp_pcb, p_out, IP_ADDR_BROADCAST, LWIP_IANA_PORT_DHCP_SERVER, netif, IP4_ADDR_ANY);
1030     pbuf_free(p_out);
1031     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_decline: BACKING OFF\n"));
1032   } else {
1033     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS,
1034                 ("dhcp_decline: could not allocate DHCP request\n"));
1035     result = ERR_MEM;
1036   }
1037   if (dhcp->tries < 255) {
1038     dhcp->tries++;
1039   }
1040   msecs = 10 * 1000;
1041   dhcp->request_timeout = (u16_t)((msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS);
1042   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_decline(): set request timeout %"U16_F" msecs\n", msecs));
1043   return result;
1044 }
1045 #endif /* DHCP_DOES_ARP_CHECK */
1046 
1047 
1048 /**
1049  * Start the DHCP process, discover a DHCP server.
1050  *
1051  * @param netif the netif under DHCP control
1052  */
1053 static err_t
1054 dhcp_discover(struct netif *netif)
1055 {
1056   struct dhcp *dhcp = netif_dhcp_data(netif);
1057   err_t result = ERR_OK;
1058   u16_t msecs;
1059   u8_t i;
1060   struct pbuf *p_out;
1061   u16_t options_out_len;
1062 
1063   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_discover()\n"));
1064 
1065   ip4_addr_set_any(&dhcp->offered_ip_addr);
1066   dhcp_set_state(dhcp, DHCP_STATE_SELECTING);
1067   /* create and initialize the DHCP message header */
1068   p_out = dhcp_create_msg(netif, dhcp, DHCP_DISCOVER, &options_out_len);
1069   if (p_out != NULL) {
1070     struct dhcp_msg *msg_out = (struct dhcp_msg *)p_out->payload;
1071     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_discover: making request\n"));
1072 
1073     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN);
1074     options_out_len = dhcp_option_short(options_out_len, msg_out->options, DHCP_MAX_MSG_LEN(netif));
1075 
1076     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_PARAMETER_REQUEST_LIST, LWIP_ARRAYSIZE(dhcp_discover_request_options));
1077     for (i = 0; i < LWIP_ARRAYSIZE(dhcp_discover_request_options); i++) {
1078       options_out_len = dhcp_option_byte(options_out_len, msg_out->options, dhcp_discover_request_options[i]);
1079     }
1080     LWIP_HOOK_DHCP_APPEND_OPTIONS(netif, dhcp, DHCP_STATE_SELECTING, msg_out, DHCP_DISCOVER, &options_out_len);
1081     dhcp_option_trailer(options_out_len, msg_out->options, p_out);
1082 
1083     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_discover: sendto(DISCOVER, IP_ADDR_BROADCAST, LWIP_IANA_PORT_DHCP_SERVER)\n"));
1084     udp_sendto_if_src(dhcp_pcb, p_out, IP_ADDR_BROADCAST, LWIP_IANA_PORT_DHCP_SERVER, netif, IP4_ADDR_ANY);
1085     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_discover: deleting()ing\n"));
1086     pbuf_free(p_out);
1087     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_discover: SELECTING\n"));
1088   } else {
1089     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_discover: could not allocate DHCP request\n"));
1090   }
1091   if (dhcp->tries < 255) {
1092     dhcp->tries++;
1093   }
1094 #if LWIP_DHCP_AUTOIP_COOP
1095   if (dhcp->tries >= LWIP_DHCP_AUTOIP_COOP_TRIES && dhcp->autoip_coop_state == DHCP_AUTOIP_COOP_STATE_OFF) {
1096     dhcp->autoip_coop_state = DHCP_AUTOIP_COOP_STATE_ON;
1097     autoip_start(netif);
1098   }
1099 #endif /* LWIP_DHCP_AUTOIP_COOP */
1100   msecs = (u16_t)((dhcp->tries < 6 ? 1 << dhcp->tries : 60) * 1000);
1101   dhcp->request_timeout = (u16_t)((msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS);
1102   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_discover(): set request timeout %"U16_F" msecs\n", msecs));
1103   return result;
1104 }
1105 
1106 
1107 /**
1108  * Bind the interface to the offered IP address.
1109  *
1110  * @param netif network interface to bind to the offered address
1111  */
1112 static void
1113 dhcp_bind(struct netif *netif)
1114 {
1115   u32_t timeout;
1116   struct dhcp *dhcp;
1117   ip4_addr_t sn_mask, gw_addr;
1118   LWIP_ERROR("dhcp_bind: netif != NULL", (netif != NULL), return;);
1119   dhcp = netif_dhcp_data(netif);
1120   LWIP_ERROR("dhcp_bind: dhcp != NULL", (dhcp != NULL), return;);
1121   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));
1122 
1123   /* reset time used of lease */
1124   dhcp->lease_used = 0;
1125 
1126   if (dhcp->offered_t0_lease != 0xffffffffUL) {
1127     /* set renewal period timer */
1128     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_bind(): t0 renewal timer %"U32_F" secs\n", dhcp->offered_t0_lease));
1129     timeout = (dhcp->offered_t0_lease + DHCP_COARSE_TIMER_SECS / 2) / DHCP_COARSE_TIMER_SECS;
1130     if (timeout > 0xffff) {
1131       timeout = 0xffff;
1132     }
1133     dhcp->t0_timeout = (u16_t)timeout;
1134     if (dhcp->t0_timeout == 0) {
1135       dhcp->t0_timeout = 1;
1136     }
1137     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_bind(): set request timeout %"U32_F" msecs\n", dhcp->offered_t0_lease * 1000));
1138   }
1139 
1140   /* temporary DHCP lease? */
1141   if (dhcp->offered_t1_renew != 0xffffffffUL) {
1142     /* set renewal period timer */
1143     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_bind(): t1 renewal timer %"U32_F" secs\n", dhcp->offered_t1_renew));
1144     timeout = (dhcp->offered_t1_renew + DHCP_COARSE_TIMER_SECS / 2) / DHCP_COARSE_TIMER_SECS;
1145     if (timeout > 0xffff) {
1146       timeout = 0xffff;
1147     }
1148     dhcp->t1_timeout = (u16_t)timeout;
1149     if (dhcp->t1_timeout == 0) {
1150       dhcp->t1_timeout = 1;
1151     }
1152     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_bind(): set request timeout %"U32_F" msecs\n", dhcp->offered_t1_renew * 1000));
1153     dhcp->t1_renew_time = dhcp->t1_timeout;
1154   }
1155   /* set renewal period timer */
1156   if (dhcp->offered_t2_rebind != 0xffffffffUL) {
1157     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_bind(): t2 rebind timer %"U32_F" secs\n", dhcp->offered_t2_rebind));
1158     timeout = (dhcp->offered_t2_rebind + DHCP_COARSE_TIMER_SECS / 2) / DHCP_COARSE_TIMER_SECS;
1159     if (timeout > 0xffff) {
1160       timeout = 0xffff;
1161     }
1162     dhcp->t2_timeout = (u16_t)timeout;
1163     if (dhcp->t2_timeout == 0) {
1164       dhcp->t2_timeout = 1;
1165     }
1166     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_bind(): set request timeout %"U32_F" msecs\n", dhcp->offered_t2_rebind * 1000));
1167     dhcp->t2_rebind_time = dhcp->t2_timeout;
1168   }
1169 
1170   /* If we have sub 1 minute lease, t2 and t1 will kick in at the same time. */
1171   if ((dhcp->t1_timeout >= dhcp->t2_timeout) && (dhcp->t2_timeout > 0)) {
1172     dhcp->t1_timeout = 0;
1173   }
1174 
1175   if (dhcp->subnet_mask_given) {
1176     /* copy offered network mask */
1177     ip4_addr_copy(sn_mask, dhcp->offered_sn_mask);
1178   } else {
1179     /* subnet mask not given, choose a safe subnet mask given the network class */
1180     u8_t first_octet = ip4_addr1(&dhcp->offered_ip_addr);
1181     if (first_octet <= 127) {
1182       ip4_addr_set_u32(&sn_mask, PP_HTONL(0xff000000UL));
1183     } else if (first_octet >= 192) {
1184       ip4_addr_set_u32(&sn_mask, PP_HTONL(0xffffff00UL));
1185     } else {
1186       ip4_addr_set_u32(&sn_mask, PP_HTONL(0xffff0000UL));
1187     }
1188   }
1189 
1190   ip4_addr_copy(gw_addr, dhcp->offered_gw_addr);
1191 
1192 #if LWIP_DHCP_AUTOIP_COOP
1193   if (dhcp->autoip_coop_state == DHCP_AUTOIP_COOP_STATE_ON) {
1194     autoip_stop(netif);
1195     dhcp->autoip_coop_state = DHCP_AUTOIP_COOP_STATE_OFF;
1196   }
1197 #endif /* LWIP_DHCP_AUTOIP_COOP */
1198 
1199   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",
1200               ip4_addr_get_u32(&dhcp->offered_ip_addr), ip4_addr_get_u32(&sn_mask), ip4_addr_get_u32(&gw_addr)));
1201   /* netif is now bound to DHCP leased address - set this before assigning the address
1202      to ensure the callback can use dhcp_supplied_address() */
1203   dhcp_set_state(dhcp, DHCP_STATE_BOUND);
1204 
1205   netif_set_addr(netif, &dhcp->offered_ip_addr, &sn_mask, &gw_addr);
1206   /* interface is used by routing now that an address is set */
1207 }
1208 
1209 /**
1210  * @ingroup dhcp4
1211  * Renew an existing DHCP lease at the involved DHCP server.
1212  *
1213  * @param netif network interface which must renew its lease
1214  */
1215 err_t
1216 dhcp_renew(struct netif *netif)
1217 {
1218   struct dhcp *dhcp = netif_dhcp_data(netif);
1219   err_t result;
1220   u16_t msecs;
1221   u8_t i;
1222   struct pbuf *p_out;
1223   u16_t options_out_len;
1224 
1225   LWIP_ASSERT_CORE_LOCKED();
1226   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_renew()\n"));
1227   dhcp_set_state(dhcp, DHCP_STATE_RENEWING);
1228 
1229   /* create and initialize the DHCP message header */
1230   p_out = dhcp_create_msg(netif, dhcp, DHCP_REQUEST, &options_out_len);
1231   if (p_out != NULL) {
1232     struct dhcp_msg *msg_out = (struct dhcp_msg *)p_out->payload;
1233     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN);
1234     options_out_len = dhcp_option_short(options_out_len, msg_out->options, DHCP_MAX_MSG_LEN(netif));
1235 
1236     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_PARAMETER_REQUEST_LIST, LWIP_ARRAYSIZE(dhcp_discover_request_options));
1237     for (i = 0; i < LWIP_ARRAYSIZE(dhcp_discover_request_options); i++) {
1238       options_out_len = dhcp_option_byte(options_out_len, msg_out->options, dhcp_discover_request_options[i]);
1239     }
1240 
1241 #if LWIP_NETIF_HOSTNAME
1242     options_out_len = dhcp_option_hostname(options_out_len, msg_out->options, netif);
1243 #endif /* LWIP_NETIF_HOSTNAME */
1244 
1245     LWIP_HOOK_DHCP_APPEND_OPTIONS(netif, dhcp, DHCP_STATE_RENEWING, msg_out, DHCP_REQUEST, &options_out_len);
1246     dhcp_option_trailer(options_out_len, msg_out->options, p_out);
1247 
1248     result = udp_sendto_if(dhcp_pcb, p_out, &dhcp->server_ip_addr, LWIP_IANA_PORT_DHCP_SERVER, netif);
1249     pbuf_free(p_out);
1250 
1251     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_renew: RENEWING\n"));
1252   } else {
1253     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_renew: could not allocate DHCP request\n"));
1254     result = ERR_MEM;
1255   }
1256   if (dhcp->tries < 255) {
1257     dhcp->tries++;
1258   }
1259   /* back-off on retries, but to a maximum of 20 seconds */
1260   msecs = (u16_t)(dhcp->tries < 10 ? dhcp->tries * 2000 : 20 * 1000);
1261   dhcp->request_timeout = (u16_t)((msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS);
1262   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_renew(): set request timeout %"U16_F" msecs\n", msecs));
1263   return result;
1264 }
1265 
1266 /**
1267  * Rebind with a DHCP server for an existing DHCP lease.
1268  *
1269  * @param netif network interface which must rebind with a DHCP server
1270  */
1271 static err_t
1272 dhcp_rebind(struct netif *netif)
1273 {
1274   struct dhcp *dhcp = netif_dhcp_data(netif);
1275   err_t result;
1276   u16_t msecs;
1277   u8_t i;
1278   struct pbuf *p_out;
1279   u16_t options_out_len;
1280 
1281   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_rebind()\n"));
1282   dhcp_set_state(dhcp, DHCP_STATE_REBINDING);
1283 
1284   /* create and initialize the DHCP message header */
1285   p_out = dhcp_create_msg(netif, dhcp, DHCP_REQUEST, &options_out_len);
1286   if (p_out != NULL) {
1287     struct dhcp_msg *msg_out = (struct dhcp_msg *)p_out->payload;
1288     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN);
1289     options_out_len = dhcp_option_short(options_out_len, msg_out->options, DHCP_MAX_MSG_LEN(netif));
1290 
1291     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_PARAMETER_REQUEST_LIST, LWIP_ARRAYSIZE(dhcp_discover_request_options));
1292     for (i = 0; i < LWIP_ARRAYSIZE(dhcp_discover_request_options); i++) {
1293       options_out_len = dhcp_option_byte(options_out_len, msg_out->options, dhcp_discover_request_options[i]);
1294     }
1295 
1296 #if LWIP_NETIF_HOSTNAME
1297     options_out_len = dhcp_option_hostname(options_out_len, msg_out->options, netif);
1298 #endif /* LWIP_NETIF_HOSTNAME */
1299 
1300     LWIP_HOOK_DHCP_APPEND_OPTIONS(netif, dhcp, DHCP_STATE_REBINDING, msg_out, DHCP_DISCOVER, &options_out_len);
1301     dhcp_option_trailer(options_out_len, msg_out->options, p_out);
1302 
1303     /* broadcast to server */
1304     result = udp_sendto_if(dhcp_pcb, p_out, IP_ADDR_BROADCAST, LWIP_IANA_PORT_DHCP_SERVER, netif);
1305     pbuf_free(p_out);
1306     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_rebind: REBINDING\n"));
1307   } else {
1308     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_rebind: could not allocate DHCP request\n"));
1309     result = ERR_MEM;
1310   }
1311   if (dhcp->tries < 255) {
1312     dhcp->tries++;
1313   }
1314   msecs = (u16_t)(dhcp->tries < 10 ? dhcp->tries * 1000 : 10 * 1000);
1315   dhcp->request_timeout = (u16_t)((msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS);
1316   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_rebind(): set request timeout %"U16_F" msecs\n", msecs));
1317   return result;
1318 }
1319 
1320 /**
1321  * Enter REBOOTING state to verify an existing lease
1322  *
1323  * @param netif network interface which must reboot
1324  */
1325 static err_t
1326 dhcp_reboot(struct netif *netif)
1327 {
1328   struct dhcp *dhcp = netif_dhcp_data(netif);
1329   err_t result;
1330   u16_t msecs;
1331   u8_t i;
1332   struct pbuf *p_out;
1333   u16_t options_out_len;
1334 
1335   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_reboot()\n"));
1336   dhcp_set_state(dhcp, DHCP_STATE_REBOOTING);
1337 
1338   /* create and initialize the DHCP message header */
1339   p_out = dhcp_create_msg(netif, dhcp, DHCP_REQUEST, &options_out_len);
1340   if (p_out != NULL) {
1341     struct dhcp_msg *msg_out = (struct dhcp_msg *)p_out->payload;
1342     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN);
1343     options_out_len = dhcp_option_short(options_out_len, msg_out->options, DHCP_MAX_MSG_LEN_MIN_REQUIRED);
1344 
1345     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_REQUESTED_IP, 4);
1346     options_out_len = dhcp_option_long(options_out_len, msg_out->options, lwip_ntohl(ip4_addr_get_u32(&dhcp->offered_ip_addr)));
1347 
1348     options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_PARAMETER_REQUEST_LIST, LWIP_ARRAYSIZE(dhcp_discover_request_options));
1349     for (i = 0; i < LWIP_ARRAYSIZE(dhcp_discover_request_options); i++) {
1350       options_out_len = dhcp_option_byte(options_out_len, msg_out->options, dhcp_discover_request_options[i]);
1351     }
1352 
1353 #if LWIP_NETIF_HOSTNAME
1354     options_out_len = dhcp_option_hostname(options_out_len, msg_out->options, netif);
1355 #endif /* LWIP_NETIF_HOSTNAME */
1356 
1357     LWIP_HOOK_DHCP_APPEND_OPTIONS(netif, dhcp, DHCP_STATE_REBOOTING, msg_out, DHCP_REQUEST, &options_out_len);
1358     dhcp_option_trailer(options_out_len, msg_out->options, p_out);
1359 
1360     /* broadcast to server */
1361     result = udp_sendto_if(dhcp_pcb, p_out, IP_ADDR_BROADCAST, LWIP_IANA_PORT_DHCP_SERVER, netif);
1362     pbuf_free(p_out);
1363     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_reboot: REBOOTING\n"));
1364   } else {
1365     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_reboot: could not allocate DHCP request\n"));
1366     result = ERR_MEM;
1367   }
1368   if (dhcp->tries < 255) {
1369     dhcp->tries++;
1370   }
1371   msecs = (u16_t)(dhcp->tries < 10 ? dhcp->tries * 1000 : 10 * 1000);
1372   dhcp->request_timeout = (u16_t)((msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS);
1373   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_reboot(): set request timeout %"U16_F" msecs\n", msecs));
1374   return result;
1375 }
1376 
1377 /**
1378  * @ingroup dhcp4
1379  * Release a DHCP lease and stop DHCP statemachine (and AUTOIP if LWIP_DHCP_AUTOIP_COOP).
1380  *
1381  * @param netif network interface
1382  */
1383 void
1384 dhcp_release_and_stop(struct netif *netif)
1385 {
1386   struct dhcp *dhcp = netif_dhcp_data(netif);
1387   ip_addr_t server_ip_addr;
1388 
1389   LWIP_ASSERT_CORE_LOCKED();
1390   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_release_and_stop()\n"));
1391   if (dhcp == NULL) {
1392     return;
1393   }
1394 
1395   /* already off? -> nothing to do */
1396   if (dhcp->state == DHCP_STATE_OFF) {
1397     return;
1398   }
1399 
1400   ip_addr_copy(server_ip_addr, dhcp->server_ip_addr);
1401 
1402   /* clean old DHCP offer */
1403   ip_addr_set_zero_ip4(&dhcp->server_ip_addr);
1404   ip4_addr_set_zero(&dhcp->offered_ip_addr);
1405   ip4_addr_set_zero(&dhcp->offered_sn_mask);
1406   ip4_addr_set_zero(&dhcp->offered_gw_addr);
1407 #if LWIP_DHCP_BOOTP_FILE
1408   ip4_addr_set_zero(&dhcp->offered_si_addr);
1409 #endif /* LWIP_DHCP_BOOTP_FILE */
1410   dhcp->offered_t0_lease = dhcp->offered_t1_renew = dhcp->offered_t2_rebind = 0;
1411   dhcp->t1_renew_time = dhcp->t2_rebind_time = dhcp->lease_used = dhcp->t0_timeout = 0;
1412 
1413   /* send release message when current IP was assigned via DHCP */
1414   if (dhcp_supplied_address(netif)) {
1415     /* create and initialize the DHCP message header */
1416     struct pbuf *p_out;
1417     u16_t options_out_len;
1418     dhcp_set_state(dhcp, DHCP_STATE_OFF);
1419     p_out = dhcp_create_msg(netif, dhcp, DHCP_RELEASE, &options_out_len);
1420     if (p_out != NULL) {
1421       struct dhcp_msg *msg_out = (struct dhcp_msg *)p_out->payload;
1422       options_out_len = dhcp_option(options_out_len, msg_out->options, DHCP_OPTION_SERVER_ID, 4);
1423       options_out_len = dhcp_option_long(options_out_len, msg_out->options, lwip_ntohl(ip4_addr_get_u32(ip_2_ip4(&server_ip_addr))));
1424 
1425       LWIP_HOOK_DHCP_APPEND_OPTIONS(netif, dhcp, dhcp->state, msg_out, DHCP_RELEASE, &options_out_len);
1426       dhcp_option_trailer(options_out_len, msg_out->options, p_out);
1427 
1428       udp_sendto_if(dhcp_pcb, p_out, &server_ip_addr, LWIP_IANA_PORT_DHCP_SERVER, netif);
1429       pbuf_free(p_out);
1430       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_release: RELEASED, DHCP_STATE_OFF\n"));
1431     } else {
1432       /* sending release failed, but that's not a problem since the correct behaviour of dhcp does not rely on release */
1433       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_release: could not allocate DHCP request\n"));
1434     }
1435 
1436     /* remove IP address from interface (prevents routing from selecting this interface) */
1437     netif_set_addr(netif, IP4_ADDR_ANY4, IP4_ADDR_ANY4, IP4_ADDR_ANY4);
1438   } else {
1439      dhcp_set_state(dhcp, DHCP_STATE_OFF);
1440   }
1441 
1442 #if LWIP_DHCP_AUTOIP_COOP
1443   if (dhcp->autoip_coop_state == DHCP_AUTOIP_COOP_STATE_ON) {
1444     autoip_stop(netif);
1445     dhcp->autoip_coop_state = DHCP_AUTOIP_COOP_STATE_OFF;
1446   }
1447 #endif /* LWIP_DHCP_AUTOIP_COOP */
1448 
1449   if (dhcp->pcb_allocated != 0) {
1450     dhcp_dec_pcb_refcount(); /* free DHCP PCB if not needed any more */
1451     dhcp->pcb_allocated = 0;
1452   }
1453 }
1454 
1455 /**
1456  * @ingroup dhcp4
1457  * This function calls dhcp_release_and_stop() internally.
1458  * @deprecated Use dhcp_release_and_stop() instead.
1459  */
1460 err_t
1461 dhcp_release(struct netif *netif)
1462 {
1463   dhcp_release_and_stop(netif);
1464   return ERR_OK;
1465 }
1466 
1467 /**
1468  * @ingroup dhcp4
1469  * This function calls dhcp_release_and_stop() internally.
1470  * @deprecated Use dhcp_release_and_stop() instead.
1471  */
1472 void
1473 dhcp_stop(struct netif *netif)
1474 {
1475   dhcp_release_and_stop(netif);
1476 }
1477 
1478 /*
1479  * Set the DHCP state of a DHCP client.
1480  *
1481  * If the state changed, reset the number of tries.
1482  */
1483 static void
1484 dhcp_set_state(struct dhcp *dhcp, u8_t new_state)
1485 {
1486   if (new_state != dhcp->state) {
1487     dhcp->state = new_state;
1488     dhcp->tries = 0;
1489     dhcp->request_timeout = 0;
1490   }
1491 }
1492 
1493 /*
1494  * Concatenate an option type and length field to the outgoing
1495  * DHCP message.
1496  *
1497  */
1498 static u16_t
1499 dhcp_option(u16_t options_out_len, u8_t *options, u8_t option_type, u8_t option_len)
1500 {
1501   LWIP_ASSERT("dhcp_option: options_out_len + 2 + option_len <= DHCP_OPTIONS_LEN", options_out_len + 2U + option_len <= DHCP_OPTIONS_LEN);
1502   options[options_out_len++] = option_type;
1503   options[options_out_len++] = option_len;
1504   return options_out_len;
1505 }
1506 /*
1507  * Concatenate a single byte to the outgoing DHCP message.
1508  *
1509  */
1510 static u16_t
1511 dhcp_option_byte(u16_t options_out_len, u8_t *options, u8_t value)
1512 {
1513   LWIP_ASSERT("dhcp_option_byte: options_out_len < DHCP_OPTIONS_LEN", options_out_len < DHCP_OPTIONS_LEN);
1514   options[options_out_len++] = value;
1515   return options_out_len;
1516 }
1517 
1518 static u16_t
1519 dhcp_option_short(u16_t options_out_len, u8_t *options, u16_t value)
1520 {
1521   LWIP_ASSERT("dhcp_option_short: options_out_len + 2 <= DHCP_OPTIONS_LEN", options_out_len + 2U <= DHCP_OPTIONS_LEN);
1522   options[options_out_len++] = (u8_t)((value & 0xff00U) >> 8);
1523   options[options_out_len++] = (u8_t) (value & 0x00ffU);
1524   return options_out_len;
1525 }
1526 
1527 static u16_t
1528 dhcp_option_long(u16_t options_out_len, u8_t *options, u32_t value)
1529 {
1530   LWIP_ASSERT("dhcp_option_long: options_out_len + 4 <= DHCP_OPTIONS_LEN", options_out_len + 4U <= DHCP_OPTIONS_LEN);
1531   options[options_out_len++] = (u8_t)((value & 0xff000000UL) >> 24);
1532   options[options_out_len++] = (u8_t)((value & 0x00ff0000UL) >> 16);
1533   options[options_out_len++] = (u8_t)((value & 0x0000ff00UL) >> 8);
1534   options[options_out_len++] = (u8_t)((value & 0x000000ffUL));
1535   return options_out_len;
1536 }
1537 
1538 #if LWIP_NETIF_HOSTNAME
1539 static u16_t
1540 dhcp_option_hostname(u16_t options_out_len, u8_t *options, struct netif *netif)
1541 {
1542   if (netif->hostname != NULL) {
1543     size_t namelen = strlen(netif->hostname);
1544     if (namelen > 0) {
1545       size_t len;
1546       const char *p = netif->hostname;
1547       /* Shrink len to available bytes (need 2 bytes for OPTION_HOSTNAME
1548          and 1 byte for trailer) */
1549       size_t available = DHCP_OPTIONS_LEN - options_out_len - 3;
1550       LWIP_ASSERT("DHCP: hostname is too long!", namelen <= available);
1551       len = LWIP_MIN(namelen, available);
1552       LWIP_ASSERT("DHCP: hostname is too long!", len <= 0xFF);
1553       options_out_len = dhcp_option(options_out_len, options, DHCP_OPTION_HOSTNAME, (u8_t)len);
1554       while (len--) {
1555         options_out_len = dhcp_option_byte(options_out_len, options, *p++);
1556       }
1557     }
1558   }
1559   return options_out_len;
1560 }
1561 #endif /* LWIP_NETIF_HOSTNAME */
1562 
1563 /**
1564  * Extract the DHCP message and the DHCP options.
1565  *
1566  * Extract the DHCP message and the DHCP options, each into a contiguous
1567  * piece of memory. As a DHCP message is variable sized by its options,
1568  * and also allows overriding some fields for options, the easy approach
1569  * is to first unfold the options into a contiguous piece of memory, and
1570  * use that further on.
1571  *
1572  */
1573 static err_t
1574 dhcp_parse_reply(struct pbuf *p, struct dhcp *dhcp)
1575 {
1576   u8_t *options;
1577   u16_t offset;
1578   u16_t offset_max;
1579   u16_t options_offset;
1580   u16_t options_idx;
1581   u16_t options_idx_max;
1582   struct pbuf *q;
1583   int parse_file_as_options = 0;
1584   int parse_sname_as_options = 0;
1585   struct dhcp_msg *msg_in;
1586 #if LWIP_DHCP_BOOTP_FILE
1587   int file_overloaded = 0;
1588 #endif
1589 
1590   LWIP_UNUSED_ARG(dhcp);
1591 
1592   /* clear received options */
1593   dhcp_clear_all_options(dhcp);
1594   /* check that beginning of dhcp_msg (up to and including chaddr) is in first pbuf */
1595   if (p->len < DHCP_SNAME_OFS) {
1596     return ERR_BUF;
1597   }
1598   msg_in = (struct dhcp_msg *)p->payload;
1599 #if LWIP_DHCP_BOOTP_FILE
1600   /* clear boot file name */
1601   dhcp->boot_file_name[0] = 0;
1602 #endif /* LWIP_DHCP_BOOTP_FILE */
1603 
1604   /* parse options */
1605 
1606   /* start with options field */
1607   options_idx = DHCP_OPTIONS_OFS;
1608   /* parse options to the end of the received packet */
1609   options_idx_max = p->tot_len;
1610 again:
1611   q = p;
1612   options_offset = options_idx;
1613   while ((q != NULL) && (options_idx >= q->len)) {
1614     options_idx = (u16_t)(options_idx - q->len);
1615     options_idx_max = (u16_t)(options_idx_max - q->len);
1616     q = q->next;
1617   }
1618   if (q == NULL) {
1619     return ERR_BUF;
1620   }
1621   offset = options_idx;
1622   offset_max = options_idx_max;
1623   options = (u8_t *)q->payload;
1624   /* at least 1 byte to read and no end marker, then at least 3 bytes to read? */
1625   while ((q != NULL) && (offset < offset_max) && (options[offset] != DHCP_OPTION_END)) {
1626     u8_t op = options[offset];
1627     u8_t len;
1628     u8_t decode_len = 0;
1629     int decode_idx = -1;
1630     u16_t val_offset = (u16_t)(offset + 2);
1631     if (val_offset < offset) {
1632       /* overflow */
1633       return ERR_BUF;
1634     }
1635     /* len byte might be in the next pbuf */
1636     if ((offset + 1) < q->len) {
1637       len = options[offset + 1];
1638     } else {
1639       len = (q->next != NULL ? ((u8_t *)q->next->payload)[0] : 0);
1640     }
1641     /* LWIP_DEBUGF(DHCP_DEBUG, ("msg_offset=%"U16_F", q->len=%"U16_F, msg_offset, q->len)); */
1642     decode_len = len;
1643     switch (op) {
1644       /* case(DHCP_OPTION_END): handled above */
1645       case (DHCP_OPTION_PAD):
1646         /* special option: no len encoded */
1647         decode_len = len = 0;
1648         /* will be increased below */
1649         break;
1650       case (DHCP_OPTION_SUBNET_MASK):
1651         LWIP_DHCP_INPUT_ERROR("len == 4", len == 4, return ERR_VAL;);
1652         decode_idx = DHCP_OPTION_IDX_SUBNET_MASK;
1653         break;
1654       case (DHCP_OPTION_ROUTER):
1655         decode_len = 4; /* only copy the first given router */
1656         LWIP_DHCP_INPUT_ERROR("len >= decode_len", len >= decode_len, return ERR_VAL;);
1657         decode_idx = DHCP_OPTION_IDX_ROUTER;
1658         break;
1659 #if LWIP_DHCP_PROVIDE_DNS_SERVERS
1660       case (DHCP_OPTION_DNS_SERVER):
1661         /* special case: there might be more than one server */
1662         LWIP_DHCP_INPUT_ERROR("len %% 4 == 0", len % 4 == 0, return ERR_VAL;);
1663         /* limit number of DNS servers */
1664         decode_len = LWIP_MIN(len, 4 * DNS_MAX_SERVERS);
1665         LWIP_DHCP_INPUT_ERROR("len >= decode_len", len >= decode_len, return ERR_VAL;);
1666         decode_idx = DHCP_OPTION_IDX_DNS_SERVER;
1667         break;
1668 #endif /* LWIP_DHCP_PROVIDE_DNS_SERVERS */
1669       case (DHCP_OPTION_LEASE_TIME):
1670         LWIP_DHCP_INPUT_ERROR("len == 4", len == 4, return ERR_VAL;);
1671         decode_idx = DHCP_OPTION_IDX_LEASE_TIME;
1672         break;
1673 #if LWIP_DHCP_GET_NTP_SRV
1674       case (DHCP_OPTION_NTP):
1675         /* special case: there might be more than one server */
1676         LWIP_DHCP_INPUT_ERROR("len %% 4 == 0", len % 4 == 0, return ERR_VAL;);
1677         /* limit number of NTP servers */
1678         decode_len = LWIP_MIN(len, 4 * LWIP_DHCP_MAX_NTP_SERVERS);
1679         LWIP_DHCP_INPUT_ERROR("len >= decode_len", len >= decode_len, return ERR_VAL;);
1680         decode_idx = DHCP_OPTION_IDX_NTP_SERVER;
1681         break;
1682 #endif /* LWIP_DHCP_GET_NTP_SRV*/
1683       case (DHCP_OPTION_OVERLOAD):
1684         LWIP_DHCP_INPUT_ERROR("len == 1", len == 1, return ERR_VAL;);
1685         /* decode overload only in options, not in file/sname: invalid packet */
1686         LWIP_DHCP_INPUT_ERROR("overload in file/sname", options_offset == DHCP_OPTIONS_OFS, return ERR_VAL;);
1687         decode_idx = DHCP_OPTION_IDX_OVERLOAD;
1688         break;
1689       case (DHCP_OPTION_MESSAGE_TYPE):
1690         LWIP_DHCP_INPUT_ERROR("len == 1", len == 1, return ERR_VAL;);
1691         decode_idx = DHCP_OPTION_IDX_MSG_TYPE;
1692         break;
1693       case (DHCP_OPTION_SERVER_ID):
1694         LWIP_DHCP_INPUT_ERROR("len == 4", len == 4, return ERR_VAL;);
1695         decode_idx = DHCP_OPTION_IDX_SERVER_ID;
1696         break;
1697       case (DHCP_OPTION_T1):
1698         LWIP_DHCP_INPUT_ERROR("len == 4", len == 4, return ERR_VAL;);
1699         decode_idx = DHCP_OPTION_IDX_T1;
1700         break;
1701       case (DHCP_OPTION_T2):
1702         LWIP_DHCP_INPUT_ERROR("len == 4", len == 4, return ERR_VAL;);
1703         decode_idx = DHCP_OPTION_IDX_T2;
1704         break;
1705       default:
1706         decode_len = 0;
1707         LWIP_DEBUGF(DHCP_DEBUG, ("skipping option %"U16_F" in options\n", (u16_t)op));
1708         LWIP_HOOK_DHCP_PARSE_OPTION(ip_current_netif(), dhcp, dhcp->state, msg_in,
1709                                     dhcp_option_given(dhcp, DHCP_OPTION_IDX_MSG_TYPE) ? (u8_t)dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_MSG_TYPE) : 0,
1710                                     op, len, q, val_offset);
1711         break;
1712     }
1713     if (op == DHCP_OPTION_PAD) {
1714       offset++;
1715     } else {
1716       if (offset + len + 2 > 0xFFFF) {
1717         /* overflow */
1718         return ERR_BUF;
1719       }
1720       offset = (u16_t)(offset + len + 2);
1721       if (decode_len > 0) {
1722         u32_t value = 0;
1723         u16_t copy_len;
1724 decode_next:
1725         LWIP_ASSERT("check decode_idx", decode_idx >= 0 && decode_idx < DHCP_OPTION_IDX_MAX);
1726         if (!dhcp_option_given(dhcp, decode_idx)) {
1727           copy_len = LWIP_MIN(decode_len, 4);
1728           if (pbuf_copy_partial(q, &value, copy_len, val_offset) != copy_len) {
1729             return ERR_BUF;
1730           }
1731           if (decode_len > 4) {
1732             /* decode more than one u32_t */
1733             u16_t next_val_offset;
1734             LWIP_DHCP_INPUT_ERROR("decode_len %% 4 == 0", decode_len % 4 == 0, return ERR_VAL;);
1735             dhcp_got_option(dhcp, decode_idx);
1736             dhcp_set_option_value(dhcp, decode_idx, lwip_htonl(value));
1737             decode_len = (u8_t)(decode_len - 4);
1738             next_val_offset = (u16_t)(val_offset + 4);
1739             if (next_val_offset < val_offset) {
1740               /* overflow */
1741               return ERR_BUF;
1742             }
1743             val_offset = next_val_offset;
1744             decode_idx++;
1745             goto decode_next;
1746           } else if (decode_len == 4) {
1747             value = lwip_ntohl(value);
1748           } else {
1749             LWIP_DHCP_INPUT_ERROR("invalid decode_len", decode_len == 1, return ERR_VAL;);
1750             value = ((u8_t *)&value)[0];
1751           }
1752           dhcp_got_option(dhcp, decode_idx);
1753           dhcp_set_option_value(dhcp, decode_idx, value);
1754         }
1755       }
1756     }
1757     if (offset >= q->len) {
1758       offset = (u16_t)(offset - q->len);
1759       offset_max = (u16_t)(offset_max - q->len);
1760       if (offset < offset_max) {
1761         q = q->next;
1762         LWIP_DHCP_INPUT_ERROR("next pbuf was null", q != NULL, return ERR_VAL;);
1763         options = (u8_t *)q->payload;
1764       } else {
1765         /* We've run out of bytes, probably no end marker. Don't proceed. */
1766         return ERR_BUF;
1767       }
1768     }
1769   }
1770   /* is this an overloaded message? */
1771   if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_OVERLOAD)) {
1772     u32_t overload = dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_OVERLOAD);
1773     dhcp_clear_option(dhcp, DHCP_OPTION_IDX_OVERLOAD);
1774     if (overload == DHCP_OVERLOAD_FILE) {
1775       parse_file_as_options = 1;
1776       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("overloaded file field\n"));
1777     } else if (overload == DHCP_OVERLOAD_SNAME) {
1778       parse_sname_as_options = 1;
1779       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("overloaded sname field\n"));
1780     } else if (overload == DHCP_OVERLOAD_SNAME_FILE) {
1781       parse_sname_as_options = 1;
1782       parse_file_as_options = 1;
1783       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("overloaded sname and file field\n"));
1784     } else {
1785       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("invalid overload option: %d\n", (int)overload));
1786     }
1787   }
1788   if (parse_file_as_options) {
1789     /* if both are overloaded, parse file first and then sname (RFC 2131 ch. 4.1) */
1790     parse_file_as_options = 0;
1791     options_idx = DHCP_FILE_OFS;
1792     options_idx_max = DHCP_FILE_OFS + DHCP_FILE_LEN;
1793 #if LWIP_DHCP_BOOTP_FILE
1794     file_overloaded = 1;
1795 #endif
1796     goto again;
1797   } else if (parse_sname_as_options) {
1798     parse_sname_as_options = 0;
1799     options_idx = DHCP_SNAME_OFS;
1800     options_idx_max = DHCP_SNAME_OFS + DHCP_SNAME_LEN;
1801     goto again;
1802   }
1803 #if LWIP_DHCP_BOOTP_FILE
1804   if (!file_overloaded) {
1805     /* only do this for ACK messages */
1806     if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_MSG_TYPE) &&
1807       (dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_MSG_TYPE) == DHCP_ACK))
1808     /* copy bootp file name, don't care for sname (server hostname) */
1809     if (pbuf_copy_partial(p, dhcp->boot_file_name, DHCP_FILE_LEN-1, DHCP_FILE_OFS) != (DHCP_FILE_LEN-1)) {
1810       return ERR_BUF;
1811     }
1812     /* make sure the string is really NULL-terminated */
1813     dhcp->boot_file_name[DHCP_FILE_LEN-1] = 0;
1814   }
1815 #endif /* LWIP_DHCP_BOOTP_FILE */
1816   return ERR_OK;
1817 }
1818 
1819 /**
1820  * If an incoming DHCP message is in response to us, then trigger the state machine
1821  */
1822 static void
1823 dhcp_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
1824 {
1825   struct netif *netif = ip_current_input_netif();
1826   struct dhcp *dhcp = netif_dhcp_data(netif);
1827   struct dhcp_msg *reply_msg = (struct dhcp_msg *)p->payload;
1828   u8_t msg_type;
1829   u8_t i;
1830   struct dhcp_msg *msg_in;
1831 
1832   LWIP_UNUSED_ARG(arg);
1833 
1834   /* Caught DHCP message from netif that does not have DHCP enabled? -> not interested */
1835   if ((dhcp == NULL) || (dhcp->pcb_allocated == 0)) {
1836     goto free_pbuf_and_return;
1837   }
1838 
1839   LWIP_ASSERT("invalid server address type", IP_IS_V4(addr));
1840 
1841   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,
1842               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));
1843   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("pbuf->len = %"U16_F"\n", p->len));
1844   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("pbuf->tot_len = %"U16_F"\n", p->tot_len));
1845   /* prevent warnings about unused arguments */
1846   LWIP_UNUSED_ARG(pcb);
1847   LWIP_UNUSED_ARG(addr);
1848   LWIP_UNUSED_ARG(port);
1849 
1850   if (p->len < DHCP_MIN_REPLY_LEN) {
1851     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("DHCP reply message or pbuf too short\n"));
1852     goto free_pbuf_and_return;
1853   }
1854 
1855   if (reply_msg->op != DHCP_BOOTREPLY) {
1856     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));
1857     goto free_pbuf_and_return;
1858   }
1859   /* iterate through hardware address and match against DHCP message */
1860   for (i = 0; i < netif->hwaddr_len && i < LWIP_MIN(DHCP_CHADDR_LEN, NETIF_MAX_HWADDR_LEN); i++) {
1861     if (netif->hwaddr[i] != reply_msg->chaddr[i]) {
1862       LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING,
1863                   ("netif->hwaddr[%"U16_F"]==%02"X16_F" != reply_msg->chaddr[%"U16_F"]==%02"X16_F"\n",
1864                    (u16_t)i, (u16_t)netif->hwaddr[i], (u16_t)i, (u16_t)reply_msg->chaddr[i]));
1865       goto free_pbuf_and_return;
1866     }
1867   }
1868   /* match transaction ID against what we expected */
1869   if (lwip_ntohl(reply_msg->xid) != dhcp->xid) {
1870     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING,
1871                 ("transaction id mismatch reply_msg->xid(%"X32_F")!=dhcp->xid(%"X32_F")\n", lwip_ntohl(reply_msg->xid), dhcp->xid));
1872     goto free_pbuf_and_return;
1873   }
1874   /* option fields could be unfold? */
1875   if (dhcp_parse_reply(p, dhcp) != ERR_OK) {
1876     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS,
1877                 ("problem unfolding DHCP message - too short on memory?\n"));
1878     goto free_pbuf_and_return;
1879   }
1880 
1881   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("searching DHCP_OPTION_MESSAGE_TYPE\n"));
1882   /* obtain pointer to DHCP message type */
1883   if (!dhcp_option_given(dhcp, DHCP_OPTION_IDX_MSG_TYPE)) {
1884     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("DHCP_OPTION_MESSAGE_TYPE option not found\n"));
1885     goto free_pbuf_and_return;
1886   }
1887 
1888   msg_in = (struct dhcp_msg *)p->payload;
1889   /* read DHCP message type */
1890   msg_type = (u8_t)dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_MSG_TYPE);
1891   /* message type is DHCP ACK? */
1892   if (msg_type == DHCP_ACK) {
1893     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("DHCP_ACK received\n"));
1894     /* in requesting state? */
1895     if (dhcp->state == DHCP_STATE_REQUESTING) {
1896       dhcp_handle_ack(netif, msg_in);
1897 #if DHCP_DOES_ARP_CHECK
1898       if ((netif->flags & NETIF_FLAG_ETHARP) != 0) {
1899         /* check if the acknowledged lease address is already in use */
1900         dhcp_check(netif);
1901       } else {
1902         /* bind interface to the acknowledged lease address */
1903         dhcp_bind(netif);
1904       }
1905 #else
1906       /* bind interface to the acknowledged lease address */
1907       dhcp_bind(netif);
1908 #endif
1909     }
1910     /* already bound to the given lease address? */
1911     else if ((dhcp->state == DHCP_STATE_REBOOTING) || (dhcp->state == DHCP_STATE_REBINDING) ||
1912              (dhcp->state == DHCP_STATE_RENEWING)) {
1913       dhcp_handle_ack(netif, msg_in);
1914       dhcp_bind(netif);
1915     }
1916   }
1917   /* received a DHCP_NAK in appropriate state? */
1918   else if ((msg_type == DHCP_NAK) &&
1919            ((dhcp->state == DHCP_STATE_REBOOTING) || (dhcp->state == DHCP_STATE_REQUESTING) ||
1920             (dhcp->state == DHCP_STATE_REBINDING) || (dhcp->state == DHCP_STATE_RENEWING  ))) {
1921     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("DHCP_NAK received\n"));
1922     dhcp_handle_nak(netif);
1923   }
1924   /* received a DHCP_OFFER in DHCP_STATE_SELECTING state? */
1925   else if ((msg_type == DHCP_OFFER) && (dhcp->state == DHCP_STATE_SELECTING)) {
1926     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("DHCP_OFFER received in DHCP_STATE_SELECTING state\n"));
1927     /* remember offered lease */
1928     dhcp_handle_offer(netif, msg_in);
1929   }
1930 
1931 free_pbuf_and_return:
1932   pbuf_free(p);
1933 }
1934 
1935 /**
1936  * Create a DHCP request, fill in common headers
1937  *
1938  * @param netif the netif under DHCP control
1939  * @param dhcp dhcp control struct
1940  * @param message_type message type of the request
1941  */
1942 static struct pbuf *
1943 dhcp_create_msg(struct netif *netif, struct dhcp *dhcp, u8_t message_type, u16_t *options_out_len)
1944 {
1945   u16_t i;
1946   struct pbuf *p_out;
1947   struct dhcp_msg *msg_out;
1948   u16_t options_out_len_loc;
1949 
1950 #ifndef DHCP_GLOBAL_XID
1951   /** default global transaction identifier starting value (easy to match
1952    *  with a packet analyser). We simply increment for each new request.
1953    *  Predefine DHCP_GLOBAL_XID to a better value or a function call to generate one
1954    *  at runtime, any supporting function prototypes can be defined in DHCP_GLOBAL_XID_HEADER */
1955 #if DHCP_CREATE_RAND_XID && defined(LWIP_RAND)
1956   static u32_t xid;
1957 #else /* DHCP_CREATE_RAND_XID && defined(LWIP_RAND) */
1958   static u32_t xid = 0xABCD0000;
1959 #endif /* DHCP_CREATE_RAND_XID && defined(LWIP_RAND) */
1960 #else
1961   if (!xid_initialised) {
1962     xid = DHCP_GLOBAL_XID;
1963     xid_initialised = !xid_initialised;
1964   }
1965 #endif
1966   LWIP_ERROR("dhcp_create_msg: netif != NULL", (netif != NULL), return NULL;);
1967   LWIP_ERROR("dhcp_create_msg: dhcp != NULL", (dhcp != NULL), return NULL;);
1968   p_out = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct dhcp_msg), PBUF_RAM);
1969   if (p_out == NULL) {
1970     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS,
1971                 ("dhcp_create_msg(): could not allocate pbuf\n"));
1972     return NULL;
1973   }
1974   LWIP_ASSERT("dhcp_create_msg: check that first pbuf can hold struct dhcp_msg",
1975               (p_out->len >= sizeof(struct dhcp_msg)));
1976 
1977   /* DHCP_REQUEST should reuse 'xid' from DHCPOFFER */
1978   if ((message_type != DHCP_REQUEST) || (dhcp->state == DHCP_STATE_REBOOTING)) {
1979     /* reuse transaction identifier in retransmissions */
1980     if (dhcp->tries == 0) {
1981 #if DHCP_CREATE_RAND_XID && defined(LWIP_RAND)
1982       xid = LWIP_RAND();
1983 #else /* DHCP_CREATE_RAND_XID && defined(LWIP_RAND) */
1984       xid++;
1985 #endif /* DHCP_CREATE_RAND_XID && defined(LWIP_RAND) */
1986     }
1987     dhcp->xid = xid;
1988   }
1989   LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE,
1990               ("transaction id xid(%"X32_F")\n", xid));
1991 
1992   msg_out = (struct dhcp_msg *)p_out->payload;
1993   memset(msg_out, 0, sizeof(struct dhcp_msg));
1994 
1995   msg_out->op = DHCP_BOOTREQUEST;
1996   /* @todo: make link layer independent */
1997   msg_out->htype = LWIP_IANA_HWTYPE_ETHERNET;
1998   msg_out->hlen = netif->hwaddr_len;
1999   msg_out->xid = lwip_htonl(dhcp->xid);
2000   /* we don't need the broadcast flag since we can receive unicast traffic
2001      before being fully configured! */
2002   /* set ciaddr to netif->ip_addr based on message_type and state */
2003   if ((message_type == DHCP_INFORM) || (message_type == DHCP_DECLINE) || (message_type == DHCP_RELEASE) ||
2004       ((message_type == DHCP_REQUEST) && /* DHCP_STATE_BOUND not used for sending! */
2005        ((dhcp->state == DHCP_STATE_RENEWING) || dhcp->state == DHCP_STATE_REBINDING))) {
2006     ip4_addr_copy(msg_out->ciaddr, *netif_ip4_addr(netif));
2007   }
2008   for (i = 0; i < LWIP_MIN(DHCP_CHADDR_LEN, NETIF_MAX_HWADDR_LEN); i++) {
2009     /* copy netif hardware address (padded with zeroes through memset already) */
2010     msg_out->chaddr[i] = netif->hwaddr[i];
2011   }
2012   msg_out->cookie = PP_HTONL(DHCP_MAGIC_COOKIE);
2013   /* Add option MESSAGE_TYPE */
2014   options_out_len_loc = dhcp_option(0, msg_out->options, DHCP_OPTION_MESSAGE_TYPE, DHCP_OPTION_MESSAGE_TYPE_LEN);
2015   options_out_len_loc = dhcp_option_byte(options_out_len_loc, msg_out->options, message_type);
2016   if (options_out_len) {
2017     *options_out_len = options_out_len_loc;
2018   }
2019   return p_out;
2020 }
2021 
2022 /**
2023  * Add a DHCP message trailer
2024  *
2025  * Adds the END option to the DHCP message, and if
2026  * necessary, up to three padding bytes.
2027  */
2028 static void
2029 dhcp_option_trailer(u16_t options_out_len, u8_t *options, struct pbuf *p_out)
2030 {
2031   options[options_out_len++] = DHCP_OPTION_END;
2032   /* packet is too small, or not 4 byte aligned? */
2033   while (((options_out_len < DHCP_MIN_OPTIONS_LEN) || (options_out_len & 3)) &&
2034          (options_out_len < DHCP_OPTIONS_LEN)) {
2035     /* add a fill/padding byte */
2036     options[options_out_len++] = 0;
2037   }
2038   /* shrink the pbuf to the actual content length */
2039   pbuf_realloc(p_out, (u16_t)(sizeof(struct dhcp_msg) - DHCP_OPTIONS_LEN + options_out_len));
2040 }
2041 
2042 /** check if DHCP supplied netif->ip_addr
2043  *
2044  * @param netif the netif to check
2045  * @return 1 if DHCP supplied netif->ip_addr (states BOUND or RENEWING),
2046  *         0 otherwise
2047  */
2048 u8_t
2049 dhcp_supplied_address(const struct netif *netif)
2050 {
2051   if ((netif != NULL) && (netif_dhcp_data(netif) != NULL)) {
2052     struct dhcp *dhcp = netif_dhcp_data(netif);
2053     return (dhcp->state == DHCP_STATE_BOUND) || (dhcp->state == DHCP_STATE_RENEWING) ||
2054            (dhcp->state == DHCP_STATE_REBINDING);
2055   }
2056   return 0;
2057 }
2058 
2059 #endif /* LWIP_IPV4 && LWIP_DHCP */
2060