1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *	Copied from Linux Monitor (LiMon) - Networking.
4  *
5  *	Copyright 1994 - 2000 Neil Russell.
6  *	Copyright 2000 Roland Borde
7  *	Copyright 2000 Paolo Scaffardi
8  *	Copyright 2000-2002 Wolfgang Denk, wd@denx.de
9  */
10 
11 /*
12  * General Desription:
13  *
14  * The user interface supports commands for BOOTP, RARP, and TFTP.
15  * Also, we support ARP internally. Depending on available data,
16  * these interact as follows:
17  *
18  * BOOTP:
19  *
20  *	Prerequisites:	- own ethernet address
21  *	We want:	- own IP address
22  *			- TFTP server IP address
23  *			- name of bootfile
24  *	Next step:	ARP
25  *
26  * LINKLOCAL:
27  *
28  *	Prerequisites:	- own ethernet address
29  *	We want:	- own IP address
30  *	Next step:	ARP
31  *
32  * RARP:
33  *
34  *	Prerequisites:	- own ethernet address
35  *	We want:	- own IP address
36  *			- TFTP server IP address
37  *	Next step:	ARP
38  *
39  * ARP:
40  *
41  *	Prerequisites:	- own ethernet address
42  *			- own IP address
43  *			- TFTP server IP address
44  *	We want:	- TFTP server ethernet address
45  *	Next step:	TFTP
46  *
47  * DHCP:
48  *
49  *     Prerequisites:	- own ethernet address
50  *     We want:		- IP, Netmask, ServerIP, Gateway IP
51  *			- bootfilename, lease time
52  *     Next step:	- TFTP
53  *
54  * TFTP:
55  *
56  *	Prerequisites:	- own ethernet address
57  *			- own IP address
58  *			- TFTP server IP address
59  *			- TFTP server ethernet address
60  *			- name of bootfile (if unknown, we use a default name
61  *			  derived from our own IP address)
62  *	We want:	- load the boot file
63  *	Next step:	none
64  *
65  * NFS:
66  *
67  *	Prerequisites:	- own ethernet address
68  *			- own IP address
69  *			- name of bootfile (if unknown, we use a default name
70  *			  derived from our own IP address)
71  *	We want:	- load the boot file
72  *	Next step:	none
73  *
74  *
75  * WOL:
76  *
77  *	Prerequisites:	- own ethernet address
78  *	We want:	- magic packet or timeout
79  *	Next step:	none
80  */
81 
82 #include <bootstage.h>
83 #include <command.h>
84 #include <console.h>
85 #include <env.h>
86 #include <env_internal.h>
87 #include <errno.h>
88 #include <image.h>
89 #include <led.h>
90 #include <log.h>
91 #if defined(CONFIG_LED_STATUS)
92 #include <miiphy.h>
93 #endif
94 #include <net.h>
95 #include <net6.h>
96 #include <ndisc.h>
97 #if defined(CONFIG_LED_STATUS)
98 #include <status_led.h>
99 #endif
100 #include <watchdog.h>
101 #include <linux/compiler.h>
102 #include <net/fastboot_udp.h>
103 #include <net/fastboot_tcp.h>
104 #include <net/ncsi.h>
105 #if defined(CONFIG_CMD_PCAP)
106 #include <net/pcap.h>
107 #endif
108 #include <net/tcp.h>
109 #include <net/tftp.h>
110 #include <net/udp.h>
111 #include <net/wget.h>
112 #include <test/test.h>
113 #include "arp.h"
114 #include "bootp.h"
115 #include "cdp.h"
116 #include "dhcpv6.h"
117 #if defined(CONFIG_DNS)
118 #include "dns.h"
119 #endif
120 #include "link_local.h"
121 #include "net_rand.h"
122 #include "nfs.h"
123 #include "ping.h"
124 #include "rarp.h"
125 #if defined(CONFIG_CMD_WOL)
126 #include "wol.h"
127 #endif
128 
129 /** BOOTP EXTENTIONS **/
130 
131 /* Our subnet mask (0=unknown) */
132 struct in_addr net_netmask;
133 /* Our gateways IP address */
134 struct in_addr net_gateway;
135 /* Our DNS IP address */
136 struct in_addr net_dns_server;
137 #if defined(CONFIG_BOOTP_DNS2)
138 /* Our 2nd DNS IP address */
139 struct in_addr net_dns_server2;
140 #endif
141 /* Indicates whether the pxe path prefix / config file was specified in dhcp option */
142 char *pxelinux_configfile;
143 
144 /** END OF BOOTP EXTENTIONS **/
145 
146 /* Our ethernet address */
147 u8 net_ethaddr[6];
148 /* Boot server enet address */
149 u8 net_server_ethaddr[6];
150 /* Our IP addr (0 = unknown) */
151 struct in_addr	net_ip;
152 /* Server IP addr (0 = unknown) */
153 struct in_addr	net_server_ip;
154 /* Current receive packet */
155 uchar *net_rx_packet;
156 /* Current rx packet length */
157 int		net_rx_packet_len;
158 /* IP packet ID */
159 static unsigned	net_ip_id;
160 /* Ethernet bcast address */
161 const u8 net_bcast_ethaddr[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
162 const u8 net_null_ethaddr[6];
163 #if defined(CONFIG_API) || defined(CONFIG_EFI_LOADER)
164 void (*push_packet)(void *, int len) = 0;
165 #endif
166 /* Network loop state */
167 enum net_loop_state net_state;
168 /* Tried all network devices */
169 int		net_restart_wrap;
170 /* Network loop restarted */
171 static int	net_restarted;
172 /* At least one device configured */
173 static int	net_dev_exists;
174 
175 /* XXX in both little & big endian machines 0xFFFF == ntohs(-1) */
176 /* default is without VLAN */
177 ushort		net_our_vlan = 0xFFFF;
178 /* ditto */
179 ushort		net_native_vlan = 0xFFFF;
180 
181 /* Boot File name */
182 char net_boot_file_name[1024];
183 /* Indicates whether the file name was specified on the command line */
184 bool net_boot_file_name_explicit;
185 /* The actual transferred size of the bootfile (in bytes) */
186 u32 net_boot_file_size;
187 /* Boot file size in blocks as reported by the DHCP server */
188 u32 net_boot_file_expected_size_in_blocks;
189 
190 static uchar net_pkt_buf[(PKTBUFSRX+1) * PKTSIZE_ALIGN + PKTALIGN];
191 /* Receive packets */
192 uchar *net_rx_packets[PKTBUFSRX];
193 /* Current UDP RX packet handler */
194 static rxhand_f *udp_packet_handler;
195 /* Current ARP RX packet handler */
196 static rxhand_f *arp_packet_handler;
197 #ifdef CONFIG_CMD_TFTPPUT
198 /* Current ICMP rx handler */
199 static rxhand_icmp_f *packet_icmp_handler;
200 #endif
201 /* Current timeout handler */
202 static thand_f *time_handler;
203 /* Time base value */
204 static ulong	time_start;
205 /* Current timeout value */
206 static ulong	time_delta;
207 /* THE transmit packet */
208 uchar *net_tx_packet;
209 
210 static int net_check_prereq(enum proto_t protocol);
211 
212 static int net_try_count;
213 
214 int __maybe_unused net_busy_flag;
215 
216 /**********************************************************************/
217 
on_ipaddr(const char * name,const char * value,enum env_op op,int flags)218 static int on_ipaddr(const char *name, const char *value, enum env_op op,
219 	int flags)
220 {
221 	if (flags & H_PROGRAMMATIC)
222 		return 0;
223 
224 	net_ip = string_to_ip(value);
225 
226 	return 0;
227 }
228 U_BOOT_ENV_CALLBACK(ipaddr, on_ipaddr);
229 
on_gatewayip(const char * name,const char * value,enum env_op op,int flags)230 static int on_gatewayip(const char *name, const char *value, enum env_op op,
231 	int flags)
232 {
233 	if (flags & H_PROGRAMMATIC)
234 		return 0;
235 
236 	net_gateway = string_to_ip(value);
237 
238 	return 0;
239 }
240 U_BOOT_ENV_CALLBACK(gatewayip, on_gatewayip);
241 
on_netmask(const char * name,const char * value,enum env_op op,int flags)242 static int on_netmask(const char *name, const char *value, enum env_op op,
243 	int flags)
244 {
245 	if (flags & H_PROGRAMMATIC)
246 		return 0;
247 
248 	net_netmask = string_to_ip(value);
249 
250 	return 0;
251 }
252 U_BOOT_ENV_CALLBACK(netmask, on_netmask);
253 
on_serverip(const char * name,const char * value,enum env_op op,int flags)254 static int on_serverip(const char *name, const char *value, enum env_op op,
255 	int flags)
256 {
257 	if (flags & H_PROGRAMMATIC)
258 		return 0;
259 
260 	net_server_ip = string_to_ip(value);
261 
262 	return 0;
263 }
264 U_BOOT_ENV_CALLBACK(serverip, on_serverip);
265 
on_nvlan(const char * name,const char * value,enum env_op op,int flags)266 static int on_nvlan(const char *name, const char *value, enum env_op op,
267 	int flags)
268 {
269 	if (flags & H_PROGRAMMATIC)
270 		return 0;
271 
272 	net_native_vlan = string_to_vlan(value);
273 
274 	return 0;
275 }
276 U_BOOT_ENV_CALLBACK(nvlan, on_nvlan);
277 
on_vlan(const char * name,const char * value,enum env_op op,int flags)278 static int on_vlan(const char *name, const char *value, enum env_op op,
279 	int flags)
280 {
281 	if (flags & H_PROGRAMMATIC)
282 		return 0;
283 
284 	net_our_vlan = string_to_vlan(value);
285 
286 	return 0;
287 }
288 U_BOOT_ENV_CALLBACK(vlan, on_vlan);
289 
290 #if defined(CONFIG_DNS)
on_dnsip(const char * name,const char * value,enum env_op op,int flags)291 static int on_dnsip(const char *name, const char *value, enum env_op op,
292 	int flags)
293 {
294 	if (flags & H_PROGRAMMATIC)
295 		return 0;
296 
297 	net_dns_server = string_to_ip(value);
298 
299 	return 0;
300 }
301 U_BOOT_ENV_CALLBACK(dnsip, on_dnsip);
302 #endif
303 
304 /*
305  * Check if autoload is enabled. If so, use either NFS or TFTP to download
306  * the boot file.
307  */
net_auto_load(void)308 void net_auto_load(void)
309 {
310 #if defined(CONFIG_CMD_NFS) && !defined(CONFIG_XPL_BUILD)
311 	const char *s = env_get("autoload");
312 
313 	if (s != NULL && strcmp(s, "NFS") == 0) {
314 		if (net_check_prereq(NFS)) {
315 /* We aren't expecting to get a serverip, so just accept the assigned IP */
316 			if (IS_ENABLED(CONFIG_BOOTP_SERVERIP)) {
317 				net_set_state(NETLOOP_SUCCESS);
318 			} else {
319 				printf("Cannot autoload with NFS\n");
320 				net_set_state(NETLOOP_FAIL);
321 			}
322 			return;
323 		}
324 		/*
325 		 * Use NFS to load the bootfile.
326 		 */
327 		nfs_start();
328 		return;
329 	}
330 #endif
331 	if (env_get_yesno("autoload") == 0) {
332 		/*
333 		 * Just use BOOTP/RARP to configure system;
334 		 * Do not use TFTP to load the bootfile.
335 		 */
336 		net_set_state(NETLOOP_SUCCESS);
337 		return;
338 	}
339 	if (IS_ENABLED(CONFIG_CMD_TFTPBOOT)) {
340 		if (net_check_prereq(TFTPGET)) {
341 			/*
342 			 * We aren't expecting to get a serverip, so just
343 			 * accept the assigned IP
344 			 */
345 			if (IS_ENABLED(CONFIG_BOOTP_SERVERIP)) {
346 				net_set_state(NETLOOP_SUCCESS);
347 			} else {
348 				printf("Cannot autoload with TFTPGET\n");
349 				net_set_state(NETLOOP_FAIL);
350 			}
351 			return;
352 		}
353 		tftp_start(TFTPGET);
354 	}
355 }
356 
net_init_loop(void)357 static int net_init_loop(void)
358 {
359 	static bool first_call = true;
360 
361 	if (eth_get_dev()) {
362 		memcpy(net_ethaddr, eth_get_ethaddr(), 6);
363 
364 		if (IS_ENABLED(CONFIG_IPV6)) {
365 			ip6_make_lladdr(&net_link_local_ip6, net_ethaddr);
366 			if (!memcmp(&net_ip6, &net_null_addr_ip6,
367 				    sizeof(struct in6_addr)))
368 				memcpy(&net_ip6, &net_link_local_ip6,
369 				       sizeof(struct in6_addr));
370 		}
371 	}
372 	else
373 		/*
374 		 * Not ideal, but there's no way to get the actual error, and I
375 		 * don't feel like fixing all the users of eth_get_dev to deal
376 		 * with errors.
377 		 */
378 		return -ENONET;
379 
380 	if (IS_ENABLED(CONFIG_IPV6_ROUTER_DISCOVERY))
381 		if (first_call && use_ip6) {
382 			first_call = false;
383 			srand_mac(); /* This is for rand used in ip6_send_rs. */
384 			net_loop(RS);
385 		}
386 	return 0;
387 }
388 
net_clear_handlers(void)389 static void net_clear_handlers(void)
390 {
391 	net_set_udp_handler(NULL);
392 	net_set_arp_handler(NULL);
393 	net_set_timeout_handler(0, NULL);
394 }
395 
net_cleanup_loop(void)396 static void net_cleanup_loop(void)
397 {
398 	net_clear_handlers();
399 }
400 
net_init(void)401 int net_init(void)
402 {
403 	static int first_call = 1;
404 
405 	if (first_call) {
406 		/*
407 		 *	Setup packet buffers, aligned correctly.
408 		 */
409 		int i;
410 
411 		net_tx_packet = &net_pkt_buf[0] + (PKTALIGN - 1);
412 		net_tx_packet -= (ulong)net_tx_packet % PKTALIGN;
413 		for (i = 0; i < PKTBUFSRX; i++) {
414 			net_rx_packets[i] = net_tx_packet +
415 				(i + 1) * PKTSIZE_ALIGN;
416 		}
417 		arp_init();
418 		ndisc_init();
419 		net_clear_handlers();
420 
421 		/* Only need to setup buffer pointers once. */
422 		first_call = 0;
423 		if (IS_ENABLED(CONFIG_PROT_TCP))
424 			tcp_init();
425 	}
426 
427 	return net_init_loop();
428 }
429 
430 /**********************************************************************/
431 /*
432  *	Main network processing loop.
433  */
434 
net_loop(enum proto_t protocol)435 int net_loop(enum proto_t protocol)
436 {
437 	int ret = -EINVAL;
438 	enum net_loop_state prev_net_state = net_state;
439 
440 #if defined(CONFIG_CMD_PING)
441 	if (protocol != PING)
442 		net_ping_ip.s_addr = 0;
443 #endif
444 	net_restarted = 0;
445 	net_dev_exists = 0;
446 	net_try_count = 1;
447 	debug_cond(DEBUG_INT_STATE, "--- net_loop Entry\n");
448 
449 #ifdef CONFIG_PHY_NCSI
450 	if (phy_interface_is_ncsi() && protocol != NCSI && !ncsi_active()) {
451 		printf("%s: configuring NCSI first\n", __func__);
452 		if (net_loop(NCSI) < 0)
453 			return ret;
454 		eth_init_state_only();
455 		goto restart;
456 	}
457 #endif
458 
459 	bootstage_mark_name(BOOTSTAGE_ID_ETH_START, "eth_start");
460 	net_init();
461 	if (eth_is_on_demand_init()) {
462 		eth_halt();
463 		eth_set_current();
464 		ret = eth_init();
465 		if (ret < 0) {
466 			eth_halt();
467 			return ret;
468 		}
469 	} else {
470 		eth_init_state_only();
471 	}
472 
473 restart:
474 #ifdef CONFIG_USB_KEYBOARD
475 	net_busy_flag = 0;
476 #endif
477 	net_set_state(NETLOOP_CONTINUE);
478 
479 	/*
480 	 *	Start the ball rolling with the given start function.  From
481 	 *	here on, this code is a state machine driven by received
482 	 *	packets and timer events.
483 	 */
484 	debug_cond(DEBUG_INT_STATE, "--- net_loop Init\n");
485 	net_init_loop();
486 
487 	if (!test_eth_enabled())
488 		return 0;
489 
490 	switch (net_check_prereq(protocol)) {
491 	case 1:
492 		/* network not configured */
493 		eth_halt();
494 		net_set_state(prev_net_state);
495 		return -ENODEV;
496 
497 	case 2:
498 		/* network device not configured */
499 		break;
500 
501 	case 0:
502 		net_dev_exists = 1;
503 		net_boot_file_size = 0;
504 		switch (protocol) {
505 #ifdef CONFIG_CMD_TFTPBOOT
506 		case TFTPGET:
507 #ifdef CONFIG_CMD_TFTPPUT
508 		case TFTPPUT:
509 #endif
510 			/* always use ARP to get server ethernet address */
511 			tftp_start(protocol);
512 			break;
513 #endif
514 #ifdef CONFIG_CMD_TFTPSRV
515 		case TFTPSRV:
516 			tftp_start_server();
517 			break;
518 #endif
519 #if CONFIG_IS_ENABLED(UDP_FUNCTION_FASTBOOT)
520 		case FASTBOOT_UDP:
521 			fastboot_udp_start_server();
522 			break;
523 #endif
524 #if CONFIG_IS_ENABLED(TCP_FUNCTION_FASTBOOT)
525 		case FASTBOOT_TCP:
526 			fastboot_tcp_start_server();
527 			break;
528 #endif
529 #if defined(CONFIG_CMD_DHCP)
530 		case DHCP:
531 			bootp_reset();
532 			net_ip.s_addr = 0;
533 			dhcp_request();		/* Basically same as BOOTP */
534 			break;
535 #endif
536 		case DHCP6:
537 			if (IS_ENABLED(CONFIG_CMD_DHCP6))
538 				dhcp6_start();
539 			break;
540 #if defined(CONFIG_CMD_BOOTP)
541 		case BOOTP:
542 			bootp_reset();
543 			net_ip.s_addr = 0;
544 			bootp_request();
545 			break;
546 #endif
547 #if defined(CONFIG_CMD_RARP)
548 		case RARP:
549 			rarp_try = 0;
550 			net_ip.s_addr = 0;
551 			rarp_request();
552 			break;
553 #endif
554 #if defined(CONFIG_CMD_PING)
555 		case PING:
556 			ping_start();
557 			break;
558 #endif
559 #if defined(CONFIG_CMD_PING6)
560 		case PING6:
561 			ping6_start();
562 			break;
563 #endif
564 #if defined(CONFIG_CMD_NFS) && !defined(CONFIG_XPL_BUILD)
565 		case NFS:
566 			nfs_start();
567 			break;
568 #endif
569 #if defined(CONFIG_CMD_WGET)
570 		case WGET:
571 			wget_start();
572 			break;
573 #endif
574 #if defined(CONFIG_CMD_CDP)
575 		case CDP:
576 			cdp_start();
577 			break;
578 #endif
579 #if defined(CONFIG_NETCONSOLE) && !defined(CONFIG_XPL_BUILD)
580 		case NETCONS:
581 			nc_start();
582 			break;
583 #endif
584 #if defined(CONFIG_DNS)
585 		case DNS:
586 			dns_start();
587 			break;
588 #endif
589 #if defined(CONFIG_CMD_LINK_LOCAL)
590 		case LINKLOCAL:
591 			link_local_start();
592 			break;
593 #endif
594 #if defined(CONFIG_CMD_WOL)
595 		case WOL:
596 			wol_start();
597 			break;
598 #endif
599 #if defined(CONFIG_PHY_NCSI)
600 		case NCSI:
601 			ncsi_probe_packages();
602 			break;
603 #endif
604 		case RS:
605 			if (IS_ENABLED(CONFIG_IPV6_ROUTER_DISCOVERY))
606 				ip6_send_rs();
607 			break;
608 		default:
609 			break;
610 		}
611 
612 		if (IS_ENABLED(CONFIG_PROT_UDP) && protocol == UDP)
613 			udp_start();
614 
615 		break;
616 	}
617 
618 #if defined(CONFIG_MII) || defined(CONFIG_CMD_MII)
619 #if	defined(CONFIG_SYS_FAULT_ECHO_LINK_DOWN)	&& \
620 	defined(CONFIG_LED_STATUS)			&& \
621 	defined(CONFIG_LED_STATUS_RED)
622 	/*
623 	 * Echo the inverted link state to the fault LED.
624 	 */
625 	if (miiphy_link(eth_get_dev()->name, CONFIG_SYS_FAULT_MII_ADDR))
626 		status_led_set(CONFIG_LED_STATUS_RED, CONFIG_LED_STATUS_OFF);
627 	else
628 		status_led_set(CONFIG_LED_STATUS_RED, CONFIG_LED_STATUS_ON);
629 #endif /* CONFIG_SYS_FAULT_ECHO_LINK_DOWN, ... */
630 #endif /* CONFIG_MII, ... */
631 #ifdef CONFIG_USB_KEYBOARD
632 	net_busy_flag = 1;
633 #endif
634 
635 	/*
636 	 *	Main packet reception loop.  Loop receiving packets until
637 	 *	someone sets `net_state' to a state that terminates.
638 	 */
639 	for (;;) {
640 		schedule();
641 		if (arp_timeout_check() > 0)
642 			time_start = get_timer(0);
643 
644 		if (IS_ENABLED(CONFIG_IPV6)) {
645 			if (use_ip6 && (ndisc_timeout_check() > 0))
646 				time_start = get_timer(0);
647 		}
648 
649 		/*
650 		 *	Check the ethernet for a new packet.  The ethernet
651 		 *	receive routine will process it.
652 		 *	Most drivers return the most recent packet size, but not
653 		 *	errors that may have happened.
654 		 */
655 		eth_rx();
656 #if defined(CONFIG_PROT_TCP)
657 		tcp_streams_poll();
658 #endif
659 
660 		/*
661 		 *	Abort if ctrl-c was pressed.
662 		 */
663 		if (ctrlc()) {
664 			/* cancel any ARP that may not have completed */
665 			net_arp_wait_packet_ip.s_addr = 0;
666 
667 			net_cleanup_loop();
668 			eth_halt();
669 			/* Invalidate the last protocol */
670 			eth_set_last_protocol(BOOTP);
671 
672 			/* Turn off activity LED if triggered */
673 			led_activity_off();
674 
675 			puts("\nAbort\n");
676 			/* include a debug print as well incase the debug
677 			   messages are directed to stderr */
678 			debug_cond(DEBUG_INT_STATE, "--- net_loop Abort!\n");
679 			ret = -EINTR;
680 			goto done;
681 		}
682 
683 		/*
684 		 *	Check for a timeout, and run the timeout handler
685 		 *	if we have one.
686 		 */
687 		if (time_handler &&
688 		    ((get_timer(0) - time_start) > time_delta)) {
689 			thand_f *x;
690 
691 #if defined(CONFIG_MII) || defined(CONFIG_CMD_MII)
692 #if	defined(CONFIG_SYS_FAULT_ECHO_LINK_DOWN)	&& \
693 	defined(CONFIG_LED_STATUS)			&& \
694 	defined(CONFIG_LED_STATUS_RED)
695 			/*
696 			 * Echo the inverted link state to the fault LED.
697 			 */
698 			if (miiphy_link(eth_get_dev()->name,
699 					CONFIG_SYS_FAULT_MII_ADDR))
700 				status_led_set(CONFIG_LED_STATUS_RED,
701 					       CONFIG_LED_STATUS_OFF);
702 			else
703 				status_led_set(CONFIG_LED_STATUS_RED,
704 					       CONFIG_LED_STATUS_ON);
705 #endif /* CONFIG_SYS_FAULT_ECHO_LINK_DOWN, ... */
706 #endif /* CONFIG_MII, ... */
707 			debug_cond(DEBUG_INT_STATE, "--- net_loop timeout\n");
708 			x = time_handler;
709 			time_handler = (thand_f *)0;
710 			(*x)();
711 		} else if (IS_ENABLED(CONFIG_IPV6_ROUTER_DISCOVERY))
712 			if (time_handler && protocol == RS)
713 				if (!ip6_is_unspecified_addr(&net_gateway6) &&
714 				    net_prefix_length != 0) {
715 					net_set_state(NETLOOP_SUCCESS);
716 					net_set_timeout_handler(0, NULL);
717 				}
718 
719 		if (net_state == NETLOOP_FAIL)
720 			ret = net_start_again();
721 
722 		switch (net_state) {
723 		case NETLOOP_RESTART:
724 			net_restarted = 1;
725 			goto restart;
726 
727 		case NETLOOP_SUCCESS:
728 			net_cleanup_loop();
729 			if (net_boot_file_size > 0) {
730 				printf("Bytes transferred = %u (%x hex)\n",
731 				       net_boot_file_size, net_boot_file_size);
732 				env_set_hex("filesize", net_boot_file_size);
733 				env_set_hex("fileaddr", image_load_addr);
734 			}
735 			if (protocol != NETCONS && protocol != NCSI)
736 				eth_halt();
737 			else
738 				eth_halt_state_only();
739 
740 			eth_set_last_protocol(protocol);
741 
742 			ret = net_boot_file_size;
743 			debug_cond(DEBUG_INT_STATE, "--- net_loop Success!\n");
744 			goto done;
745 
746 		case NETLOOP_FAIL:
747 			net_cleanup_loop();
748 			/* Invalidate the last protocol */
749 			eth_set_last_protocol(BOOTP);
750 			debug_cond(DEBUG_INT_STATE, "--- net_loop Fail!\n");
751 			ret = -ENONET;
752 			goto done;
753 
754 		case NETLOOP_CONTINUE:
755 			continue;
756 		}
757 	}
758 
759 done:
760 #ifdef CONFIG_USB_KEYBOARD
761 	net_busy_flag = 0;
762 #endif
763 #ifdef CONFIG_CMD_TFTPPUT
764 	/* Clear out the handlers */
765 	net_set_udp_handler(NULL);
766 	net_set_icmp_handler(NULL);
767 #endif
768 	net_set_state(prev_net_state);
769 
770 #if defined(CONFIG_CMD_PCAP)
771 	if (pcap_active())
772 		pcap_print_status();
773 #endif
774 	return ret;
775 }
776 
777 /**********************************************************************/
778 
start_again_timeout_handler(void)779 static void start_again_timeout_handler(void)
780 {
781 	net_set_state(NETLOOP_RESTART);
782 }
783 
net_start_again(void)784 int net_start_again(void)
785 {
786 	char *nretry;
787 	int retry_forever = 0;
788 	unsigned long retrycnt = 0;
789 	int ret;
790 
791 	nretry = env_get("netretry");
792 	if (nretry) {
793 		if (!strcmp(nretry, "yes"))
794 			retry_forever = 1;
795 		else if (!strcmp(nretry, "no"))
796 			retrycnt = 0;
797 		else if (!strcmp(nretry, "once"))
798 			retrycnt = 1;
799 		else
800 			retrycnt = simple_strtoul(nretry, NULL, 0);
801 	} else {
802 		retrycnt = 0;
803 		retry_forever = 0;
804 	}
805 
806 	if ((!retry_forever) && (net_try_count > retrycnt)) {
807 		eth_halt();
808 		net_set_state(NETLOOP_FAIL);
809 		/*
810 		 * We don't provide a way for the protocol to return an error,
811 		 * but this is almost always the reason.
812 		 */
813 		return -ETIMEDOUT;
814 	}
815 
816 	net_try_count++;
817 
818 	eth_halt();
819 #if !defined(CONFIG_NET_DO_NOT_TRY_ANOTHER)
820 	eth_try_another(!net_restarted);
821 #endif
822 	ret = eth_init();
823 	if (net_restart_wrap) {
824 		net_restart_wrap = 0;
825 		if (net_dev_exists) {
826 			net_set_timeout_handler(10000UL,
827 						start_again_timeout_handler);
828 			net_set_udp_handler(NULL);
829 		} else {
830 			net_set_state(NETLOOP_FAIL);
831 		}
832 	} else {
833 		net_set_state(NETLOOP_RESTART);
834 	}
835 	return ret;
836 }
837 
838 /**********************************************************************/
839 /*
840  *	Miscelaneous bits.
841  */
842 
dummy_handler(uchar * pkt,unsigned dport,struct in_addr sip,unsigned sport,unsigned len)843 static void dummy_handler(uchar *pkt, unsigned dport,
844 			struct in_addr sip, unsigned sport,
845 			unsigned len)
846 {
847 }
848 
net_get_udp_handler(void)849 rxhand_f *net_get_udp_handler(void)
850 {
851 	return udp_packet_handler;
852 }
853 
net_set_udp_handler(rxhand_f * f)854 void net_set_udp_handler(rxhand_f *f)
855 {
856 	debug_cond(DEBUG_INT_STATE, "--- net_loop UDP handler set (%p)\n", f);
857 	if (f == NULL)
858 		udp_packet_handler = dummy_handler;
859 	else
860 		udp_packet_handler = f;
861 }
862 
net_get_arp_handler(void)863 rxhand_f *net_get_arp_handler(void)
864 {
865 	return arp_packet_handler;
866 }
867 
net_set_arp_handler(rxhand_f * f)868 void net_set_arp_handler(rxhand_f *f)
869 {
870 	debug_cond(DEBUG_INT_STATE, "--- net_loop ARP handler set (%p)\n", f);
871 	if (f == NULL)
872 		arp_packet_handler = dummy_handler;
873 	else
874 		arp_packet_handler = f;
875 }
876 
877 #ifdef CONFIG_CMD_TFTPPUT
net_set_icmp_handler(rxhand_icmp_f * f)878 void net_set_icmp_handler(rxhand_icmp_f *f)
879 {
880 	packet_icmp_handler = f;
881 }
882 #endif
883 
net_set_timeout_handler(ulong iv,thand_f * f)884 void net_set_timeout_handler(ulong iv, thand_f *f)
885 {
886 	if (iv == 0) {
887 		debug_cond(DEBUG_INT_STATE,
888 			   "--- net_loop timeout handler cancelled\n");
889 		time_handler = (thand_f *)0;
890 	} else {
891 		debug_cond(DEBUG_INT_STATE,
892 			   "--- net_loop timeout handler set (%p)\n", f);
893 		time_handler = f;
894 		time_start = get_timer(0);
895 		time_delta = iv * CONFIG_SYS_HZ / 1000;
896 	}
897 }
898 
net_get_async_tx_pkt_buf(void)899 uchar *net_get_async_tx_pkt_buf(void)
900 {
901 	if (arp_is_waiting())
902 		return arp_tx_packet; /* If we are waiting, we already sent */
903 	else
904 		return net_tx_packet;
905 }
906 
net_send_udp_packet(uchar * ether,struct in_addr dest,int dport,int sport,int payload_len)907 int net_send_udp_packet(uchar *ether, struct in_addr dest, int dport, int sport,
908 		int payload_len)
909 {
910 	return net_send_ip_packet(ether, dest, dport, sport, payload_len,
911 				  IPPROTO_UDP, 0, 0, 0);
912 }
913 
914 #if defined(CONFIG_PROT_TCP)
net_send_tcp_packet(int payload_len,struct in_addr dhost,int dport,int sport,u8 action,u32 tcp_seq_num,u32 tcp_ack_num)915 int net_send_tcp_packet(int payload_len, struct in_addr dhost, int dport,
916 			int sport, u8 action, u32 tcp_seq_num, u32 tcp_ack_num)
917 {
918 	return net_send_ip_packet(net_server_ethaddr, dhost, dport,
919 				  sport, payload_len, IPPROTO_TCP, action,
920 				  tcp_seq_num, tcp_ack_num);
921 }
922 #endif
923 
net_send_ip_packet(uchar * ether,struct in_addr dest,int dport,int sport,int payload_len,int proto,u8 action,u32 tcp_seq_num,u32 tcp_ack_num)924 int net_send_ip_packet(uchar *ether, struct in_addr dest, int dport, int sport,
925 		       int payload_len, int proto, u8 action, u32 tcp_seq_num,
926 		       u32 tcp_ack_num)
927 {
928 	uchar *pkt;
929 	int eth_hdr_size;
930 	int pkt_hdr_size;
931 #if defined(CONFIG_PROT_TCP)
932 	struct tcp_stream *tcp;
933 #endif
934 
935 	/* make sure the net_tx_packet is initialized (net_init() was called) */
936 	assert(net_tx_packet != NULL);
937 	if (net_tx_packet == NULL)
938 		return -1;
939 
940 	/* convert to new style broadcast */
941 	if (dest.s_addr == 0)
942 		dest.s_addr = 0xFFFFFFFF;
943 
944 	/* if broadcast, make the ether address a broadcast and don't do ARP */
945 	if (dest.s_addr == 0xFFFFFFFF)
946 		ether = (uchar *)net_bcast_ethaddr;
947 
948 	pkt = (uchar *)net_tx_packet;
949 
950 	eth_hdr_size = net_set_ether(pkt, ether, PROT_IP);
951 
952 	switch (proto) {
953 	case IPPROTO_UDP:
954 		net_set_udp_header(pkt + eth_hdr_size, dest, dport, sport,
955 				   payload_len);
956 		pkt_hdr_size = eth_hdr_size + IP_UDP_HDR_SIZE;
957 		break;
958 #if defined(CONFIG_PROT_TCP)
959 	case IPPROTO_TCP:
960 		tcp = tcp_stream_get(0, dest, dport, sport);
961 		if (!tcp)
962 			return -EINVAL;
963 
964 		pkt_hdr_size = eth_hdr_size
965 			+ tcp_set_tcp_header(tcp, pkt + eth_hdr_size,
966 					     payload_len, action, tcp_seq_num,
967 					     tcp_ack_num);
968 		tcp_stream_put(tcp);
969 		break;
970 #endif
971 	default:
972 		return -EINVAL;
973 	}
974 
975 	/* if MAC address was not discovered yet, do an ARP request */
976 	if (memcmp(ether, net_null_ethaddr, 6) == 0) {
977 		debug_cond(DEBUG_DEV_PKT, "sending ARP for %pI4\n", &dest);
978 
979 		/* save the ip and eth addr for the packet to send after arp */
980 		net_arp_wait_packet_ip = dest;
981 		arp_wait_packet_ethaddr = ether;
982 
983 		/* size of the waiting packet */
984 		arp_wait_tx_packet_size = pkt_hdr_size + payload_len;
985 
986 		/* and do the ARP request */
987 		arp_wait_try = 1;
988 		arp_wait_timer_start = get_timer(0);
989 		arp_request();
990 		return 1;	/* waiting */
991 	} else {
992 		debug_cond(DEBUG_DEV_PKT, "sending UDP to %pI4/%pM\n",
993 			   &dest, ether);
994 		net_send_packet(net_tx_packet, pkt_hdr_size + payload_len);
995 		return 0;	/* transmitted */
996 	}
997 }
998 
999 #ifdef CONFIG_IP_DEFRAG
1000 /*
1001  * This function collects fragments in a single packet, according
1002  * to the algorithm in RFC815. It returns NULL or the pointer to
1003  * a complete packet, in static storage
1004  */
1005 #define IP_PKTSIZE (CONFIG_NET_MAXDEFRAG)
1006 
1007 #define IP_MAXUDP (IP_PKTSIZE - IP_HDR_SIZE)
1008 
1009 /*
1010  * this is the packet being assembled, either data or frag control.
1011  * Fragments go by 8 bytes, so this union must be 8 bytes long
1012  */
1013 struct hole {
1014 	/* first_byte is address of this structure */
1015 	u16 last_byte;	/* last byte in this hole + 1 (begin of next hole) */
1016 	u16 next_hole;	/* index of next (in 8-b blocks), 0 == none */
1017 	u16 prev_hole;	/* index of prev, 0 == none */
1018 	u16 unused;
1019 };
1020 
__net_defragment(struct ip_udp_hdr * ip,int * lenp)1021 static struct ip_udp_hdr *__net_defragment(struct ip_udp_hdr *ip, int *lenp)
1022 {
1023 	static uchar pkt_buff[IP_PKTSIZE] __aligned(PKTALIGN);
1024 	static u16 first_hole, total_len;
1025 	struct hole *payload, *thisfrag, *h, *newh;
1026 	struct ip_udp_hdr *localip = (struct ip_udp_hdr *)pkt_buff;
1027 	uchar *indata = (uchar *)ip;
1028 	int offset8, start, len, done = 0;
1029 	u16 ip_off = ntohs(ip->ip_off);
1030 
1031 	/*
1032 	 * Calling code already rejected <, but we don't have to deal
1033 	 * with an IP fragment with no payload.
1034 	 */
1035 	if (ntohs(ip->ip_len) <= IP_HDR_SIZE)
1036 		return NULL;
1037 
1038 	/* payload starts after IP header, this fragment is in there */
1039 	payload = (struct hole *)(pkt_buff + IP_HDR_SIZE);
1040 	offset8 =  (ip_off & IP_OFFS);
1041 	thisfrag = payload + offset8;
1042 	start = offset8 * 8;
1043 	len = ntohs(ip->ip_len) - IP_HDR_SIZE;
1044 
1045 	/* All but last fragment must have a multiple-of-8 payload. */
1046 	if ((len & 7) && (ip_off & IP_FLAGS_MFRAG))
1047 		return NULL;
1048 
1049 	if (start + len > IP_MAXUDP) /* fragment extends too far */
1050 		return NULL;
1051 
1052 	if (!total_len || localip->ip_id != ip->ip_id) {
1053 		/* new (or different) packet, reset structs */
1054 		total_len = 0xffff;
1055 		payload[0].last_byte = ~0;
1056 		payload[0].next_hole = 0;
1057 		payload[0].prev_hole = 0;
1058 		first_hole = 0;
1059 		/* any IP header will work, copy the first we received */
1060 		memcpy(localip, ip, IP_HDR_SIZE);
1061 	}
1062 
1063 	/*
1064 	 * What follows is the reassembly algorithm. We use the payload
1065 	 * array as a linked list of hole descriptors, as each hole starts
1066 	 * at a multiple of 8 bytes. However, last byte can be whatever value,
1067 	 * so it is represented as byte count, not as 8-byte blocks.
1068 	 */
1069 
1070 	h = payload + first_hole;
1071 	while (h->last_byte < start) {
1072 		if (!h->next_hole) {
1073 			/* no hole that far away */
1074 			return NULL;
1075 		}
1076 		h = payload + h->next_hole;
1077 	}
1078 
1079 	/* last fragment may be 1..7 bytes, the "+7" forces acceptance */
1080 	if (offset8 + ((len + 7) / 8) <= h - payload) {
1081 		/* no overlap with holes (dup fragment?) */
1082 		return NULL;
1083 	}
1084 
1085 	if (!(ip_off & IP_FLAGS_MFRAG)) {
1086 		/* no more fragmentss: truncate this (last) hole */
1087 		total_len = start + len;
1088 		h->last_byte = start + len;
1089 	}
1090 
1091 	/*
1092 	 * There is some overlap: fix the hole list. This code deals
1093 	 * with a fragment that overlaps with two different holes
1094 	 * (thus being a superset of a previously-received fragment)
1095 	 * by only using the part of the fragment that fits in the
1096 	 * first hole.
1097 	 */
1098 	if (h->last_byte < start + len)
1099 		len = h->last_byte - start;
1100 
1101 	if ((h >= thisfrag) && (h->last_byte <= start + len)) {
1102 		/* complete overlap with hole: remove hole */
1103 		if (!h->prev_hole && !h->next_hole) {
1104 			/* last remaining hole */
1105 			done = 1;
1106 		} else if (!h->prev_hole) {
1107 			/* first hole */
1108 			first_hole = h->next_hole;
1109 			payload[h->next_hole].prev_hole = 0;
1110 		} else if (!h->next_hole) {
1111 			/* last hole */
1112 			payload[h->prev_hole].next_hole = 0;
1113 		} else {
1114 			/* in the middle of the list */
1115 			payload[h->next_hole].prev_hole = h->prev_hole;
1116 			payload[h->prev_hole].next_hole = h->next_hole;
1117 		}
1118 
1119 	} else if (h->last_byte <= start + len) {
1120 		/* overlaps with final part of the hole: shorten this hole */
1121 		h->last_byte = start;
1122 
1123 	} else if (h >= thisfrag) {
1124 		/* overlaps with initial part of the hole: move this hole */
1125 		newh = thisfrag + (len / 8);
1126 		*newh = *h;
1127 		h = newh;
1128 		if (h->next_hole)
1129 			payload[h->next_hole].prev_hole = (h - payload);
1130 		if (h->prev_hole)
1131 			payload[h->prev_hole].next_hole = (h - payload);
1132 		else
1133 			first_hole = (h - payload);
1134 
1135 	} else {
1136 		/* fragment sits in the middle: split the hole */
1137 		newh = thisfrag + (len / 8);
1138 		*newh = *h;
1139 		h->last_byte = start;
1140 		h->next_hole = (newh - payload);
1141 		newh->prev_hole = (h - payload);
1142 		if (newh->next_hole)
1143 			payload[newh->next_hole].prev_hole = (newh - payload);
1144 	}
1145 
1146 	/* finally copy this fragment and possibly return whole packet */
1147 	memcpy((uchar *)thisfrag, indata + IP_HDR_SIZE, len);
1148 	if (!done)
1149 		return NULL;
1150 
1151 	*lenp = total_len + IP_HDR_SIZE;
1152 	localip->ip_len = htons(*lenp);
1153 	return localip;
1154 }
1155 
net_defragment(struct ip_udp_hdr * ip,int * lenp)1156 static inline struct ip_udp_hdr *net_defragment(struct ip_udp_hdr *ip,
1157 	int *lenp)
1158 {
1159 	u16 ip_off = ntohs(ip->ip_off);
1160 	if (!(ip_off & (IP_OFFS | IP_FLAGS_MFRAG)))
1161 		return ip; /* not a fragment */
1162 	return __net_defragment(ip, lenp);
1163 }
1164 
1165 #else /* !CONFIG_IP_DEFRAG */
1166 
net_defragment(struct ip_udp_hdr * ip,int * lenp)1167 static inline struct ip_udp_hdr *net_defragment(struct ip_udp_hdr *ip,
1168 	int *lenp)
1169 {
1170 	u16 ip_off = ntohs(ip->ip_off);
1171 	if (!(ip_off & (IP_OFFS | IP_FLAGS_MFRAG)))
1172 		return ip; /* not a fragment */
1173 	return NULL;
1174 }
1175 #endif
1176 
1177 /**
1178  * Receive an ICMP packet. We deal with REDIRECT and PING here, and silently
1179  * drop others.
1180  *
1181  * @parma ip	IP packet containing the ICMP
1182  */
receive_icmp(struct ip_udp_hdr * ip,int len,struct in_addr src_ip,struct ethernet_hdr * et)1183 static void receive_icmp(struct ip_udp_hdr *ip, int len,
1184 			struct in_addr src_ip, struct ethernet_hdr *et)
1185 {
1186 	struct icmp_hdr *icmph = (struct icmp_hdr *)&ip->udp_src;
1187 
1188 	switch (icmph->type) {
1189 	case ICMP_REDIRECT:
1190 		if (icmph->code != ICMP_REDIR_HOST)
1191 			return;
1192 		printf(" ICMP Host Redirect to %pI4 ",
1193 		       &icmph->un.gateway);
1194 		break;
1195 	default:
1196 #if defined(CONFIG_CMD_PING)
1197 		ping_receive(et, ip, len);
1198 #endif
1199 #ifdef CONFIG_CMD_TFTPPUT
1200 		if (packet_icmp_handler)
1201 			packet_icmp_handler(icmph->type, icmph->code,
1202 					    ntohs(ip->udp_dst), src_ip,
1203 					    ntohs(ip->udp_src), icmph->un.data,
1204 					    ntohs(ip->udp_len));
1205 #endif
1206 		break;
1207 	}
1208 }
1209 
net_process_received_packet(uchar * in_packet,int len)1210 void net_process_received_packet(uchar *in_packet, int len)
1211 {
1212 	struct ethernet_hdr *et;
1213 	struct ip_udp_hdr *ip;
1214 	struct in_addr dst_ip;
1215 	struct in_addr src_ip;
1216 	int eth_proto;
1217 #if defined(CONFIG_CMD_CDP)
1218 	int iscdp;
1219 #endif
1220 	ushort cti = 0, vlanid = VLAN_NONE, myvlanid, mynvlanid;
1221 
1222 	debug_cond(DEBUG_NET_PKT, "packet received\n");
1223 	if (DEBUG_NET_PKT_TRACE)
1224 		print_hex_dump_bytes("rx: ", DUMP_PREFIX_OFFSET, in_packet,
1225 				     len);
1226 
1227 #if defined(CONFIG_CMD_PCAP)
1228 	pcap_post(in_packet, len, false);
1229 #endif
1230 	net_rx_packet = in_packet;
1231 	net_rx_packet_len = len;
1232 	et = (struct ethernet_hdr *)in_packet;
1233 
1234 	/* too small packet? */
1235 	if (len < ETHER_HDR_SIZE)
1236 		return;
1237 
1238 #if defined(CONFIG_API) || defined(CONFIG_EFI_LOADER)
1239 	if (push_packet) {
1240 		(*push_packet)(in_packet, len);
1241 		return;
1242 	}
1243 #endif
1244 
1245 #if defined(CONFIG_CMD_CDP)
1246 	/* keep track if packet is CDP */
1247 	iscdp = is_cdp_packet(et->et_dest);
1248 #endif
1249 
1250 	myvlanid = ntohs(net_our_vlan);
1251 	if (myvlanid == (ushort)-1)
1252 		myvlanid = VLAN_NONE;
1253 	mynvlanid = ntohs(net_native_vlan);
1254 	if (mynvlanid == (ushort)-1)
1255 		mynvlanid = VLAN_NONE;
1256 
1257 	eth_proto = ntohs(et->et_protlen);
1258 
1259 	if (eth_proto < 1514) {
1260 		struct e802_hdr *et802 = (struct e802_hdr *)et;
1261 		/*
1262 		 *	Got a 802.2 packet.  Check the other protocol field.
1263 		 *	XXX VLAN over 802.2+SNAP not implemented!
1264 		 */
1265 		eth_proto = ntohs(et802->et_prot);
1266 
1267 		ip = (struct ip_udp_hdr *)(in_packet + E802_HDR_SIZE);
1268 		len -= E802_HDR_SIZE;
1269 
1270 	} else if (eth_proto != PROT_VLAN) {	/* normal packet */
1271 		ip = (struct ip_udp_hdr *)(in_packet + ETHER_HDR_SIZE);
1272 		len -= ETHER_HDR_SIZE;
1273 
1274 	} else {			/* VLAN packet */
1275 		struct vlan_ethernet_hdr *vet =
1276 			(struct vlan_ethernet_hdr *)et;
1277 
1278 		debug_cond(DEBUG_NET_PKT, "VLAN packet received\n");
1279 
1280 		/* too small packet? */
1281 		if (len < VLAN_ETHER_HDR_SIZE)
1282 			return;
1283 
1284 		/* if no VLAN active */
1285 		if ((ntohs(net_our_vlan) & VLAN_IDMASK) == VLAN_NONE
1286 #if defined(CONFIG_CMD_CDP)
1287 				&& iscdp == 0
1288 #endif
1289 				)
1290 			return;
1291 
1292 		cti = ntohs(vet->vet_tag);
1293 		vlanid = cti & VLAN_IDMASK;
1294 		eth_proto = ntohs(vet->vet_type);
1295 
1296 		ip = (struct ip_udp_hdr *)(in_packet + VLAN_ETHER_HDR_SIZE);
1297 		len -= VLAN_ETHER_HDR_SIZE;
1298 	}
1299 
1300 	debug_cond(DEBUG_NET_PKT, "Receive from protocol 0x%x\n", eth_proto);
1301 
1302 #if defined(CONFIG_CMD_CDP)
1303 	if (iscdp) {
1304 		cdp_receive((uchar *)ip, len);
1305 		return;
1306 	}
1307 #endif
1308 
1309 	if ((myvlanid & VLAN_IDMASK) != VLAN_NONE) {
1310 		if (vlanid == VLAN_NONE)
1311 			vlanid = (mynvlanid & VLAN_IDMASK);
1312 		/* not matched? */
1313 		if (vlanid != (myvlanid & VLAN_IDMASK))
1314 			return;
1315 	}
1316 
1317 	switch (eth_proto) {
1318 	case PROT_ARP:
1319 		arp_receive(et, ip, len);
1320 		break;
1321 
1322 #ifdef CONFIG_CMD_RARP
1323 	case PROT_RARP:
1324 		rarp_receive(ip, len);
1325 		break;
1326 #endif
1327 #if IS_ENABLED(CONFIG_IPV6)
1328 	case PROT_IP6:
1329 		net_ip6_handler(et, (struct ip6_hdr *)ip, len);
1330 		break;
1331 #endif
1332 	case PROT_IP:
1333 		debug_cond(DEBUG_NET_PKT, "Got IP\n");
1334 		/* Before we start poking the header, make sure it is there */
1335 		if (len < IP_HDR_SIZE) {
1336 			debug("len bad %d < %lu\n", len,
1337 			      (ulong)IP_HDR_SIZE);
1338 			return;
1339 		}
1340 		/* Check the packet length */
1341 		if (len < ntohs(ip->ip_len)) {
1342 			debug("len bad %d < %d\n", len, ntohs(ip->ip_len));
1343 			return;
1344 		}
1345 		len = ntohs(ip->ip_len);
1346 		if (len < IP_HDR_SIZE) {
1347 			debug("bad ip->ip_len %d < %d\n", len, (int)IP_HDR_SIZE);
1348 			return;
1349 		}
1350 		debug_cond(DEBUG_NET_PKT, "len=%d, v=%02x\n",
1351 			   len, ip->ip_hl_v & 0xff);
1352 
1353 		/* Can't deal with anything except IPv4 */
1354 		if ((ip->ip_hl_v & 0xf0) != 0x40)
1355 			return;
1356 		/* Can't deal with IP options (headers != 20 bytes) */
1357 		if ((ip->ip_hl_v & 0x0f) != 0x05)
1358 			return;
1359 		/* Check the Checksum of the header */
1360 		if (!ip_checksum_ok((uchar *)ip, IP_HDR_SIZE)) {
1361 			debug("checksum bad\n");
1362 			return;
1363 		}
1364 		/* If it is not for us, ignore it */
1365 		dst_ip = net_read_ip(&ip->ip_dst);
1366 		if (net_ip.s_addr && dst_ip.s_addr != net_ip.s_addr &&
1367 		    dst_ip.s_addr != 0xFFFFFFFF) {
1368 				return;
1369 		}
1370 		/* Read source IP address for later use */
1371 		src_ip = net_read_ip(&ip->ip_src);
1372 		/*
1373 		 * The function returns the unchanged packet if it's not
1374 		 * a fragment, and either the complete packet or NULL if
1375 		 * it is a fragment (if !CONFIG_IP_DEFRAG, it returns NULL)
1376 		 */
1377 		ip = net_defragment(ip, &len);
1378 		if (!ip)
1379 			return;
1380 		/*
1381 		 * watch for ICMP host redirects
1382 		 *
1383 		 * There is no real handler code (yet). We just watch
1384 		 * for ICMP host redirect messages. In case anybody
1385 		 * sees these messages: please contact me
1386 		 * (wd@denx.de), or - even better - send me the
1387 		 * necessary fixes :-)
1388 		 *
1389 		 * Note: in all cases where I have seen this so far
1390 		 * it was a problem with the router configuration,
1391 		 * for instance when a router was configured in the
1392 		 * BOOTP reply, but the TFTP server was on the same
1393 		 * subnet. So this is probably a warning that your
1394 		 * configuration might be wrong. But I'm not really
1395 		 * sure if there aren't any other situations.
1396 		 *
1397 		 * Simon Glass <sjg@chromium.org>: We get an ICMP when
1398 		 * we send a tftp packet to a dead connection, or when
1399 		 * there is no server at the other end.
1400 		 */
1401 		if (ip->ip_p == IPPROTO_ICMP) {
1402 			receive_icmp(ip, len, src_ip, et);
1403 			return;
1404 #if defined(CONFIG_PROT_TCP)
1405 		} else if (ip->ip_p == IPPROTO_TCP) {
1406 			debug_cond(DEBUG_DEV_PKT,
1407 				   "TCP PH (to=%pI4, from=%pI4, len=%d)\n",
1408 				   &dst_ip, &src_ip, len);
1409 
1410 			rxhand_tcp_f((union tcp_build_pkt *)ip, len);
1411 			return;
1412 #endif
1413 		} else if (ip->ip_p != IPPROTO_UDP) {	/* Only UDP packets */
1414 			return;
1415 		}
1416 
1417 		if (ntohs(ip->udp_len) < UDP_HDR_SIZE || ntohs(ip->udp_len) > len - IP_HDR_SIZE)
1418 			return;
1419 
1420 		debug_cond(DEBUG_DEV_PKT,
1421 			   "received UDP (to=%pI4, from=%pI4, len=%d)\n",
1422 			   &dst_ip, &src_ip, len);
1423 
1424 		if (IS_ENABLED(CONFIG_UDP_CHECKSUM) && ip->udp_xsum != 0) {
1425 			ulong   xsum;
1426 			u8 *sumptr;
1427 			ushort  sumlen;
1428 
1429 			xsum  = ip->ip_p;
1430 			xsum += (ntohs(ip->udp_len));
1431 			xsum += (ntohl(ip->ip_src.s_addr) >> 16) & 0x0000ffff;
1432 			xsum += (ntohl(ip->ip_src.s_addr) >>  0) & 0x0000ffff;
1433 			xsum += (ntohl(ip->ip_dst.s_addr) >> 16) & 0x0000ffff;
1434 			xsum += (ntohl(ip->ip_dst.s_addr) >>  0) & 0x0000ffff;
1435 
1436 			sumlen = ntohs(ip->udp_len);
1437 			sumptr = (u8 *)&ip->udp_src;
1438 
1439 			while (sumlen > 1) {
1440 				/* inlined ntohs() to avoid alignment errors */
1441 				xsum += (sumptr[0] << 8) + sumptr[1];
1442 				sumptr += 2;
1443 				sumlen -= 2;
1444 			}
1445 			if (sumlen > 0)
1446 				xsum += (sumptr[0] << 8) + sumptr[0];
1447 			while ((xsum >> 16) != 0) {
1448 				xsum = (xsum & 0x0000ffff) +
1449 				       ((xsum >> 16) & 0x0000ffff);
1450 			}
1451 			if ((xsum != 0x00000000) && (xsum != 0x0000ffff)) {
1452 				printf(" UDP wrong checksum %08lx %08x\n",
1453 				       xsum, ntohs(ip->udp_xsum));
1454 				return;
1455 			}
1456 		}
1457 
1458 #if defined(CONFIG_NETCONSOLE) && !defined(CONFIG_XPL_BUILD)
1459 		nc_input_packet((uchar *)ip + IP_UDP_HDR_SIZE,
1460 				src_ip,
1461 				ntohs(ip->udp_dst),
1462 				ntohs(ip->udp_src),
1463 				ntohs(ip->udp_len) - UDP_HDR_SIZE);
1464 #endif
1465 		/*
1466 		 * IP header OK.  Pass the packet to the current handler.
1467 		 */
1468 		(*udp_packet_handler)((uchar *)ip + IP_UDP_HDR_SIZE,
1469 				      ntohs(ip->udp_dst),
1470 				      src_ip,
1471 				      ntohs(ip->udp_src),
1472 				      ntohs(ip->udp_len) - UDP_HDR_SIZE);
1473 		break;
1474 #ifdef CONFIG_CMD_WOL
1475 	case PROT_WOL:
1476 		wol_receive(ip, len);
1477 		break;
1478 #endif
1479 #ifdef CONFIG_PHY_NCSI
1480 	case PROT_NCSI:
1481 		ncsi_receive(et, ip, len);
1482 		break;
1483 #endif
1484 	}
1485 }
1486 
1487 /**********************************************************************/
1488 
net_check_prereq(enum proto_t protocol)1489 static int net_check_prereq(enum proto_t protocol)
1490 {
1491 	switch (protocol) {
1492 		/* Fall through */
1493 #if defined(CONFIG_CMD_PING)
1494 	case PING:
1495 		if (net_ping_ip.s_addr == 0) {
1496 			puts("*** ERROR: ping address not given\n");
1497 			return 1;
1498 		}
1499 		goto common;
1500 #endif
1501 #if defined(CONFIG_CMD_PING6)
1502 	case PING6:
1503 		if (ip6_is_unspecified_addr(&net_ping_ip6)) {
1504 			puts("*** ERROR: ping address not given\n");
1505 			return 1;
1506 		}
1507 		goto common;
1508 #endif
1509 #if defined(CONFIG_DNS)
1510 	case DNS:
1511 		if (net_dns_server.s_addr == 0) {
1512 			puts("*** ERROR: DNS server address not given\n");
1513 			return 1;
1514 		}
1515 		goto common;
1516 #endif
1517 #if defined(CONFIG_PROT_UDP)
1518 	case UDP:
1519 		if (udp_prereq())
1520 			return 1;
1521 		goto common;
1522 #endif
1523 
1524 #if defined(CONFIG_CMD_NFS)
1525 	case NFS:
1526 #endif
1527 		/* Fall through */
1528 	case TFTPGET:
1529 	case TFTPPUT:
1530 		if (IS_ENABLED(CONFIG_IPV6) && use_ip6) {
1531 			if (!memcmp(&net_server_ip6, &net_null_addr_ip6,
1532 				    sizeof(struct in6_addr)) &&
1533 				    !strchr(net_boot_file_name, '[')) {
1534 				puts("*** ERROR: `serverip6' not set\n");
1535 				return 1;
1536 			}
1537 		} else if (net_server_ip.s_addr == 0 && !is_serverip_in_cmd()) {
1538 			puts("*** ERROR: `serverip' not set\n");
1539 			return 1;
1540 		}
1541 #if	defined(CONFIG_CMD_PING) || \
1542 	defined(CONFIG_DNS) || defined(CONFIG_PROT_UDP)
1543 common:
1544 #endif
1545 		/* Fall through */
1546 
1547 	case NETCONS:
1548 	case FASTBOOT_UDP:
1549 	case FASTBOOT_TCP:
1550 	case TFTPSRV:
1551 		if (IS_ENABLED(CONFIG_IPV6) && use_ip6) {
1552 			if (!memcmp(&net_link_local_ip6, &net_null_addr_ip6,
1553 				    sizeof(struct in6_addr))) {
1554 				puts("*** ERROR: `ip6addr` not set\n");
1555 				return 1;
1556 			}
1557 		} else if (net_ip.s_addr == 0) {
1558 			puts("*** ERROR: `ipaddr' not set\n");
1559 			return 1;
1560 		}
1561 		fallthrough;
1562 
1563 #ifdef CONFIG_CMD_RARP
1564 	case RARP:
1565 #endif
1566 #ifdef CONFIG_PHY_NCSI
1567 	case NCSI:
1568 #endif
1569 	case BOOTP:
1570 	case CDP:
1571 	case DHCP:
1572 	case LINKLOCAL:
1573 		if (memcmp(net_ethaddr, "\0\0\0\0\0\0", 6) == 0) {
1574 			int num = eth_get_dev_index();
1575 
1576 			switch (num) {
1577 			case -1:
1578 				puts("*** ERROR: No ethernet found.\n");
1579 				return 1;
1580 			case 0:
1581 				puts("*** ERROR: `ethaddr' not set\n");
1582 				break;
1583 			default:
1584 				printf("*** ERROR: `eth%daddr' not set\n",
1585 				       num);
1586 				break;
1587 			}
1588 
1589 			net_start_again();
1590 			return 2;
1591 		}
1592 		/* Fall through */
1593 	default:
1594 		return 0;
1595 	}
1596 	return 0;		/* OK */
1597 }
1598 /**********************************************************************/
1599 
1600 int
net_eth_hdr_size(void)1601 net_eth_hdr_size(void)
1602 {
1603 	ushort myvlanid;
1604 
1605 	myvlanid = ntohs(net_our_vlan);
1606 	if (myvlanid == (ushort)-1)
1607 		myvlanid = VLAN_NONE;
1608 
1609 	return ((myvlanid & VLAN_IDMASK) == VLAN_NONE) ? ETHER_HDR_SIZE :
1610 		VLAN_ETHER_HDR_SIZE;
1611 }
1612 
net_set_ether(uchar * xet,const uchar * dest_ethaddr,uint prot)1613 int net_set_ether(uchar *xet, const uchar *dest_ethaddr, uint prot)
1614 {
1615 	struct ethernet_hdr *et = (struct ethernet_hdr *)xet;
1616 	ushort myvlanid;
1617 
1618 	myvlanid = ntohs(net_our_vlan);
1619 	if (myvlanid == (ushort)-1)
1620 		myvlanid = VLAN_NONE;
1621 
1622 	memcpy(et->et_dest, dest_ethaddr, 6);
1623 	memcpy(et->et_src, net_ethaddr, 6);
1624 	if ((myvlanid & VLAN_IDMASK) == VLAN_NONE) {
1625 		et->et_protlen = htons(prot);
1626 		return ETHER_HDR_SIZE;
1627 	} else {
1628 		struct vlan_ethernet_hdr *vet =
1629 			(struct vlan_ethernet_hdr *)xet;
1630 
1631 		vet->vet_vlan_type = htons(PROT_VLAN);
1632 		vet->vet_tag = htons((0 << 5) | (myvlanid & VLAN_IDMASK));
1633 		vet->vet_type = htons(prot);
1634 		return VLAN_ETHER_HDR_SIZE;
1635 	}
1636 }
1637 
net_update_ether(struct ethernet_hdr * et,uchar * addr,uint prot)1638 int net_update_ether(struct ethernet_hdr *et, uchar *addr, uint prot)
1639 {
1640 	ushort protlen;
1641 
1642 	memcpy(et->et_dest, addr, 6);
1643 	memcpy(et->et_src, net_ethaddr, 6);
1644 	protlen = ntohs(et->et_protlen);
1645 	if (protlen == PROT_VLAN) {
1646 		struct vlan_ethernet_hdr *vet =
1647 			(struct vlan_ethernet_hdr *)et;
1648 		vet->vet_type = htons(prot);
1649 		return VLAN_ETHER_HDR_SIZE;
1650 	} else if (protlen > 1514) {
1651 		et->et_protlen = htons(prot);
1652 		return ETHER_HDR_SIZE;
1653 	} else {
1654 		/* 802.2 + SNAP */
1655 		struct e802_hdr *et802 = (struct e802_hdr *)et;
1656 		et802->et_prot = htons(prot);
1657 		return E802_HDR_SIZE;
1658 	}
1659 }
1660 
net_set_ip_header(uchar * pkt,struct in_addr dest,struct in_addr source,u16 pkt_len,u8 proto)1661 void net_set_ip_header(uchar *pkt, struct in_addr dest, struct in_addr source,
1662 		       u16 pkt_len, u8 proto)
1663 {
1664 	struct ip_udp_hdr *ip = (struct ip_udp_hdr *)pkt;
1665 
1666 	/*
1667 	 *	Construct an IP header.
1668 	 */
1669 	/* IP_HDR_SIZE / 4 (not including UDP) */
1670 	ip->ip_hl_v  = 0x45;
1671 	ip->ip_tos   = 0;
1672 	ip->ip_len   = htons(pkt_len);
1673 	ip->ip_p     = proto;
1674 	ip->ip_id    = htons(net_ip_id++);
1675 	ip->ip_off   = htons(IP_FLAGS_DFRAG);	/* Don't fragment */
1676 	ip->ip_ttl   = 255;
1677 	ip->ip_sum   = 0;
1678 	/* already in network byte order */
1679 	net_copy_ip((void *)&ip->ip_src, &source);
1680 	/* already in network byte order */
1681 	net_copy_ip((void *)&ip->ip_dst, &dest);
1682 
1683 	ip->ip_sum   = compute_ip_checksum(ip, IP_HDR_SIZE);
1684 }
1685 
net_set_udp_header(uchar * pkt,struct in_addr dest,int dport,int sport,int len)1686 void net_set_udp_header(uchar *pkt, struct in_addr dest, int dport, int sport,
1687 			int len)
1688 {
1689 	struct ip_udp_hdr *ip = (struct ip_udp_hdr *)pkt;
1690 
1691 	/*
1692 	 *	If the data is an odd number of bytes, zero the
1693 	 *	byte after the last byte so that the checksum
1694 	 *	will work.
1695 	 */
1696 	if (len & 1)
1697 		pkt[IP_UDP_HDR_SIZE + len] = 0;
1698 
1699 	net_set_ip_header(pkt, dest, net_ip, IP_UDP_HDR_SIZE + len,
1700 			  IPPROTO_UDP);
1701 
1702 	ip->udp_src  = htons(sport);
1703 	ip->udp_dst  = htons(dport);
1704 	ip->udp_len  = htons(UDP_HDR_SIZE + len);
1705 	ip->udp_xsum = 0;
1706 }
1707 
is_serverip_in_cmd(void)1708 int is_serverip_in_cmd(void)
1709 {
1710 	return !!strchr(net_boot_file_name, ':');
1711 }
1712 
net_parse_bootfile(struct in_addr * ipaddr,char * filename,int max_len)1713 int net_parse_bootfile(struct in_addr *ipaddr, char *filename, int max_len)
1714 {
1715 	char *colon;
1716 	struct in_addr ip;
1717 	ip.s_addr = 0;
1718 
1719 	if (net_boot_file_name[0] == '\0')
1720 		return 0;
1721 
1722 	colon = strchr(net_boot_file_name, ':');
1723 	if (colon) {
1724 		ip = string_to_ip(net_boot_file_name);
1725 		if (ipaddr && ip.s_addr)
1726 			*ipaddr = ip;
1727 	}
1728 	if (ip.s_addr) {
1729 		strncpy(filename, colon + 1, max_len);
1730 	} else {
1731 		strncpy(filename, net_boot_file_name, max_len);
1732 	}
1733 	filename[max_len - 1] = '\0';
1734 
1735 	return 1;
1736 }
1737 
vlan_to_string(ushort x,char * s)1738 void vlan_to_string(ushort x, char *s)
1739 {
1740 	x = ntohs(x);
1741 
1742 	if (x == (ushort)-1)
1743 		x = VLAN_NONE;
1744 
1745 	if (x == VLAN_NONE)
1746 		strcpy(s, "none");
1747 	else
1748 		sprintf(s, "%d", x & VLAN_IDMASK);
1749 }
1750 
string_to_vlan(const char * s)1751 ushort string_to_vlan(const char *s)
1752 {
1753 	ushort id;
1754 
1755 	if (s == NULL)
1756 		return htons(VLAN_NONE);
1757 
1758 	if (*s < '0' || *s > '9')
1759 		id = VLAN_NONE;
1760 	else
1761 		id = (ushort)dectoul(s, NULL);
1762 
1763 	return htons(id);
1764 }
1765 
env_get_vlan(char * var)1766 ushort env_get_vlan(char *var)
1767 {
1768 	return string_to_vlan(env_get(var));
1769 }
1770