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