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