1 /* SPDX-License-Identifier: GPL-2.0-only */
2 /*
3  *	Based on LiMon - BOOTP.
4  *
5  *	Copyright 1994, 1995, 2000 Neil Russell.
6  *	Copyright 2000 Roland Borde
7  *	Copyright 2000 Paolo Scaffardi
8  *	Copyright 2000-2004 Wolfgang Denk, wd@denx.de
9  */
10 
11 #include <bootstage.h>
12 #include <command.h>
13 #include <env.h>
14 #include <efi_loader.h>
15 #include <log.h>
16 #include <net.h>
17 #include <rand.h>
18 #include <u-boot/uuid.h>
19 #include <linux/delay.h>
20 #include <net/tftp.h>
21 #include "bootp.h"
22 #ifdef CONFIG_LED_STATUS
23 #include <status_led.h>
24 #endif
25 #ifdef CONFIG_BOOTP_RANDOM_DELAY
26 #include "net_rand.h"
27 #endif
28 #include <malloc.h>
29 
30 #define BOOTP_VENDOR_MAGIC	0x63825363	/* RFC1048 Magic Cookie */
31 
32 /*
33  * The timeout for the initial BOOTP/DHCP request used to be described by a
34  * counter of fixed-length timeout periods. CONFIG_NET_RETRY_COUNT represents
35  * that counter
36  *
37  * Now that the timeout periods are variable (exponential backoff and retry)
38  * we convert the timeout count to the absolute time it would have take to
39  * execute that many retries, and keep sending retry packets until that time
40  * is reached.
41  */
42 #define TIMEOUT_MS	((3 + (CONFIG_NET_RETRY_COUNT * 5)) * 1000)
43 
44 /*
45  * According to rfc951 : 7.2. Client Retransmission Strategy
46  * "After the 'average' backoff reaches about 60 seconds, it should be
47  * increased no further, but still randomized."
48  *
49  * U-Boot has saturated this backoff at 2 seconds for a long time.
50  * To modify, set the environment variable "bootpretransmitperiodmax"
51  */
52 #define RETRANSMIT_PERIOD_MAX_MS	60000
53 
54 /* Retransmission timeout for the initial packet (in milliseconds).
55  * This timeout will double on each retry.  To modify, set the
56  * environment variable bootpretransmitperiodinit.
57  */
58 #define RETRANSMIT_PERIOD_INIT_MS	250
59 
60 #ifndef CFG_DHCP_MIN_EXT_LEN		/* minimal length of extension list */
61 #define CFG_DHCP_MIN_EXT_LEN 64
62 #endif
63 
64 #ifndef CFG_BOOTP_ID_CACHE_SIZE
65 #define CFG_BOOTP_ID_CACHE_SIZE 4
66 #endif
67 
68 u32		bootp_ids[CFG_BOOTP_ID_CACHE_SIZE];
69 unsigned int	bootp_num_ids;
70 int		bootp_try;
71 u32		bootp_id;
72 ulong		bootp_start;
73 ulong		bootp_timeout;
74 char net_nis_domain[32] = {0,}; /* Our NIS domain */
75 char net_hostname[32] = {0,}; /* Our hostname */
76 char net_root_path[CONFIG_BOOTP_MAX_ROOT_PATH_LEN] = {0,}; /* Our bootpath */
77 
78 static ulong time_taken_max;
79 static u32   retransmit_period_max_ms;
80 
81 #if defined(CONFIG_CMD_DHCP)
82 static dhcp_state_t dhcp_state = INIT;
83 static u32 dhcp_leasetime;
84 static struct in_addr dhcp_server_ip;
85 static u8 dhcp_option_overload;
86 #define OVERLOAD_FILE 1
87 #define OVERLOAD_SNAME 2
88 static void dhcp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
89 			unsigned src, unsigned len);
90 
91 /* For Debug */
92 #if 0
93 static char *dhcpmsg2str(int type)
94 {
95 	switch (type) {
96 	case 1:	 return "DHCPDISCOVER"; break;
97 	case 2:	 return "DHCPOFFER";	break;
98 	case 3:	 return "DHCPREQUEST";	break;
99 	case 4:	 return "DHCPDECLINE";	break;
100 	case 5:	 return "DHCPACK";	break;
101 	case 6:	 return "DHCPNACK";	break;
102 	case 7:	 return "DHCPRELEASE";	break;
103 	default: return "UNKNOWN/INVALID MSG TYPE"; break;
104 	}
105 }
106 #endif
107 #endif
108 
bootp_add_id(ulong id)109 static void bootp_add_id(ulong id)
110 {
111 	if (bootp_num_ids >= ARRAY_SIZE(bootp_ids)) {
112 		size_t size = sizeof(bootp_ids) - sizeof(id);
113 
114 		memmove(bootp_ids, &bootp_ids[1], size);
115 		bootp_ids[bootp_num_ids - 1] = id;
116 	} else {
117 		bootp_ids[bootp_num_ids] = id;
118 		bootp_num_ids++;
119 	}
120 }
121 
bootp_match_id(ulong id)122 static bool bootp_match_id(ulong id)
123 {
124 	unsigned int i;
125 
126 	for (i = 0; i < bootp_num_ids; i++)
127 		if (bootp_ids[i] == id)
128 			return true;
129 
130 	return false;
131 }
132 
check_reply_packet(uchar * pkt,unsigned dest,unsigned src,unsigned len)133 static int check_reply_packet(uchar *pkt, unsigned dest, unsigned src,
134 			      unsigned len)
135 {
136 	struct bootp_hdr *bp = (struct bootp_hdr *)pkt;
137 	int retval = 0;
138 
139 	if (dest != PORT_BOOTPC || src != PORT_BOOTPS)
140 		retval = -1;
141 	else if (len < sizeof(struct bootp_hdr) - OPT_FIELD_SIZE)
142 		retval = -2;
143 	else if (bp->bp_op != OP_BOOTREPLY)
144 		retval = -3;
145 	else if (bp->bp_htype != HWT_ETHER)
146 		retval = -4;
147 	else if (bp->bp_hlen != HWL_ETHER)
148 		retval = -5;
149 	else if (!bootp_match_id(net_read_u32(&bp->bp_id)))
150 		retval = -6;
151 	else if (memcmp(bp->bp_chaddr, net_ethaddr, HWL_ETHER) != 0)
152 		retval = -7;
153 
154 	debug("Filtering pkt = %d\n", retval);
155 
156 	return retval;
157 }
158 
store_bootp_params(struct bootp_hdr * bp)159 static void store_bootp_params(struct bootp_hdr *bp)
160 {
161 	struct in_addr tmp_ip;
162 	bool overwrite_serverip = true;
163 
164 	if (IS_ENABLED(CONFIG_BOOTP_SERVERIP))
165 		return;
166 
167 #if defined(CONFIG_BOOTP_PREFER_SERVERIP)
168 	overwrite_serverip = false;
169 #endif
170 
171 	net_copy_ip(&tmp_ip, &bp->bp_siaddr);
172 	if (tmp_ip.s_addr != 0 && (overwrite_serverip || !net_server_ip.s_addr))
173 		net_copy_ip(&net_server_ip, &bp->bp_siaddr);
174 	memcpy(net_server_ethaddr,
175 	       ((struct ethernet_hdr *)net_rx_packet)->et_src, 6);
176 	if (
177 #if defined(CONFIG_CMD_DHCP)
178 	    !(dhcp_option_overload & OVERLOAD_FILE) &&
179 #endif
180 	    (strlen(bp->bp_file) > 0) &&
181 	    !net_boot_file_name_explicit) {
182 		copy_filename(net_boot_file_name, bp->bp_file,
183 			      sizeof(net_boot_file_name));
184 	}
185 
186 	debug("net_boot_file_name: %s\n", net_boot_file_name);
187 
188 	/* Propagate to environment:
189 	 * don't delete exising entry when BOOTP / DHCP reply does
190 	 * not contain a new value
191 	 */
192 	if (*net_boot_file_name)
193 		env_set("bootfile", net_boot_file_name);
194 }
195 
196 /*
197  * Copy parameters of interest from BOOTP_REPLY/DHCP_OFFER packet
198  */
store_net_params(struct bootp_hdr * bp)199 static void store_net_params(struct bootp_hdr *bp)
200 {
201 #if !defined(CONFIG_SERVERIP_FROM_PROXYDHCP)
202 	store_bootp_params(bp);
203 #endif
204 	net_copy_ip(&net_ip, &bp->bp_yiaddr);
205 }
206 
truncate_sz(const char * name,int maxlen,int curlen)207 static int truncate_sz(const char *name, int maxlen, int curlen)
208 {
209 	if (curlen >= maxlen) {
210 		printf("*** WARNING: %s is too long (%d - max: %d)"
211 			" - truncated\n", name, curlen, maxlen);
212 		curlen = maxlen - 1;
213 	}
214 	return curlen;
215 }
216 
217 #if !defined(CONFIG_CMD_DHCP)
218 
bootp_process_vendor_field(u8 * ext)219 static void bootp_process_vendor_field(u8 *ext)
220 {
221 	int size = *(ext + 1);
222 
223 	debug("[BOOTP] Processing extension %d... (%d bytes)\n", *ext,
224 	      *(ext + 1));
225 
226 	net_boot_file_expected_size_in_blocks = 0;
227 
228 	switch (*ext) {
229 		/* Fixed length fields */
230 	case 1:			/* Subnet mask */
231 		if (net_netmask.s_addr == 0)
232 			net_copy_ip(&net_netmask, (struct in_addr *)(ext + 2));
233 		break;
234 	case 2:			/* Time offset - Not yet supported */
235 		break;
236 		/* Variable length fields */
237 	case 3:			/* Gateways list */
238 		if (net_gateway.s_addr == 0)
239 			net_copy_ip(&net_gateway, (struct in_addr *)(ext + 2));
240 		break;
241 	case 4:			/* Time server - Not yet supported */
242 		break;
243 	case 5:			/* IEN-116 name server - Not yet supported */
244 		break;
245 	case 6:
246 		if (net_dns_server.s_addr == 0)
247 			net_copy_ip(&net_dns_server,
248 				    (struct in_addr *)(ext + 2));
249 #if defined(CONFIG_BOOTP_DNS2)
250 		if ((net_dns_server2.s_addr == 0) && (size > 4))
251 			net_copy_ip(&net_dns_server2,
252 				    (struct in_addr *)(ext + 2 + 4));
253 #endif
254 		break;
255 	case 7:			/* Log server - Not yet supported */
256 		break;
257 	case 8:			/* Cookie/Quote server - Not yet supported */
258 		break;
259 	case 9:			/* LPR server - Not yet supported */
260 		break;
261 	case 10:		/* Impress server - Not yet supported */
262 		break;
263 	case 11:		/* RPL server - Not yet supported */
264 		break;
265 	case 12:		/* Host name */
266 		if (net_hostname[0] == 0) {
267 			size = truncate_sz("Host Name",
268 				sizeof(net_hostname), size);
269 			memcpy(&net_hostname, ext + 2, size);
270 			net_hostname[size] = 0;
271 		}
272 		break;
273 	case 13:		/* Boot file size */
274 		if (size == 2)
275 			net_boot_file_expected_size_in_blocks =
276 				ntohs(*(ushort *)(ext + 2));
277 		else if (size == 4)
278 			net_boot_file_expected_size_in_blocks =
279 				ntohl(*(ulong *)(ext + 2));
280 		break;
281 	case 14:		/* Merit dump file - Not yet supported */
282 		break;
283 	case 15:		/* Domain name - Not yet supported */
284 		break;
285 	case 16:		/* Swap server - Not yet supported */
286 		break;
287 	case 17:		/* Root path */
288 		if (net_root_path[0] == 0) {
289 			size = truncate_sz("Root Path",
290 				sizeof(net_root_path), size);
291 			memcpy(&net_root_path, ext + 2, size);
292 			net_root_path[size] = 0;
293 		}
294 		break;
295 	case 18:		/* Extension path - Not yet supported */
296 		/*
297 		 * This can be used to send the information of the
298 		 * vendor area in another file that the client can
299 		 * access via TFTP.
300 		 */
301 		break;
302 		/* IP host layer fields */
303 	case 40:		/* NIS Domain name */
304 		if (net_nis_domain[0] == 0) {
305 			size = truncate_sz("NIS Domain Name",
306 				sizeof(net_nis_domain), size);
307 			memcpy(&net_nis_domain, ext + 2, size);
308 			net_nis_domain[size] = 0;
309 		}
310 		break;
311 #if defined(CONFIG_CMD_SNTP) && defined(CONFIG_BOOTP_NTPSERVER)
312 	case 42:	/* NTP server IP */
313 		net_copy_ip(&net_ntp_server, (struct in_addr *)(ext + 2));
314 		break;
315 #endif
316 		/* Application layer fields */
317 	case 43:		/* Vendor specific info - Not yet supported */
318 		/*
319 		 * Binary information to exchange specific
320 		 * product information.
321 		 */
322 		break;
323 		/* Reserved (custom) fields (128..254) */
324 	}
325 }
326 
bootp_process_vendor(u8 * ext,int size)327 static void bootp_process_vendor(u8 *ext, int size)
328 {
329 	u8 *end = ext + size;
330 
331 	debug("[BOOTP] Checking extension (%d bytes)...\n", size);
332 
333 	while ((ext < end) && (*ext != 0xff)) {
334 		if (*ext == 0) {
335 			ext++;
336 		} else {
337 			u8 *opt = ext;
338 
339 			ext += ext[1] + 2;
340 			if (ext <= end)
341 				bootp_process_vendor_field(opt);
342 		}
343 	}
344 
345 	debug("[BOOTP] Received fields:\n");
346 	if (net_netmask.s_addr)
347 		debug("net_netmask : %pI4\n", &net_netmask);
348 
349 	if (net_gateway.s_addr)
350 		debug("net_gateway	: %pI4", &net_gateway);
351 
352 	if (net_boot_file_expected_size_in_blocks)
353 		debug("net_boot_file_expected_size_in_blocks : %d\n",
354 		      net_boot_file_expected_size_in_blocks);
355 
356 	if (net_hostname[0])
357 		debug("net_hostname  : %s\n", net_hostname);
358 
359 	if (net_root_path[0])
360 		debug("net_root_path  : %s\n", net_root_path);
361 
362 	if (net_nis_domain[0])
363 		debug("net_nis_domain : %s\n", net_nis_domain);
364 
365 #if defined(CONFIG_CMD_SNTP) && defined(CONFIG_BOOTP_NTPSERVER)
366 	if (net_ntp_server.s_addr)
367 		debug("net_ntp_server : %pI4\n", &net_ntp_server);
368 #endif
369 }
370 
371 /*
372  *	Handle a BOOTP received packet.
373  */
bootp_handler(uchar * pkt,unsigned dest,struct in_addr sip,unsigned src,unsigned len)374 static void bootp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
375 			  unsigned src, unsigned len)
376 {
377 	struct bootp_hdr *bp;
378 
379 	debug("got BOOTP packet (src=%d, dst=%d, len=%d want_len=%zu)\n",
380 	      src, dest, len, sizeof(struct bootp_hdr));
381 
382 	bp = (struct bootp_hdr *)pkt;
383 
384 	/* Filter out pkts we don't want */
385 	if (check_reply_packet(pkt, dest, src, len))
386 		return;
387 
388 	/*
389 	 *	Got a good BOOTP reply.	 Copy the data into our variables.
390 	 */
391 #if defined(CONFIG_LED_STATUS) && defined(CONFIG_LED_STATUS_BOOT_ENABLE)
392 	status_led_set(CONFIG_LED_STATUS_BOOT, CONFIG_LED_STATUS_OFF);
393 #endif
394 
395 	store_net_params(bp);		/* Store net parameters from reply */
396 
397 	/* Retrieve extended information (we must parse the vendor area) */
398 	if (net_read_u32((u32 *)&bp->bp_vend[0]) == htonl(BOOTP_VENDOR_MAGIC))
399 		bootp_process_vendor((uchar *)&bp->bp_vend[4], len);
400 
401 	net_set_timeout_handler(0, (thand_f *)0);
402 	bootstage_mark_name(BOOTSTAGE_ID_BOOTP_STOP, "bootp_stop");
403 
404 	debug("Got good BOOTP\n");
405 
406 	net_auto_load();
407 }
408 #endif
409 
410 /*
411  *	Timeout on BOOTP/DHCP request.
412  */
bootp_timeout_handler(void)413 static void bootp_timeout_handler(void)
414 {
415 	ulong time_taken = get_timer(bootp_start);
416 	int rand_minus_plus_100;
417 
418 	if (time_taken >= time_taken_max) {
419 #ifdef CONFIG_BOOTP_MAY_FAIL
420 		char *ethrotate;
421 
422 		ethrotate = env_get("ethrotate");
423 		if ((ethrotate && strcmp(ethrotate, "no") == 0) ||
424 		    net_restart_wrap) {
425 			puts("\nRetry time exceeded\n");
426 			net_set_state(NETLOOP_FAIL);
427 		} else
428 #endif
429 		{
430 			puts("\nRetry time exceeded; starting again\n");
431 			net_start_again();
432 		}
433 	} else {
434 		bootp_timeout *= 2;
435 		if (bootp_timeout > retransmit_period_max_ms)
436 			bootp_timeout = retransmit_period_max_ms;
437 
438 		/* Randomize by adding bootp_timeout*RAND, where RAND
439 		 * is a randomization factor between -0.1..+0.1
440 		 */
441 		srand(get_ticks() + rand());
442 		rand_minus_plus_100 = ((rand() % 200) - 100);
443 		bootp_timeout = bootp_timeout +
444 				(((int)bootp_timeout * rand_minus_plus_100) / 1000);
445 
446 		net_set_timeout_handler(bootp_timeout, bootp_timeout_handler);
447 		bootp_request();
448 	}
449 }
450 
451 #define put_vci(e, str)						\
452 	do {							\
453 		size_t vci_strlen = strlen(str);		\
454 		*e++ = 60;	/* Vendor Class Identifier */	\
455 		*e++ = vci_strlen;				\
456 		memcpy(e, str, vci_strlen);			\
457 		e += vci_strlen;				\
458 	} while (0)
459 
add_vci(u8 * e)460 static u8 *add_vci(u8 *e)
461 {
462 	char *vci = NULL;
463 	char *env_vci = env_get("bootp_vci");
464 
465 #if defined(CONFIG_XPL_BUILD) && defined(CONFIG_SPL_NET_VCI_STRING)
466 	vci = CONFIG_SPL_NET_VCI_STRING;
467 #elif defined(CONFIG_BOOTP_VCI_STRING)
468 	vci = CONFIG_BOOTP_VCI_STRING;
469 #endif
470 
471 	if (env_vci)
472 		vci = env_vci;
473 
474 	if (vci)
475 		put_vci(e, vci);
476 
477 	return e;
478 }
479 
480 /*
481  *	Initialize BOOTP extension fields in the request.
482  */
483 #if defined(CONFIG_CMD_DHCP)
dhcp_extended(u8 * e,int message_type,struct in_addr server_ip,struct in_addr requested_ip)484 static int dhcp_extended(u8 *e, int message_type, struct in_addr server_ip,
485 			struct in_addr requested_ip)
486 {
487 	u8 *start = e;
488 	u8 *cnt;
489 #ifdef CONFIG_LIB_UUID
490 	char *uuid;
491 #endif
492 	int clientarch = -1;
493 
494 #if defined(CONFIG_BOOTP_VENDOREX)
495 	u8 *x;
496 #endif
497 #if defined(CONFIG_BOOTP_SEND_HOSTNAME)
498 	char *hostname;
499 #endif
500 
501 	*e++ = 99;		/* RFC1048 Magic Cookie */
502 	*e++ = 130;
503 	*e++ = 83;
504 	*e++ = 99;
505 
506 	*e++ = 53;		/* DHCP Message Type */
507 	*e++ = 1;
508 	*e++ = message_type;
509 
510 	*e++ = 57;		/* Maximum DHCP Message Size */
511 	*e++ = 2;
512 	*e++ = (576 - 312 + OPT_FIELD_SIZE) >> 8;
513 	*e++ = (576 - 312 + OPT_FIELD_SIZE) & 0xff;
514 
515 	if (server_ip.s_addr) {
516 		int tmp = ntohl(server_ip.s_addr);
517 
518 		*e++ = 54;	/* ServerID */
519 		*e++ = 4;
520 		*e++ = tmp >> 24;
521 		*e++ = tmp >> 16;
522 		*e++ = tmp >> 8;
523 		*e++ = tmp & 0xff;
524 	}
525 
526 	if (requested_ip.s_addr) {
527 		int tmp = ntohl(requested_ip.s_addr);
528 
529 		*e++ = 50;	/* Requested IP */
530 		*e++ = 4;
531 		*e++ = tmp >> 24;
532 		*e++ = tmp >> 16;
533 		*e++ = tmp >> 8;
534 		*e++ = tmp & 0xff;
535 	}
536 #if defined(CONFIG_BOOTP_SEND_HOSTNAME)
537 	hostname = env_get("hostname");
538 	if (hostname) {
539 		int hostnamelen = strlen(hostname);
540 
541 		*e++ = 12;	/* Hostname */
542 		*e++ = hostnamelen;
543 		memcpy(e, hostname, hostnamelen);
544 		e += hostnamelen;
545 	}
546 #endif
547 
548 #ifdef CONFIG_DHCP_PXE_CLIENTARCH
549 	clientarch = CONFIG_DHCP_PXE_CLIENTARCH;
550 #endif
551 
552 	if (env_get("bootp_arch"))
553 		clientarch = env_get_ulong("bootp_arch", 16, clientarch);
554 
555 	if (clientarch != 0xff) {
556 		*e++ = 93;	/* Client System Architecture */
557 		*e++ = 2;
558 		*e++ = (clientarch >> 8) & 0xff;
559 		*e++ = clientarch & 0xff;
560 	}
561 
562 	*e++ = 94;	/* Client Network Interface Identifier */
563 	*e++ = 3;
564 	*e++ = 1;	/* type field for UNDI */
565 	*e++ = 0;	/* major revision */
566 	*e++ = 0;	/* minor revision */
567 
568 #ifdef CONFIG_LIB_UUID
569 	uuid = env_get("pxeuuid");
570 
571 	if (uuid) {
572 		if (uuid_str_valid(uuid)) {
573 			*e++ = 97;	/* Client Machine Identifier */
574 			*e++ = 17;
575 			*e++ = 0;	/* type 0 - UUID */
576 
577 			uuid_str_to_bin(uuid, e, UUID_STR_FORMAT_STD);
578 			e += 16;
579 		} else {
580 			printf("Invalid pxeuuid: %s\n", uuid);
581 		}
582 	}
583 #endif
584 
585 	e = add_vci(e);
586 
587 #if defined(CONFIG_BOOTP_VENDOREX)
588 	x = dhcp_vendorex_prep(e);
589 	if (x)
590 		return x - start;
591 #endif
592 
593 	*e++ = 55;		/* Parameter Request List */
594 	 cnt = e++;		/* Pointer to count of requested items */
595 	*cnt = 0;
596 #if defined(CONFIG_BOOTP_SUBNETMASK)
597 	*e++  = 1;		/* Subnet Mask */
598 	*cnt += 1;
599 #endif
600 #if defined(CONFIG_BOOTP_TIMEOFFSET)
601 	*e++  = 2;
602 	*cnt += 1;
603 #endif
604 #if defined(CONFIG_BOOTP_GATEWAY)
605 	*e++  = 3;		/* Router Option */
606 	*cnt += 1;
607 #endif
608 #if defined(CONFIG_BOOTP_DNS)
609 	*e++  = 6;		/* DNS Server(s) */
610 	*cnt += 1;
611 #endif
612 #if defined(CONFIG_BOOTP_HOSTNAME)
613 	*e++  = 12;		/* Hostname */
614 	*cnt += 1;
615 #endif
616 #if defined(CONFIG_BOOTP_BOOTFILESIZE)
617 	*e++  = 13;		/* Boot File Size */
618 	*cnt += 1;
619 #endif
620 #if defined(CONFIG_BOOTP_BOOTPATH)
621 	*e++  = 17;		/* Boot path */
622 	*cnt += 1;
623 #endif
624 #if defined(CONFIG_BOOTP_NISDOMAIN)
625 	*e++  = 40;		/* NIS Domain name request */
626 	*cnt += 1;
627 #endif
628 #if defined(CONFIG_BOOTP_NTPSERVER)
629 	*e++  = 42;
630 	*cnt += 1;
631 #endif
632 	if (IS_ENABLED(CONFIG_BOOTP_PXE_DHCP_OPTION)) {
633 		*e++ = DHCP_OPTION_PXE_CONFIG_FILE;	/* PXELINUX Config File */
634 		*cnt += 1;
635 	}
636 	/* no options, so back up to avoid sending an empty request list */
637 	if (*cnt == 0)
638 		e -= 2;
639 
640 	*e++  = 255;		/* End of the list */
641 
642 	/* Pad to minimal length */
643 #ifdef	CFG_DHCP_MIN_EXT_LEN
644 	while ((e - start) < CFG_DHCP_MIN_EXT_LEN)
645 		*e++ = 0;
646 #endif
647 
648 	return e - start;
649 }
650 
651 #else
652 /*
653  * Warning: no field size check - change CONFIG_BOOTP_* at your own risk!
654  */
bootp_extended(u8 * e)655 static int bootp_extended(u8 *e)
656 {
657 	u8 *start = e;
658 
659 	*e++ = 99;		/* RFC1048 Magic Cookie */
660 	*e++ = 130;
661 	*e++ = 83;
662 	*e++ = 99;
663 
664 #if defined(CONFIG_CMD_DHCP)
665 	*e++ = 53;		/* DHCP Message Type */
666 	*e++ = 1;
667 	*e++ = DHCP_DISCOVER;
668 
669 	*e++ = 57;		/* Maximum DHCP Message Size */
670 	*e++ = 2;
671 	*e++ = (576 - 312 + OPT_FIELD_SIZE) >> 16;
672 	*e++ = (576 - 312 + OPT_FIELD_SIZE) & 0xff;
673 #endif
674 
675 	e = add_vci(e);
676 
677 #if defined(CONFIG_BOOTP_SUBNETMASK)
678 	*e++ = 1;		/* Subnet mask request */
679 	*e++ = 4;
680 	e   += 4;
681 #endif
682 
683 #if defined(CONFIG_BOOTP_GATEWAY)
684 	*e++ = 3;		/* Default gateway request */
685 	*e++ = 4;
686 	e   += 4;
687 #endif
688 
689 #if defined(CONFIG_BOOTP_DNS)
690 	*e++ = 6;		/* Domain Name Server */
691 	*e++ = 4;
692 	e   += 4;
693 #endif
694 
695 #if defined(CONFIG_BOOTP_HOSTNAME)
696 	*e++ = 12;		/* Host name request */
697 	*e++ = 32;
698 	e   += 32;
699 #endif
700 
701 #if defined(CONFIG_BOOTP_BOOTFILESIZE)
702 	*e++ = 13;		/* Boot file size */
703 	*e++ = 2;
704 	e   += 2;
705 #endif
706 
707 #if defined(CONFIG_BOOTP_BOOTPATH)
708 	*e++ = 17;		/* Boot path */
709 	*e++ = 32;
710 	e   += 32;
711 #endif
712 
713 #if defined(CONFIG_BOOTP_NISDOMAIN)
714 	*e++ = 40;		/* NIS Domain name request */
715 	*e++ = 32;
716 	e   += 32;
717 #endif
718 #if defined(CONFIG_BOOTP_NTPSERVER)
719 	*e++ = 42;
720 	*e++ = 4;
721 	e   += 4;
722 #endif
723 
724 	*e++ = 255;		/* End of the list */
725 
726 	/*
727 	 * If nothing in list, remove it altogether. Some DHCP servers get
728 	 * upset by this minor faux pas and do not respond at all.
729 	 */
730 	if (e == start + 3) {
731 		printf("*** Warning: no DHCP options requested\n");
732 		e -= 3;
733 	}
734 
735 	return e - start;
736 }
737 #endif
738 
bootp_reset(void)739 void bootp_reset(void)
740 {
741 	bootp_num_ids = 0;
742 	bootp_try = 0;
743 	bootp_start = get_timer(0);
744 
745 	bootp_timeout = env_get_ulong("bootpretransmitperiodinit", 10, RETRANSMIT_PERIOD_INIT_MS);
746 }
747 
bootp_request(void)748 void bootp_request(void)
749 {
750 	uchar *pkt, *iphdr;
751 	struct bootp_hdr *bp;
752 	int extlen, pktlen, iplen;
753 	int eth_hdr_size;
754 #ifdef CONFIG_BOOTP_RANDOM_DELAY
755 	ulong rand_ms;
756 #endif
757 	struct in_addr zero_ip;
758 	struct in_addr bcast_ip;
759 	char *ep;  /* Environment pointer */
760 
761 	bootstage_mark_name(BOOTSTAGE_ID_BOOTP_START, "bootp_start");
762 #if defined(CONFIG_CMD_DHCP)
763 	dhcp_state = INIT;
764 #endif
765 
766 	ep = env_get("bootpretryperiod");
767 	if (ep != NULL)
768 		time_taken_max = dectoul(ep, NULL);
769 	else
770 		time_taken_max = TIMEOUT_MS;
771 
772 	retransmit_period_max_ms = env_get_ulong("bootpretransmitperiodmax", 10,
773 						 RETRANSMIT_PERIOD_MAX_MS);
774 
775 #ifdef CONFIG_BOOTP_RANDOM_DELAY		/* Random BOOTP delay */
776 	if (bootp_try == 0)
777 		srand_mac();
778 
779 	if (bootp_try <= 2)	/* Start with max 1024 * 1ms */
780 		rand_ms = rand() >> (22 - bootp_try);
781 	else		/* After 3rd BOOTP request max 8192 * 1ms */
782 		rand_ms = rand() >> 19;
783 
784 	printf("Random delay: %ld ms...\n", rand_ms);
785 	mdelay(rand_ms);
786 
787 #endif	/* CONFIG_BOOTP_RANDOM_DELAY */
788 
789 	printf("BOOTP broadcast %d\n", ++bootp_try);
790 	pkt = net_tx_packet;
791 	memset((void *)pkt, 0, PKTSIZE);
792 
793 	eth_hdr_size = net_set_ether(pkt, net_bcast_ethaddr, PROT_IP);
794 	pkt += eth_hdr_size;
795 
796 	/*
797 	 * Next line results in incorrect packet size being transmitted,
798 	 * resulting in errors in some DHCP servers, reporting missing bytes.
799 	 * Size must be set in packet header after extension length has been
800 	 * determined.
801 	 * C. Hallinan, DS4.COM, Inc.
802 	 */
803 	/* net_set_udp_header(pkt, 0xFFFFFFFFL, PORT_BOOTPS, PORT_BOOTPC,
804 		sizeof (struct bootp_hdr)); */
805 	iphdr = pkt;	/* We need this later for net_set_udp_header() */
806 	pkt += IP_UDP_HDR_SIZE;
807 
808 	bp = (struct bootp_hdr *)pkt;
809 	bp->bp_op = OP_BOOTREQUEST;
810 	bp->bp_htype = HWT_ETHER;
811 	bp->bp_hlen = HWL_ETHER;
812 	bp->bp_hops = 0;
813 	/*
814 	 * according to RFC1542, should be 0 on first request, secs since
815 	 * first request otherwise
816 	 */
817 	bp->bp_secs = htons(get_timer(bootp_start) / 1000);
818 	zero_ip.s_addr = 0;
819 	net_write_ip(&bp->bp_ciaddr, zero_ip);
820 	net_write_ip(&bp->bp_yiaddr, zero_ip);
821 	net_write_ip(&bp->bp_siaddr, zero_ip);
822 	net_write_ip(&bp->bp_giaddr, zero_ip);
823 	memcpy(bp->bp_chaddr, net_ethaddr, 6);
824 	copy_filename(bp->bp_file, net_boot_file_name, sizeof(bp->bp_file));
825 
826 	/* Request additional information from the BOOTP/DHCP server */
827 #if defined(CONFIG_CMD_DHCP)
828 	extlen = dhcp_extended((u8 *)bp->bp_vend, DHCP_DISCOVER, zero_ip,
829 			       zero_ip);
830 #else
831 	extlen = bootp_extended((u8 *)bp->bp_vend);
832 #endif
833 
834 	/* Only generate a new transaction ID for each new BOOTP request */
835 	if (bootp_try == 1) {
836 		if (IS_ENABLED(CONFIG_BOOTP_RANDOM_XID)) {
837 			srand(get_ticks() + rand());
838 			bootp_id = rand();
839 		} else {
840 			/*
841 			 *	Bootp ID is the lower 4 bytes of our ethernet address
842 			 *	plus the current time in ms.
843 			 */
844 			bootp_id = ((u32)net_ethaddr[2] << 24)
845 				| ((u32)net_ethaddr[3] << 16)
846 				| ((u32)net_ethaddr[4] << 8)
847 				| (u32)net_ethaddr[5];
848 			bootp_id += get_timer(0);
849 			bootp_id = htonl(bootp_id);
850 		}
851 	}
852 
853 	bootp_add_id(bootp_id);
854 	net_copy_u32(&bp->bp_id, &bootp_id);
855 	/*
856 	 * Calculate proper packet lengths taking into account the
857 	 * variable size of the options field
858 	 */
859 	iplen = BOOTP_HDR_SIZE - OPT_FIELD_SIZE + extlen;
860 	pktlen = eth_hdr_size + IP_UDP_HDR_SIZE + iplen;
861 	bcast_ip.s_addr = 0xFFFFFFFFL;
862 	net_set_udp_header(iphdr, bcast_ip, PORT_BOOTPS, PORT_BOOTPC, iplen);
863 	net_set_timeout_handler(bootp_timeout, bootp_timeout_handler);
864 
865 #if defined(CONFIG_CMD_DHCP)
866 	dhcp_state = SELECTING;
867 	net_set_udp_handler(dhcp_handler);
868 #else
869 	net_set_udp_handler(bootp_handler);
870 #endif
871 	net_send_packet(net_tx_packet, pktlen);
872 }
873 
874 #if defined(CONFIG_CMD_DHCP)
dhcp_process_options(uchar * popt,uchar * end)875 static void dhcp_process_options(uchar *popt, uchar *end)
876 {
877 	int oplen, size;
878 #if defined(CONFIG_CMD_SNTP) && defined(CONFIG_BOOTP_TIMEOFFSET)
879 	int *to_ptr;
880 #endif
881 
882 	while (popt < end && *popt != 0xff) {
883 		oplen = *(popt + 1);
884 		switch (*popt) {
885 		case 0:
886 			oplen = -1; /* Pad omits len byte */
887 			break;
888 		case 1:
889 			net_copy_ip(&net_netmask, (popt + 2));
890 			break;
891 #if defined(CONFIG_CMD_SNTP) && defined(CONFIG_BOOTP_TIMEOFFSET)
892 		case 2:		/* Time offset	*/
893 			to_ptr = &net_ntp_time_offset;
894 			net_copy_u32((u32 *)to_ptr, (u32 *)(popt + 2));
895 			net_ntp_time_offset = ntohl(net_ntp_time_offset);
896 			break;
897 #endif
898 		case 3:
899 			net_copy_ip(&net_gateway, (popt + 2));
900 			break;
901 		case 6:
902 			net_copy_ip(&net_dns_server, (popt + 2));
903 #if defined(CONFIG_BOOTP_DNS2)
904 			if (*(popt + 1) > 4)
905 				net_copy_ip(&net_dns_server2, (popt + 2 + 4));
906 #endif
907 			break;
908 		case 12:
909 			size = truncate_sz("Host Name",
910 				sizeof(net_hostname), oplen);
911 			memcpy(&net_hostname, popt + 2, size);
912 			net_hostname[size] = 0;
913 			break;
914 		case 15:	/* Ignore Domain Name Option */
915 			break;
916 		case 17:
917 			size = truncate_sz("Root Path",
918 				sizeof(net_root_path), oplen);
919 			memcpy(&net_root_path, popt + 2, size);
920 			net_root_path[size] = 0;
921 			break;
922 		case 28:	/* Ignore Broadcast Address Option */
923 			break;
924 		case 40:	/* NIS Domain name */
925 			if (net_nis_domain[0] == 0) {
926 				size = truncate_sz("NIS Domain Name",
927 					sizeof(net_nis_domain), oplen);
928 				memcpy(&net_nis_domain, popt + 2, size);
929 				net_nis_domain[size] = 0;
930 			}
931 			break;
932 #if defined(CONFIG_CMD_SNTP) && defined(CONFIG_BOOTP_NTPSERVER)
933 		case 42:	/* NTP server IP */
934 			net_copy_ip(&net_ntp_server, (popt + 2));
935 			break;
936 #endif
937 		case 51:
938 			net_copy_u32(&dhcp_leasetime, (u32 *)(popt + 2));
939 			break;
940 		case 52:
941 			dhcp_option_overload = popt[2];
942 			break;
943 		case 53:	/* Ignore Message Type Option */
944 			break;
945 		case 54:
946 			net_copy_ip(&dhcp_server_ip, (popt + 2));
947 			break;
948 		case 58:	/* Ignore Renewal Time Option */
949 			break;
950 		case 59:	/* Ignore Rebinding Time Option */
951 			break;
952 		case 66:	/* Ignore TFTP server name */
953 			break;
954 		case 67:	/* Bootfile option */
955 			if (!net_boot_file_name_explicit) {
956 				size = truncate_sz("Bootfile",
957 						   sizeof(net_boot_file_name),
958 						   oplen);
959 				memcpy(&net_boot_file_name, popt + 2, size);
960 				net_boot_file_name[size] = 0;
961 			}
962 			break;
963 		case DHCP_OPTION_PXE_CONFIG_FILE:	/* PXELINUX Config File */
964 			if (IS_ENABLED(CONFIG_BOOTP_PXE_DHCP_OPTION)) {
965 				/* In case it has already been allocated when get DHCP Offer packet,
966 				 * free first to avoid memory leak.
967 				 */
968 				if (pxelinux_configfile)
969 					free(pxelinux_configfile);
970 
971 				pxelinux_configfile = (char *)malloc((oplen + 1) * sizeof(char));
972 
973 				if (pxelinux_configfile)
974 					strlcpy(pxelinux_configfile, popt + 2, oplen + 1);
975 				else
976 					printf("Error: Failed to allocate pxelinux_configfile\n");
977 			}
978 			break;
979 		default:
980 #if defined(CONFIG_BOOTP_VENDOREX)
981 			if (dhcp_vendorex_proc(popt))
982 				break;
983 #endif
984 			printf("*** Unhandled DHCP Option in OFFER/ACK:"
985 			       " %d\n", *popt);
986 			break;
987 		}
988 		popt += oplen + 2;	/* Process next option */
989 	}
990 }
991 
dhcp_packet_process_options(struct bootp_hdr * bp)992 static void dhcp_packet_process_options(struct bootp_hdr *bp)
993 {
994 	uchar *popt = (uchar *)&bp->bp_vend[4];
995 	uchar *end = popt + BOOTP_HDR_SIZE;
996 
997 	if (net_read_u32((u32 *)&bp->bp_vend[0]) != htonl(BOOTP_VENDOR_MAGIC))
998 		return;
999 
1000 	dhcp_option_overload = 0;
1001 
1002 	/*
1003 	 * The 'options' field MUST be interpreted first, 'file' next,
1004 	 * 'sname' last.
1005 	 */
1006 	dhcp_process_options(popt, end);
1007 
1008 	if (dhcp_option_overload & OVERLOAD_FILE) {
1009 		popt = (uchar *)bp->bp_file;
1010 		end = popt + sizeof(bp->bp_file);
1011 		dhcp_process_options(popt, end);
1012 	}
1013 
1014 	if (dhcp_option_overload & OVERLOAD_SNAME) {
1015 		popt = (uchar *)bp->bp_sname;
1016 		end = popt + sizeof(bp->bp_sname);
1017 		dhcp_process_options(popt, end);
1018 	}
1019 }
1020 
dhcp_message_type(unsigned char * popt)1021 static int dhcp_message_type(unsigned char *popt)
1022 {
1023 	if (net_read_u32((u32 *)popt) != htonl(BOOTP_VENDOR_MAGIC))
1024 		return -1;
1025 
1026 	popt += 4;
1027 	while (*popt != 0xff) {
1028 		if (*popt == 53)	/* DHCP Message Type */
1029 			return *(popt + 2);
1030 		if (*popt == 0)	{
1031 			/* Pad */
1032 			popt += 1;
1033 		} else {
1034 			/* Scan through all options */
1035 			popt += *(popt + 1) + 2;
1036 		}
1037 	}
1038 	return -1;
1039 }
1040 
dhcp_send_request_packet(struct bootp_hdr * bp_offer)1041 static void dhcp_send_request_packet(struct bootp_hdr *bp_offer)
1042 {
1043 	uchar *pkt, *iphdr;
1044 	struct bootp_hdr *bp;
1045 	int pktlen, iplen, extlen;
1046 	int eth_hdr_size;
1047 	struct in_addr offered_ip;
1048 	struct in_addr zero_ip;
1049 	struct in_addr bcast_ip;
1050 
1051 	debug("dhcp_send_request_packet: Sending DHCPREQUEST\n");
1052 	pkt = net_tx_packet;
1053 	memset((void *)pkt, 0, PKTSIZE);
1054 
1055 	eth_hdr_size = net_set_ether(pkt, net_bcast_ethaddr, PROT_IP);
1056 	pkt += eth_hdr_size;
1057 
1058 	iphdr = pkt;	/* We'll need this later to set proper pkt size */
1059 	pkt += IP_UDP_HDR_SIZE;
1060 
1061 	bp = (struct bootp_hdr *)pkt;
1062 	bp->bp_op = OP_BOOTREQUEST;
1063 	bp->bp_htype = HWT_ETHER;
1064 	bp->bp_hlen = HWL_ETHER;
1065 	bp->bp_hops = 0;
1066 	bp->bp_secs = htons(get_timer(bootp_start) / 1000);
1067 	/* Do not set the client IP, your IP, or server IP yet, since it
1068 	 * hasn't been ACK'ed by the server yet */
1069 
1070 	/*
1071 	 * RFC3046 requires Relay Agents to discard packets with
1072 	 * nonzero and offered giaddr
1073 	 */
1074 	zero_ip.s_addr = 0;
1075 	net_write_ip(&bp->bp_giaddr, zero_ip);
1076 
1077 	memcpy(bp->bp_chaddr, net_ethaddr, 6);
1078 	copy_filename(bp->bp_file, net_boot_file_name, sizeof(bp->bp_file));
1079 
1080 	/*
1081 	 * ID is the id of the OFFER packet
1082 	 */
1083 
1084 	net_copy_u32(&bp->bp_id, &bp_offer->bp_id);
1085 
1086 	/*
1087 	 * Copy options from OFFER packet if present
1088 	 */
1089 
1090 	/* Copy offered IP into the parameters request list */
1091 	net_copy_ip(&offered_ip, &bp_offer->bp_yiaddr);
1092 	extlen = dhcp_extended((u8 *)bp->bp_vend, DHCP_REQUEST,
1093 		dhcp_server_ip, offered_ip);
1094 
1095 	iplen = BOOTP_HDR_SIZE - OPT_FIELD_SIZE + extlen;
1096 	pktlen = eth_hdr_size + IP_UDP_HDR_SIZE + iplen;
1097 	bcast_ip.s_addr = 0xFFFFFFFFL;
1098 	net_set_udp_header(iphdr, bcast_ip, PORT_BOOTPS, PORT_BOOTPC, iplen);
1099 
1100 	debug("Transmitting DHCPREQUEST packet: len = %d\n", pktlen);
1101 	net_send_packet(net_tx_packet, pktlen);
1102 }
1103 
1104 /*
1105  *	Handle DHCP received packets.
1106  */
dhcp_handler(uchar * pkt,unsigned dest,struct in_addr sip,unsigned src,unsigned len)1107 static void dhcp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
1108 			 unsigned src, unsigned len)
1109 {
1110 	struct bootp_hdr *bp = (struct bootp_hdr *)pkt;
1111 
1112 	debug("DHCPHandler: got packet: (src=%d, dst=%d, len=%d) state: %d\n",
1113 	      src, dest, len, dhcp_state);
1114 
1115 	/* Filter out pkts we don't want */
1116 	if (check_reply_packet(pkt, dest, src, len))
1117 		return;
1118 
1119 	debug("DHCPHandler: got DHCP packet: (src=%d, dst=%d, len=%d) state: "
1120 	      "%d\n", src, dest, len, dhcp_state);
1121 
1122 	if (net_read_ip(&bp->bp_yiaddr).s_addr == 0) {
1123 #if defined(CONFIG_SERVERIP_FROM_PROXYDHCP)
1124 		store_bootp_params(bp);
1125 #endif
1126 		return;
1127 	}
1128 
1129 	switch (dhcp_state) {
1130 	case SELECTING:
1131 		/*
1132 		 * Wait an appropriate time for any potential DHCPOFFER packets
1133 		 * to arrive.  Then select one, and generate DHCPREQUEST
1134 		 * response.  If filename is in format we recognize, assume it
1135 		 * is a valid OFFER from a server we want.
1136 		 */
1137 		debug("DHCP: state=SELECTING bp_file: \"%s\"\n", bp->bp_file);
1138 #ifdef CONFIG_SYS_BOOTFILE_PREFIX
1139 		if (strncmp(bp->bp_file,
1140 			    CONFIG_SYS_BOOTFILE_PREFIX,
1141 			    strlen(CONFIG_SYS_BOOTFILE_PREFIX)) == 0) {
1142 #endif	/* CONFIG_SYS_BOOTFILE_PREFIX */
1143 			if (CONFIG_IS_ENABLED(UNIT_TEST) &&
1144 			    dhcp_message_type((u8 *)bp->bp_vend) == -1) {
1145 				debug("got BOOTP response; transitioning to BOUND\n");
1146 				goto dhcp_got_bootp;
1147 			}
1148 			dhcp_packet_process_options(bp);
1149 			if (CONFIG_IS_ENABLED(EFI_LOADER) &&
1150 			    IS_ENABLED(CONFIG_NETDEVICES))
1151 				efi_net_set_dhcp_ack(pkt, len);
1152 
1153 #if defined(CONFIG_SERVERIP_FROM_PROXYDHCP)
1154 			if (!net_server_ip.s_addr)
1155 				udelay(CONFIG_SERVERIP_FROM_PROXYDHCP_DELAY_MS *
1156 					1000);
1157 #endif	/* CONFIG_SERVERIP_FROM_PROXYDHCP */
1158 
1159 			debug("TRANSITIONING TO REQUESTING STATE\n");
1160 			dhcp_state = REQUESTING;
1161 
1162 			net_set_timeout_handler(5000, bootp_timeout_handler);
1163 			dhcp_send_request_packet(bp);
1164 #ifdef CONFIG_SYS_BOOTFILE_PREFIX
1165 		}
1166 #endif	/* CONFIG_SYS_BOOTFILE_PREFIX */
1167 
1168 		return;
1169 		break;
1170 	case REQUESTING:
1171 		debug("DHCP State: REQUESTING\n");
1172 
1173 		if (dhcp_message_type((u8 *)bp->bp_vend) == DHCP_ACK) {
1174 dhcp_got_bootp:
1175 			dhcp_packet_process_options(bp);
1176 			/* Store net params from reply */
1177 			store_net_params(bp);
1178 			dhcp_state = BOUND;
1179 			printf("DHCP client bound to address %pI4 (%lu ms)\n",
1180 			       &net_ip, get_timer(bootp_start));
1181 			net_set_timeout_handler(0, (thand_f *)0);
1182 			bootstage_mark_name(BOOTSTAGE_ID_BOOTP_STOP,
1183 					    "bootp_stop");
1184 
1185 			net_auto_load();
1186 			return;
1187 		}
1188 		break;
1189 	case BOUND:
1190 		/* DHCP client bound to address */
1191 		break;
1192 	default:
1193 		puts("DHCP: INVALID STATE\n");
1194 		break;
1195 	}
1196 }
1197 
dhcp_request(void)1198 void dhcp_request(void)
1199 {
1200 	bootp_request();
1201 }
1202 #endif	/* CONFIG_CMD_DHCP */
1203