]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - net/net.c
env: Use getenv_yesno() more generally
[karo-tx-uboot.git] / net / net.c
1 /*
2  *      Copied from Linux Monitor (LiMon) - Networking.
3  *
4  *      Copyright 1994 - 2000 Neil Russell.
5  *      (See License)
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  * LINK_LOCAL:
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  * SNTP:
75  *
76  *      Prerequisites:  - own ethernet address
77  *                      - own IP address
78  *      We want:        - network time
79  *      Next step:      none
80  */
81
82
83 #include <common.h>
84 #include <command.h>
85 #include <net.h>
86 #if defined(CONFIG_STATUS_LED)
87 #include <miiphy.h>
88 #include <status_led.h>
89 #endif
90 #include <watchdog.h>
91 #include <linux/compiler.h>
92 #include "arp.h"
93 #include "bootp.h"
94 #include "cdp.h"
95 #if defined(CONFIG_CMD_DNS)
96 #include "dns.h"
97 #endif
98 #include "link_local.h"
99 #include "nfs.h"
100 #include "ping.h"
101 #include "rarp.h"
102 #if defined(CONFIG_CMD_SNTP)
103 #include "sntp.h"
104 #endif
105 #include "tftp.h"
106
107 DECLARE_GLOBAL_DATA_PTR;
108
109 /** BOOTP EXTENTIONS **/
110
111 /* Our subnet mask (0=unknown) */
112 IPaddr_t        NetOurSubnetMask;
113 /* Our gateways IP address */
114 IPaddr_t        NetOurGatewayIP;
115 /* Our DNS IP address */
116 IPaddr_t        NetOurDNSIP;
117 #if defined(CONFIG_BOOTP_DNS2)
118 /* Our 2nd DNS IP address */
119 IPaddr_t        NetOurDNS2IP;
120 #endif
121 /* Our NIS domain */
122 char            NetOurNISDomain[32] = {0,};
123 /* Our hostname */
124 char            NetOurHostName[32] = {0,};
125 /* Our bootpath */
126 char            NetOurRootPath[64] = {0,};
127 /* Our bootfile size in blocks */
128 ushort          NetBootFileSize;
129
130 #ifdef CONFIG_MCAST_TFTP        /* Multicast TFTP */
131 IPaddr_t Mcast_addr;
132 #endif
133
134 /** END OF BOOTP EXTENTIONS **/
135
136 /* The actual transferred size of the bootfile (in bytes) */
137 ulong           NetBootFileXferSize;
138 /* Our ethernet address */
139 uchar           NetOurEther[6];
140 /* Boot server enet address */
141 uchar           NetServerEther[6];
142 /* Our IP addr (0 = unknown) */
143 IPaddr_t        NetOurIP;
144 /* Server IP addr (0 = unknown) */
145 IPaddr_t        NetServerIP;
146 /* Current receive packet */
147 uchar *NetRxPacket;
148 /* Current rx packet length */
149 int             NetRxPacketLen;
150 /* IP packet ID */
151 unsigned        NetIPID;
152 /* Ethernet bcast address */
153 uchar           NetBcastAddr[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
154 uchar           NetEtherNullAddr[6];
155 #ifdef CONFIG_API
156 void            (*push_packet)(void *, int len) = 0;
157 #endif
158 /* Network loop state */
159 enum net_loop_state net_state;
160 /* Tried all network devices */
161 int             NetRestartWrap;
162 /* Network loop restarted */
163 static int      NetRestarted;
164 /* At least one device configured */
165 static int      NetDevExists;
166
167 /* XXX in both little & big endian machines 0xFFFF == ntohs(-1) */
168 /* default is without VLAN */
169 ushort          NetOurVLAN = 0xFFFF;
170 /* ditto */
171 ushort          NetOurNativeVLAN = 0xFFFF;
172
173 /* Boot File name */
174 char            BootFile[128];
175
176 #if defined(CONFIG_CMD_SNTP)
177 /* NTP server IP address */
178 IPaddr_t        NetNtpServerIP;
179 /* offset time from UTC */
180 int             NetTimeOffset;
181 #endif
182
183 static uchar PktBuf[(PKTBUFSRX+1) * PKTSIZE_ALIGN + PKTALIGN];
184
185 /* Receive packet */
186 uchar *NetRxPackets[PKTBUFSRX];
187
188 /* Current UDP RX packet handler */
189 static rxhand_f *udp_packet_handler;
190 /* Current ARP RX packet handler */
191 static rxhand_f *arp_packet_handler;
192 #ifdef CONFIG_CMD_TFTPPUT
193 /* Current ICMP rx handler */
194 static rxhand_icmp_f *packet_icmp_handler;
195 #endif
196 /* Current timeout handler */
197 static thand_f *timeHandler;
198 /* Time base value */
199 static ulong    timeStart;
200 /* Current timeout value */
201 static ulong    timeDelta;
202 /* THE transmit packet */
203 uchar *NetTxPacket;
204
205 static int net_check_prereq(enum proto_t protocol);
206
207 static int NetTryCount;
208
209 /**********************************************************************/
210
211 /*
212  * Check if autoload is enabled. If so, use either NFS or TFTP to download
213  * the boot file.
214  */
215 void net_auto_load(void)
216 {
217 #if defined(CONFIG_CMD_NFS)
218         const char *s = getenv("autoload");
219
220         if (s != NULL && strcmp(s, "NFS") == 0) {
221                 /*
222                  * Use NFS to load the bootfile.
223                  */
224                 NfsStart();
225                 return;
226         }
227 #endif
228         if (getenv_yesno("autoload") == 0) {
229                 /*
230                  * Just use BOOTP/RARP to configure system;
231                  * Do not use TFTP to load the bootfile.
232                  */
233                 net_set_state(NETLOOP_SUCCESS);
234                 return;
235         }
236         TftpStart(TFTPGET);
237 }
238
239 static void NetInitLoop(void)
240 {
241         static int env_changed_id;
242         int env_id = get_env_id();
243
244         /* update only when the environment has changed */
245         if (env_changed_id != env_id) {
246                 NetOurIP = getenv_IPaddr("ipaddr");
247                 NetOurGatewayIP = getenv_IPaddr("gatewayip");
248                 NetOurSubnetMask = getenv_IPaddr("netmask");
249                 NetServerIP = getenv_IPaddr("serverip");
250                 NetOurNativeVLAN = getenv_VLAN("nvlan");
251                 NetOurVLAN = getenv_VLAN("vlan");
252 #if defined(CONFIG_CMD_DNS)
253                 NetOurDNSIP = getenv_IPaddr("dnsip");
254 #endif
255                 env_changed_id = env_id;
256         }
257         memcpy(NetOurEther, eth_get_dev()->enetaddr, 6);
258
259         return;
260 }
261
262 static void net_clear_handlers(void)
263 {
264         net_set_udp_handler(NULL);
265         net_set_arp_handler(NULL);
266         NetSetTimeout(0, NULL);
267 }
268
269 static void net_cleanup_loop(void)
270 {
271         net_clear_handlers();
272 }
273
274 void net_init(void)
275 {
276         static int first_call = 1;
277
278         if (first_call) {
279                 /*
280                  *      Setup packet buffers, aligned correctly.
281                  */
282                 int i;
283
284                 NetTxPacket = &PktBuf[0] + (PKTALIGN - 1);
285                 NetTxPacket -= (ulong)NetTxPacket % PKTALIGN;
286                 for (i = 0; i < PKTBUFSRX; i++)
287                         NetRxPackets[i] = NetTxPacket + (i + 1) * PKTSIZE_ALIGN;
288
289                 ArpInit();
290                 net_clear_handlers();
291
292                 /* Only need to setup buffer pointers once. */
293                 first_call = 0;
294         }
295
296         NetInitLoop();
297 }
298
299 /**********************************************************************/
300 /*
301  *      Main network processing loop.
302  */
303
304 int NetLoop(enum proto_t protocol)
305 {
306         bd_t *bd = gd->bd;
307         int ret = -1;
308
309         NetRestarted = 0;
310         NetDevExists = 0;
311         NetTryCount = 1;
312         debug_cond(DEBUG_INT_STATE, "--- NetLoop Entry\n");
313
314         bootstage_mark_name(BOOTSTAGE_ID_ETH_START, "eth_start");
315         net_init();
316         if (eth_is_on_demand_init() || protocol != NETCONS) {
317                 eth_halt();
318                 eth_set_current();
319                 if (eth_init(bd) < 0) {
320                         eth_halt();
321                         return -1;
322                 }
323         } else
324                 eth_init_state_only(bd);
325
326 restart:
327         net_set_state(NETLOOP_CONTINUE);
328
329         /*
330          *      Start the ball rolling with the given start function.  From
331          *      here on, this code is a state machine driven by received
332          *      packets and timer events.
333          */
334         debug_cond(DEBUG_INT_STATE, "--- NetLoop Init\n");
335         NetInitLoop();
336
337         switch (net_check_prereq(protocol)) {
338         case 1:
339                 /* network not configured */
340                 eth_halt();
341                 return -1;
342
343         case 2:
344                 /* network device not configured */
345                 break;
346
347         case 0:
348                 NetDevExists = 1;
349                 NetBootFileXferSize = 0;
350                 switch (protocol) {
351                 case TFTPGET:
352 #ifdef CONFIG_CMD_TFTPPUT
353                 case TFTPPUT:
354 #endif
355                         /* always use ARP to get server ethernet address */
356                         TftpStart(protocol);
357                         break;
358 #ifdef CONFIG_CMD_TFTPSRV
359                 case TFTPSRV:
360                         TftpStartServer();
361                         break;
362 #endif
363 #if defined(CONFIG_CMD_DHCP)
364                 case DHCP:
365                         BootpTry = 0;
366                         NetOurIP = 0;
367                         DhcpRequest();          /* Basically same as BOOTP */
368                         break;
369 #endif
370
371                 case BOOTP:
372                         BootpTry = 0;
373                         NetOurIP = 0;
374                         BootpRequest();
375                         break;
376
377 #if defined(CONFIG_CMD_RARP)
378                 case RARP:
379                         RarpTry = 0;
380                         NetOurIP = 0;
381                         RarpRequest();
382                         break;
383 #endif
384 #if defined(CONFIG_CMD_PING)
385                 case PING:
386                         ping_start();
387                         break;
388 #endif
389 #if defined(CONFIG_CMD_NFS)
390                 case NFS:
391                         NfsStart();
392                         break;
393 #endif
394 #if defined(CONFIG_CMD_CDP)
395                 case CDP:
396                         CDPStart();
397                         break;
398 #endif
399 #ifdef CONFIG_NETCONSOLE
400                 case NETCONS:
401                         NcStart();
402                         break;
403 #endif
404 #if defined(CONFIG_CMD_SNTP)
405                 case SNTP:
406                         SntpStart();
407                         break;
408 #endif
409 #if defined(CONFIG_CMD_DNS)
410                 case DNS:
411                         DnsStart();
412                         break;
413 #endif
414 #if defined(CONFIG_CMD_LINK_LOCAL)
415                 case LINKLOCAL:
416                         link_local_start();
417                         break;
418 #endif
419                 default:
420                         break;
421                 }
422
423                 break;
424         }
425
426 #if defined(CONFIG_MII) || defined(CONFIG_CMD_MII)
427 #if     defined(CONFIG_SYS_FAULT_ECHO_LINK_DOWN)        && \
428         defined(CONFIG_STATUS_LED)                      && \
429         defined(STATUS_LED_RED)
430         /*
431          * Echo the inverted link state to the fault LED.
432          */
433         if (miiphy_link(eth_get_dev()->name, CONFIG_SYS_FAULT_MII_ADDR))
434                 status_led_set(STATUS_LED_RED, STATUS_LED_OFF);
435         else
436                 status_led_set(STATUS_LED_RED, STATUS_LED_ON);
437 #endif /* CONFIG_SYS_FAULT_ECHO_LINK_DOWN, ... */
438 #endif /* CONFIG_MII, ... */
439
440         /*
441          *      Main packet reception loop.  Loop receiving packets until
442          *      someone sets `net_state' to a state that terminates.
443          */
444         for (;;) {
445                 WATCHDOG_RESET();
446 #ifdef CONFIG_SHOW_ACTIVITY
447                 show_activity(1);
448 #endif
449                 /*
450                  *      Check the ethernet for a new packet.  The ethernet
451                  *      receive routine will process it.
452                  */
453                 eth_rx();
454
455                 /*
456                  *      Abort if ctrl-c was pressed.
457                  */
458                 if (ctrlc()) {
459                         /* cancel any ARP that may not have completed */
460                         NetArpWaitPacketIP = 0;
461
462                         net_cleanup_loop();
463                         eth_halt();
464                         /* Invalidate the last protocol */
465                         eth_set_last_protocol(BOOTP);
466
467                         puts("\nAbort\n");
468                         /* include a debug print as well incase the debug
469                            messages are directed to stderr */
470                         debug_cond(DEBUG_INT_STATE, "--- NetLoop Abort!\n");
471                         goto done;
472                 }
473
474                 ArpTimeoutCheck();
475
476                 /*
477                  *      Check for a timeout, and run the timeout handler
478                  *      if we have one.
479                  */
480                 if (timeHandler && ((get_timer(0) - timeStart) > timeDelta)) {
481                         thand_f *x;
482
483 #if defined(CONFIG_MII) || defined(CONFIG_CMD_MII)
484 #if     defined(CONFIG_SYS_FAULT_ECHO_LINK_DOWN)        && \
485         defined(CONFIG_STATUS_LED)                      && \
486         defined(STATUS_LED_RED)
487                         /*
488                          * Echo the inverted link state to the fault LED.
489                          */
490                         if (miiphy_link(eth_get_dev()->name,
491                                        CONFIG_SYS_FAULT_MII_ADDR)) {
492                                 status_led_set(STATUS_LED_RED, STATUS_LED_OFF);
493                         } else {
494                                 status_led_set(STATUS_LED_RED, STATUS_LED_ON);
495                         }
496 #endif /* CONFIG_SYS_FAULT_ECHO_LINK_DOWN, ... */
497 #endif /* CONFIG_MII, ... */
498                         debug_cond(DEBUG_INT_STATE, "--- NetLoop timeout\n");
499                         x = timeHandler;
500                         timeHandler = (thand_f *)0;
501                         (*x)();
502                 }
503
504
505                 switch (net_state) {
506
507                 case NETLOOP_RESTART:
508                         NetRestarted = 1;
509                         goto restart;
510
511                 case NETLOOP_SUCCESS:
512                         net_cleanup_loop();
513                         if (NetBootFileXferSize > 0) {
514                                 char buf[20];
515                                 printf("Bytes transferred = %ld (%lx hex)\n",
516                                         NetBootFileXferSize,
517                                         NetBootFileXferSize);
518                                 sprintf(buf, "%lX", NetBootFileXferSize);
519                                 setenv("filesize", buf);
520
521                                 sprintf(buf, "%lX", (unsigned long)load_addr);
522                                 setenv("fileaddr", buf);
523                         }
524                         if (protocol != NETCONS)
525                                 eth_halt();
526                         else
527                                 eth_halt_state_only();
528
529                         eth_set_last_protocol(protocol);
530
531                         ret = NetBootFileXferSize;
532                         debug_cond(DEBUG_INT_STATE, "--- NetLoop Success!\n");
533                         goto done;
534
535                 case NETLOOP_FAIL:
536                         net_cleanup_loop();
537                         /* Invalidate the last protocol */
538                         eth_set_last_protocol(BOOTP);
539                         debug_cond(DEBUG_INT_STATE, "--- NetLoop Fail!\n");
540                         goto done;
541
542                 case NETLOOP_CONTINUE:
543                         continue;
544                 }
545         }
546
547 done:
548 #ifdef CONFIG_CMD_TFTPPUT
549         /* Clear out the handlers */
550         net_set_udp_handler(NULL);
551         net_set_icmp_handler(NULL);
552 #endif
553         return ret;
554 }
555
556 /**********************************************************************/
557
558 static void
559 startAgainTimeout(void)
560 {
561         net_set_state(NETLOOP_RESTART);
562 }
563
564 void NetStartAgain(void)
565 {
566         char *nretry;
567         int retry_forever = 0;
568         unsigned long retrycnt = 0;
569
570         nretry = getenv("netretry");
571         if (nretry) {
572                 if (!strcmp(nretry, "yes"))
573                         retry_forever = 1;
574                 else if (!strcmp(nretry, "no"))
575                         retrycnt = 0;
576                 else if (!strcmp(nretry, "once"))
577                         retrycnt = 1;
578                 else
579                         retrycnt = simple_strtoul(nretry, NULL, 0);
580         } else
581                 retry_forever = 1;
582
583         if ((!retry_forever) && (NetTryCount >= retrycnt)) {
584                 eth_halt();
585                 net_set_state(NETLOOP_FAIL);
586                 return;
587         }
588
589         NetTryCount++;
590
591         eth_halt();
592 #if !defined(CONFIG_NET_DO_NOT_TRY_ANOTHER)
593         eth_try_another(!NetRestarted);
594 #endif
595         eth_init(gd->bd);
596         if (NetRestartWrap) {
597                 NetRestartWrap = 0;
598                 if (NetDevExists) {
599                         NetSetTimeout(10000UL, startAgainTimeout);
600                         net_set_udp_handler(NULL);
601                 } else {
602                         net_set_state(NETLOOP_FAIL);
603                 }
604         } else {
605                 net_set_state(NETLOOP_RESTART);
606         }
607 }
608
609 /**********************************************************************/
610 /*
611  *      Miscelaneous bits.
612  */
613
614 static void dummy_handler(uchar *pkt, unsigned dport,
615                         IPaddr_t sip, unsigned sport,
616                         unsigned len)
617 {
618 }
619
620 rxhand_f *net_get_udp_handler(void)
621 {
622         return udp_packet_handler;
623 }
624
625 void net_set_udp_handler(rxhand_f *f)
626 {
627         debug_cond(DEBUG_INT_STATE, "--- NetLoop UDP handler set (%p)\n", f);
628         if (f == NULL)
629                 udp_packet_handler = dummy_handler;
630         else
631                 udp_packet_handler = f;
632 }
633
634 rxhand_f *net_get_arp_handler(void)
635 {
636         return arp_packet_handler;
637 }
638
639 void net_set_arp_handler(rxhand_f *f)
640 {
641         debug_cond(DEBUG_INT_STATE, "--- NetLoop ARP handler set (%p)\n", f);
642         if (f == NULL)
643                 arp_packet_handler = dummy_handler;
644         else
645                 arp_packet_handler = f;
646 }
647
648 #ifdef CONFIG_CMD_TFTPPUT
649 void net_set_icmp_handler(rxhand_icmp_f *f)
650 {
651         packet_icmp_handler = f;
652 }
653 #endif
654
655 void
656 NetSetTimeout(ulong iv, thand_f *f)
657 {
658         if (iv == 0) {
659                 debug_cond(DEBUG_INT_STATE,
660                         "--- NetLoop timeout handler cancelled\n");
661                 timeHandler = (thand_f *)0;
662         } else {
663                 debug_cond(DEBUG_INT_STATE,
664                         "--- NetLoop timeout handler set (%p)\n", f);
665                 timeHandler = f;
666                 timeStart = get_timer(0);
667                 timeDelta = iv * CONFIG_SYS_HZ / 1000;
668         }
669 }
670
671 int NetSendUDPPacket(uchar *ether, IPaddr_t dest, int dport, int sport,
672                 int payload_len)
673 {
674         uchar *pkt;
675         int eth_hdr_size;
676         int pkt_hdr_size;
677
678         /* make sure the NetTxPacket is initialized (NetInit() was called) */
679         assert(NetTxPacket != NULL);
680         if (NetTxPacket == NULL)
681                 return -1;
682
683         /* convert to new style broadcast */
684         if (dest == 0)
685                 dest = 0xFFFFFFFF;
686
687         /* if broadcast, make the ether address a broadcast and don't do ARP */
688         if (dest == 0xFFFFFFFF)
689                 ether = NetBcastAddr;
690
691         pkt = (uchar *)NetTxPacket;
692
693         eth_hdr_size = NetSetEther(pkt, ether, PROT_IP);
694         pkt += eth_hdr_size;
695         net_set_udp_header(pkt, dest, dport, sport, payload_len);
696         pkt_hdr_size = eth_hdr_size + IP_UDP_HDR_SIZE;
697
698         /* if MAC address was not discovered yet, do an ARP request */
699         if (memcmp(ether, NetEtherNullAddr, 6) == 0) {
700                 debug_cond(DEBUG_DEV_PKT, "sending ARP for %pI4\n", &dest);
701
702                 /* save the ip and eth addr for the packet to send after arp */
703                 NetArpWaitPacketIP = dest;
704                 NetArpWaitPacketMAC = ether;
705
706                 /* size of the waiting packet */
707                 NetArpWaitTxPacketSize = pkt_hdr_size + payload_len;
708
709                 /* and do the ARP request */
710                 NetArpWaitTry = 1;
711                 NetArpWaitTimerStart = get_timer(0);
712                 ArpRequest();
713                 return 1;       /* waiting */
714         } else {
715                 debug_cond(DEBUG_DEV_PKT, "sending UDP to %pI4/%pM\n",
716                         &dest, ether);
717                 NetSendPacket(NetTxPacket, pkt_hdr_size + payload_len);
718                 return 0;       /* transmitted */
719         }
720 }
721
722 #ifdef CONFIG_IP_DEFRAG
723 /*
724  * This function collects fragments in a single packet, according
725  * to the algorithm in RFC815. It returns NULL or the pointer to
726  * a complete packet, in static storage
727  */
728 #ifndef CONFIG_NET_MAXDEFRAG
729 #define CONFIG_NET_MAXDEFRAG 16384
730 #endif
731 /*
732  * MAXDEFRAG, above, is chosen in the config file and  is real data
733  * so we need to add the NFS overhead, which is more than TFTP.
734  * To use sizeof in the internal unnamed structures, we need a real
735  * instance (can't do "sizeof(struct rpc_t.u.reply))", unfortunately).
736  * The compiler doesn't complain nor allocates the actual structure
737  */
738 static struct rpc_t rpc_specimen;
739 #define IP_PKTSIZE (CONFIG_NET_MAXDEFRAG + sizeof(rpc_specimen.u.reply))
740
741 #define IP_MAXUDP (IP_PKTSIZE - IP_HDR_SIZE)
742
743 /*
744  * this is the packet being assembled, either data or frag control.
745  * Fragments go by 8 bytes, so this union must be 8 bytes long
746  */
747 struct hole {
748         /* first_byte is address of this structure */
749         u16 last_byte;  /* last byte in this hole + 1 (begin of next hole) */
750         u16 next_hole;  /* index of next (in 8-b blocks), 0 == none */
751         u16 prev_hole;  /* index of prev, 0 == none */
752         u16 unused;
753 };
754
755 static struct ip_udp_hdr *__NetDefragment(struct ip_udp_hdr *ip, int *lenp)
756 {
757         static uchar pkt_buff[IP_PKTSIZE] __aligned(PKTALIGN);
758         static u16 first_hole, total_len;
759         struct hole *payload, *thisfrag, *h, *newh;
760         struct ip_udp_hdr *localip = (struct ip_udp_hdr *)pkt_buff;
761         uchar *indata = (uchar *)ip;
762         int offset8, start, len, done = 0;
763         u16 ip_off = ntohs(ip->ip_off);
764
765         /* payload starts after IP header, this fragment is in there */
766         payload = (struct hole *)(pkt_buff + IP_HDR_SIZE);
767         offset8 =  (ip_off & IP_OFFS);
768         thisfrag = payload + offset8;
769         start = offset8 * 8;
770         len = ntohs(ip->ip_len) - IP_HDR_SIZE;
771
772         if (start + len > IP_MAXUDP) /* fragment extends too far */
773                 return NULL;
774
775         if (!total_len || localip->ip_id != ip->ip_id) {
776                 /* new (or different) packet, reset structs */
777                 total_len = 0xffff;
778                 payload[0].last_byte = ~0;
779                 payload[0].next_hole = 0;
780                 payload[0].prev_hole = 0;
781                 first_hole = 0;
782                 /* any IP header will work, copy the first we received */
783                 memcpy(localip, ip, IP_HDR_SIZE);
784         }
785
786         /*
787          * What follows is the reassembly algorithm. We use the payload
788          * array as a linked list of hole descriptors, as each hole starts
789          * at a multiple of 8 bytes. However, last byte can be whatever value,
790          * so it is represented as byte count, not as 8-byte blocks.
791          */
792
793         h = payload + first_hole;
794         while (h->last_byte < start) {
795                 if (!h->next_hole) {
796                         /* no hole that far away */
797                         return NULL;
798                 }
799                 h = payload + h->next_hole;
800         }
801
802         /* last fragment may be 1..7 bytes, the "+7" forces acceptance */
803         if (offset8 + ((len + 7) / 8) <= h - payload) {
804                 /* no overlap with holes (dup fragment?) */
805                 return NULL;
806         }
807
808         if (!(ip_off & IP_FLAGS_MFRAG)) {
809                 /* no more fragmentss: truncate this (last) hole */
810                 total_len = start + len;
811                 h->last_byte = start + len;
812         }
813
814         /*
815          * There is some overlap: fix the hole list. This code doesn't
816          * deal with a fragment that overlaps with two different holes
817          * (thus being a superset of a previously-received fragment).
818          */
819
820         if ((h >= thisfrag) && (h->last_byte <= start + len)) {
821                 /* complete overlap with hole: remove hole */
822                 if (!h->prev_hole && !h->next_hole) {
823                         /* last remaining hole */
824                         done = 1;
825                 } else if (!h->prev_hole) {
826                         /* first hole */
827                         first_hole = h->next_hole;
828                         payload[h->next_hole].prev_hole = 0;
829                 } else if (!h->next_hole) {
830                         /* last hole */
831                         payload[h->prev_hole].next_hole = 0;
832                 } else {
833                         /* in the middle of the list */
834                         payload[h->next_hole].prev_hole = h->prev_hole;
835                         payload[h->prev_hole].next_hole = h->next_hole;
836                 }
837
838         } else if (h->last_byte <= start + len) {
839                 /* overlaps with final part of the hole: shorten this hole */
840                 h->last_byte = start;
841
842         } else if (h >= thisfrag) {
843                 /* overlaps with initial part of the hole: move this hole */
844                 newh = thisfrag + (len / 8);
845                 *newh = *h;
846                 h = newh;
847                 if (h->next_hole)
848                         payload[h->next_hole].prev_hole = (h - payload);
849                 if (h->prev_hole)
850                         payload[h->prev_hole].next_hole = (h - payload);
851                 else
852                         first_hole = (h - payload);
853
854         } else {
855                 /* fragment sits in the middle: split the hole */
856                 newh = thisfrag + (len / 8);
857                 *newh = *h;
858                 h->last_byte = start;
859                 h->next_hole = (newh - payload);
860                 newh->prev_hole = (h - payload);
861                 if (newh->next_hole)
862                         payload[newh->next_hole].prev_hole = (newh - payload);
863         }
864
865         /* finally copy this fragment and possibly return whole packet */
866         memcpy((uchar *)thisfrag, indata + IP_HDR_SIZE, len);
867         if (!done)
868                 return NULL;
869
870         localip->ip_len = htons(total_len);
871         *lenp = total_len + IP_HDR_SIZE;
872         return localip;
873 }
874
875 static inline struct ip_udp_hdr *NetDefragment(struct ip_udp_hdr *ip, int *lenp)
876 {
877         u16 ip_off = ntohs(ip->ip_off);
878         if (!(ip_off & (IP_OFFS | IP_FLAGS_MFRAG)))
879                 return ip; /* not a fragment */
880         return __NetDefragment(ip, lenp);
881 }
882
883 #else /* !CONFIG_IP_DEFRAG */
884
885 static inline struct ip_udp_hdr *NetDefragment(struct ip_udp_hdr *ip, int *lenp)
886 {
887         u16 ip_off = ntohs(ip->ip_off);
888         if (!(ip_off & (IP_OFFS | IP_FLAGS_MFRAG)))
889                 return ip; /* not a fragment */
890         return NULL;
891 }
892 #endif
893
894 /**
895  * Receive an ICMP packet. We deal with REDIRECT and PING here, and silently
896  * drop others.
897  *
898  * @parma ip    IP packet containing the ICMP
899  */
900 static void receive_icmp(struct ip_udp_hdr *ip, int len,
901                         IPaddr_t src_ip, struct ethernet_hdr *et)
902 {
903         struct icmp_hdr *icmph = (struct icmp_hdr *)&ip->udp_src;
904
905         switch (icmph->type) {
906         case ICMP_REDIRECT:
907                 if (icmph->code != ICMP_REDIR_HOST)
908                         return;
909                 printf(" ICMP Host Redirect to %pI4 ",
910                         &icmph->un.gateway);
911                 break;
912         default:
913 #if defined(CONFIG_CMD_PING)
914                 ping_receive(et, ip, len);
915 #endif
916 #ifdef CONFIG_CMD_TFTPPUT
917                 if (packet_icmp_handler)
918                         packet_icmp_handler(icmph->type, icmph->code,
919                                 ntohs(ip->udp_dst), src_ip, ntohs(ip->udp_src),
920                                 icmph->un.data, ntohs(ip->udp_len));
921 #endif
922                 break;
923         }
924 }
925
926 void
927 NetReceive(uchar *inpkt, int len)
928 {
929         struct ethernet_hdr *et;
930         struct ip_udp_hdr *ip;
931         IPaddr_t dst_ip;
932         IPaddr_t src_ip;
933         int eth_proto;
934 #if defined(CONFIG_CMD_CDP)
935         int iscdp;
936 #endif
937         ushort cti = 0, vlanid = VLAN_NONE, myvlanid, mynvlanid;
938
939         debug_cond(DEBUG_NET_PKT, "packet received\n");
940
941         NetRxPacket = inpkt;
942         NetRxPacketLen = len;
943         et = (struct ethernet_hdr *)inpkt;
944
945         /* too small packet? */
946         if (len < ETHER_HDR_SIZE)
947                 return;
948
949 #ifdef CONFIG_API
950         if (push_packet) {
951                 (*push_packet)(inpkt, len);
952                 return;
953         }
954 #endif
955
956 #if defined(CONFIG_CMD_CDP)
957         /* keep track if packet is CDP */
958         iscdp = is_cdp_packet(et->et_dest);
959 #endif
960
961         myvlanid = ntohs(NetOurVLAN);
962         if (myvlanid == (ushort)-1)
963                 myvlanid = VLAN_NONE;
964         mynvlanid = ntohs(NetOurNativeVLAN);
965         if (mynvlanid == (ushort)-1)
966                 mynvlanid = VLAN_NONE;
967
968         eth_proto = ntohs(et->et_protlen);
969
970         if (eth_proto < 1514) {
971                 struct e802_hdr *et802 = (struct e802_hdr *)et;
972                 /*
973                  *      Got a 802.2 packet.  Check the other protocol field.
974                  *      XXX VLAN over 802.2+SNAP not implemented!
975                  */
976                 eth_proto = ntohs(et802->et_prot);
977
978                 ip = (struct ip_udp_hdr *)(inpkt + E802_HDR_SIZE);
979                 len -= E802_HDR_SIZE;
980
981         } else if (eth_proto != PROT_VLAN) {    /* normal packet */
982                 ip = (struct ip_udp_hdr *)(inpkt + ETHER_HDR_SIZE);
983                 len -= ETHER_HDR_SIZE;
984
985         } else {                        /* VLAN packet */
986                 struct vlan_ethernet_hdr *vet =
987                         (struct vlan_ethernet_hdr *)et;
988
989                 debug_cond(DEBUG_NET_PKT, "VLAN packet received\n");
990
991                 /* too small packet? */
992                 if (len < VLAN_ETHER_HDR_SIZE)
993                         return;
994
995                 /* if no VLAN active */
996                 if ((ntohs(NetOurVLAN) & VLAN_IDMASK) == VLAN_NONE
997 #if defined(CONFIG_CMD_CDP)
998                                 && iscdp == 0
999 #endif
1000                                 )
1001                         return;
1002
1003                 cti = ntohs(vet->vet_tag);
1004                 vlanid = cti & VLAN_IDMASK;
1005                 eth_proto = ntohs(vet->vet_type);
1006
1007                 ip = (struct ip_udp_hdr *)(inpkt + VLAN_ETHER_HDR_SIZE);
1008                 len -= VLAN_ETHER_HDR_SIZE;
1009         }
1010
1011         debug_cond(DEBUG_NET_PKT, "Receive from protocol 0x%x\n", eth_proto);
1012
1013 #if defined(CONFIG_CMD_CDP)
1014         if (iscdp) {
1015                 cdp_receive((uchar *)ip, len);
1016                 return;
1017         }
1018 #endif
1019
1020         if ((myvlanid & VLAN_IDMASK) != VLAN_NONE) {
1021                 if (vlanid == VLAN_NONE)
1022                         vlanid = (mynvlanid & VLAN_IDMASK);
1023                 /* not matched? */
1024                 if (vlanid != (myvlanid & VLAN_IDMASK))
1025                         return;
1026         }
1027
1028         switch (eth_proto) {
1029
1030         case PROT_ARP:
1031                 ArpReceive(et, ip, len);
1032                 break;
1033
1034 #ifdef CONFIG_CMD_RARP
1035         case PROT_RARP:
1036                 rarp_receive(ip, len);
1037                 break;
1038 #endif
1039         case PROT_IP:
1040                 debug_cond(DEBUG_NET_PKT, "Got IP\n");
1041                 /* Before we start poking the header, make sure it is there */
1042                 if (len < IP_UDP_HDR_SIZE) {
1043                         debug("len bad %d < %lu\n", len,
1044                                 (ulong)IP_UDP_HDR_SIZE);
1045                         return;
1046                 }
1047                 /* Check the packet length */
1048                 if (len < ntohs(ip->ip_len)) {
1049                         debug("len bad %d < %d\n", len, ntohs(ip->ip_len));
1050                         return;
1051                 }
1052                 len = ntohs(ip->ip_len);
1053                 debug_cond(DEBUG_NET_PKT, "len=%d, v=%02x\n",
1054                         len, ip->ip_hl_v & 0xff);
1055
1056                 /* Can't deal with anything except IPv4 */
1057                 if ((ip->ip_hl_v & 0xf0) != 0x40)
1058                         return;
1059                 /* Can't deal with IP options (headers != 20 bytes) */
1060                 if ((ip->ip_hl_v & 0x0f) > 0x05)
1061                         return;
1062                 /* Check the Checksum of the header */
1063                 if (!NetCksumOk((uchar *)ip, IP_HDR_SIZE / 2)) {
1064                         debug("checksum bad\n");
1065                         return;
1066                 }
1067                 /* If it is not for us, ignore it */
1068                 dst_ip = NetReadIP(&ip->ip_dst);
1069                 if (NetOurIP && dst_ip != NetOurIP && dst_ip != 0xFFFFFFFF) {
1070 #ifdef CONFIG_MCAST_TFTP
1071                         if (Mcast_addr != dst_ip)
1072 #endif
1073                                 return;
1074                 }
1075                 /* Read source IP address for later use */
1076                 src_ip = NetReadIP(&ip->ip_src);
1077                 /*
1078                  * The function returns the unchanged packet if it's not
1079                  * a fragment, and either the complete packet or NULL if
1080                  * it is a fragment (if !CONFIG_IP_DEFRAG, it returns NULL)
1081                  */
1082                 ip = NetDefragment(ip, &len);
1083                 if (!ip)
1084                         return;
1085                 /*
1086                  * watch for ICMP host redirects
1087                  *
1088                  * There is no real handler code (yet). We just watch
1089                  * for ICMP host redirect messages. In case anybody
1090                  * sees these messages: please contact me
1091                  * (wd@denx.de), or - even better - send me the
1092                  * necessary fixes :-)
1093                  *
1094                  * Note: in all cases where I have seen this so far
1095                  * it was a problem with the router configuration,
1096                  * for instance when a router was configured in the
1097                  * BOOTP reply, but the TFTP server was on the same
1098                  * subnet. So this is probably a warning that your
1099                  * configuration might be wrong. But I'm not really
1100                  * sure if there aren't any other situations.
1101                  *
1102                  * Simon Glass <sjg@chromium.org>: We get an ICMP when
1103                  * we send a tftp packet to a dead connection, or when
1104                  * there is no server at the other end.
1105                  */
1106                 if (ip->ip_p == IPPROTO_ICMP) {
1107                         receive_icmp(ip, len, src_ip, et);
1108                         return;
1109                 } else if (ip->ip_p != IPPROTO_UDP) {   /* Only UDP packets */
1110                         return;
1111                 }
1112
1113                 debug_cond(DEBUG_DEV_PKT,
1114                         "received UDP (to=%pI4, from=%pI4, len=%d)\n",
1115                         &dst_ip, &src_ip, len);
1116
1117 #ifdef CONFIG_UDP_CHECKSUM
1118                 if (ip->udp_xsum != 0) {
1119                         ulong   xsum;
1120                         ushort *sumptr;
1121                         ushort  sumlen;
1122
1123                         xsum  = ip->ip_p;
1124                         xsum += (ntohs(ip->udp_len));
1125                         xsum += (ntohl(ip->ip_src) >> 16) & 0x0000ffff;
1126                         xsum += (ntohl(ip->ip_src) >>  0) & 0x0000ffff;
1127                         xsum += (ntohl(ip->ip_dst) >> 16) & 0x0000ffff;
1128                         xsum += (ntohl(ip->ip_dst) >>  0) & 0x0000ffff;
1129
1130                         sumlen = ntohs(ip->udp_len);
1131                         sumptr = (ushort *) &(ip->udp_src);
1132
1133                         while (sumlen > 1) {
1134                                 ushort sumdata;
1135
1136                                 sumdata = *sumptr++;
1137                                 xsum += ntohs(sumdata);
1138                                 sumlen -= 2;
1139                         }
1140                         if (sumlen > 0) {
1141                                 ushort sumdata;
1142
1143                                 sumdata = *(unsigned char *) sumptr;
1144                                 sumdata = (sumdata << 8) & 0xff00;
1145                                 xsum += sumdata;
1146                         }
1147                         while ((xsum >> 16) != 0) {
1148                                 xsum = (xsum & 0x0000ffff) +
1149                                        ((xsum >> 16) & 0x0000ffff);
1150                         }
1151                         if ((xsum != 0x00000000) && (xsum != 0x0000ffff)) {
1152                                 printf(" UDP wrong checksum %08lx %08x\n",
1153                                         xsum, ntohs(ip->udp_xsum));
1154                                 return;
1155                         }
1156                 }
1157 #endif
1158
1159
1160 #ifdef CONFIG_NETCONSOLE
1161                 nc_input_packet((uchar *)ip + IP_UDP_HDR_SIZE,
1162                                         src_ip,
1163                                         ntohs(ip->udp_dst),
1164                                         ntohs(ip->udp_src),
1165                                         ntohs(ip->udp_len) - UDP_HDR_SIZE);
1166 #endif
1167                 /*
1168                  *      IP header OK.  Pass the packet to the current handler.
1169                  */
1170                 (*udp_packet_handler)((uchar *)ip + IP_UDP_HDR_SIZE,
1171                                 ntohs(ip->udp_dst),
1172                                 src_ip,
1173                                 ntohs(ip->udp_src),
1174                                 ntohs(ip->udp_len) - UDP_HDR_SIZE);
1175                 break;
1176         }
1177 }
1178
1179
1180 /**********************************************************************/
1181
1182 static int net_check_prereq(enum proto_t protocol)
1183 {
1184         switch (protocol) {
1185                 /* Fall through */
1186 #if defined(CONFIG_CMD_PING)
1187         case PING:
1188                 if (NetPingIP == 0) {
1189                         puts("*** ERROR: ping address not given\n");
1190                         return 1;
1191                 }
1192                 goto common;
1193 #endif
1194 #if defined(CONFIG_CMD_SNTP)
1195         case SNTP:
1196                 if (NetNtpServerIP == 0) {
1197                         puts("*** ERROR: NTP server address not given\n");
1198                         return 1;
1199                 }
1200                 goto common;
1201 #endif
1202 #if defined(CONFIG_CMD_DNS)
1203         case DNS:
1204                 if (NetOurDNSIP == 0) {
1205                         puts("*** ERROR: DNS server address not given\n");
1206                         return 1;
1207                 }
1208                 goto common;
1209 #endif
1210 #if defined(CONFIG_CMD_NFS)
1211         case NFS:
1212 #endif
1213         case TFTPGET:
1214         case TFTPPUT:
1215                 if (NetServerIP == 0) {
1216                         puts("*** ERROR: `serverip' not set\n");
1217                         return 1;
1218                 }
1219 #if     defined(CONFIG_CMD_PING) || defined(CONFIG_CMD_SNTP) || \
1220         defined(CONFIG_CMD_DNS)
1221 common:
1222 #endif
1223                 /* Fall through */
1224
1225         case NETCONS:
1226         case TFTPSRV:
1227                 if (NetOurIP == 0) {
1228                         puts("*** ERROR: `ipaddr' not set\n");
1229                         return 1;
1230                 }
1231                 /* Fall through */
1232
1233 #ifdef CONFIG_CMD_RARP
1234         case RARP:
1235 #endif
1236         case BOOTP:
1237         case CDP:
1238         case DHCP:
1239         case LINKLOCAL:
1240                 if (memcmp(NetOurEther, "\0\0\0\0\0\0", 6) == 0) {
1241                         int num = eth_get_dev_index();
1242
1243                         switch (num) {
1244                         case -1:
1245                                 puts("*** ERROR: No ethernet found.\n");
1246                                 return 1;
1247                         case 0:
1248                                 puts("*** ERROR: `ethaddr' not set\n");
1249                                 break;
1250                         default:
1251                                 printf("*** ERROR: `eth%daddr' not set\n",
1252                                         num);
1253                                 break;
1254                         }
1255
1256                         NetStartAgain();
1257                         return 2;
1258                 }
1259                 /* Fall through */
1260         default:
1261                 return 0;
1262         }
1263         return 0;               /* OK */
1264 }
1265 /**********************************************************************/
1266
1267 int
1268 NetCksumOk(uchar *ptr, int len)
1269 {
1270         return !((NetCksum(ptr, len) + 1) & 0xfffe);
1271 }
1272
1273
1274 unsigned
1275 NetCksum(uchar *ptr, int len)
1276 {
1277         ulong   xsum;
1278         ushort *p = (ushort *)ptr;
1279
1280         xsum = 0;
1281         while (len-- > 0)
1282                 xsum += *p++;
1283         xsum = (xsum & 0xffff) + (xsum >> 16);
1284         xsum = (xsum & 0xffff) + (xsum >> 16);
1285         return xsum & 0xffff;
1286 }
1287
1288 int
1289 NetEthHdrSize(void)
1290 {
1291         ushort myvlanid;
1292
1293         myvlanid = ntohs(NetOurVLAN);
1294         if (myvlanid == (ushort)-1)
1295                 myvlanid = VLAN_NONE;
1296
1297         return ((myvlanid & VLAN_IDMASK) == VLAN_NONE) ? ETHER_HDR_SIZE :
1298                 VLAN_ETHER_HDR_SIZE;
1299 }
1300
1301 int
1302 NetSetEther(uchar *xet, uchar * addr, uint prot)
1303 {
1304         struct ethernet_hdr *et = (struct ethernet_hdr *)xet;
1305         ushort myvlanid;
1306
1307         myvlanid = ntohs(NetOurVLAN);
1308         if (myvlanid == (ushort)-1)
1309                 myvlanid = VLAN_NONE;
1310
1311         memcpy(et->et_dest, addr, 6);
1312         memcpy(et->et_src, NetOurEther, 6);
1313         if ((myvlanid & VLAN_IDMASK) == VLAN_NONE) {
1314                 et->et_protlen = htons(prot);
1315                 return ETHER_HDR_SIZE;
1316         } else {
1317                 struct vlan_ethernet_hdr *vet =
1318                         (struct vlan_ethernet_hdr *)xet;
1319
1320                 vet->vet_vlan_type = htons(PROT_VLAN);
1321                 vet->vet_tag = htons((0 << 5) | (myvlanid & VLAN_IDMASK));
1322                 vet->vet_type = htons(prot);
1323                 return VLAN_ETHER_HDR_SIZE;
1324         }
1325 }
1326
1327 int net_update_ether(struct ethernet_hdr *et, uchar *addr, uint prot)
1328 {
1329         ushort protlen;
1330
1331         memcpy(et->et_dest, addr, 6);
1332         memcpy(et->et_src, NetOurEther, 6);
1333         protlen = ntohs(et->et_protlen);
1334         if (protlen == PROT_VLAN) {
1335                 struct vlan_ethernet_hdr *vet =
1336                         (struct vlan_ethernet_hdr *)et;
1337                 vet->vet_type = htons(prot);
1338                 return VLAN_ETHER_HDR_SIZE;
1339         } else if (protlen > 1514) {
1340                 et->et_protlen = htons(prot);
1341                 return ETHER_HDR_SIZE;
1342         } else {
1343                 /* 802.2 + SNAP */
1344                 struct e802_hdr *et802 = (struct e802_hdr *)et;
1345                 et802->et_prot = htons(prot);
1346                 return E802_HDR_SIZE;
1347         }
1348 }
1349
1350 void net_set_ip_header(uchar *pkt, IPaddr_t dest, IPaddr_t source)
1351 {
1352         struct ip_udp_hdr *ip = (struct ip_udp_hdr *)pkt;
1353
1354         /*
1355          *      Construct an IP header.
1356          */
1357         /* IP_HDR_SIZE / 4 (not including UDP) */
1358         ip->ip_hl_v  = 0x45;
1359         ip->ip_tos   = 0;
1360         ip->ip_len   = htons(IP_HDR_SIZE);
1361         ip->ip_id    = htons(NetIPID++);
1362         ip->ip_off   = htons(IP_FLAGS_DFRAG);   /* Don't fragment */
1363         ip->ip_ttl   = 255;
1364         ip->ip_sum   = 0;
1365         /* already in network byte order */
1366         NetCopyIP((void *)&ip->ip_src, &source);
1367         /* already in network byte order */
1368         NetCopyIP((void *)&ip->ip_dst, &dest);
1369 }
1370
1371 void net_set_udp_header(uchar *pkt, IPaddr_t dest, int dport, int sport,
1372                         int len)
1373 {
1374         struct ip_udp_hdr *ip = (struct ip_udp_hdr *)pkt;
1375
1376         /*
1377          *      If the data is an odd number of bytes, zero the
1378          *      byte after the last byte so that the checksum
1379          *      will work.
1380          */
1381         if (len & 1)
1382                 pkt[IP_UDP_HDR_SIZE + len] = 0;
1383
1384         net_set_ip_header(pkt, dest, NetOurIP);
1385         ip->ip_len   = htons(IP_UDP_HDR_SIZE + len);
1386         ip->ip_p     = IPPROTO_UDP;
1387         ip->ip_sum   = ~NetCksum((uchar *)ip, IP_HDR_SIZE >> 1);
1388
1389         ip->udp_src  = htons(sport);
1390         ip->udp_dst  = htons(dport);
1391         ip->udp_len  = htons(UDP_HDR_SIZE + len);
1392         ip->udp_xsum = 0;
1393 }
1394
1395 void copy_filename(char *dst, const char *src, int size)
1396 {
1397         if (*src && (*src == '"')) {
1398                 ++src;
1399                 --size;
1400         }
1401
1402         while ((--size > 0) && *src && (*src != '"'))
1403                 *dst++ = *src++;
1404         *dst = '\0';
1405 }
1406
1407 #if     defined(CONFIG_CMD_NFS)         || \
1408         defined(CONFIG_CMD_SNTP)        || \
1409         defined(CONFIG_CMD_DNS)
1410 /*
1411  * make port a little random (1024-17407)
1412  * This keeps the math somewhat trivial to compute, and seems to work with
1413  * all supported protocols/clients/servers
1414  */
1415 unsigned int random_port(void)
1416 {
1417         return 1024 + (get_timer(0) % 0x4000);
1418 }
1419 #endif
1420
1421 void ip_to_string(IPaddr_t x, char *s)
1422 {
1423         x = ntohl(x);
1424         sprintf(s, "%d.%d.%d.%d",
1425                 (int) ((x >> 24) & 0xff),
1426                 (int) ((x >> 16) & 0xff),
1427                 (int) ((x >> 8) & 0xff), (int) ((x >> 0) & 0xff)
1428         );
1429 }
1430
1431 void VLAN_to_string(ushort x, char *s)
1432 {
1433         x = ntohs(x);
1434
1435         if (x == (ushort)-1)
1436                 x = VLAN_NONE;
1437
1438         if (x == VLAN_NONE)
1439                 strcpy(s, "none");
1440         else
1441                 sprintf(s, "%d", x & VLAN_IDMASK);
1442 }
1443
1444 ushort string_to_VLAN(const char *s)
1445 {
1446         ushort id;
1447
1448         if (s == NULL)
1449                 return htons(VLAN_NONE);
1450
1451         if (*s < '0' || *s > '9')
1452                 id = VLAN_NONE;
1453         else
1454                 id = (ushort)simple_strtoul(s, NULL, 10);
1455
1456         return htons(id);
1457 }
1458
1459 ushort getenv_VLAN(char *var)
1460 {
1461         return string_to_VLAN(getenv(var));
1462 }