blob: fe2f147418df0de120ae61f4e21d6d381c13b8f3 [file] [log] [blame]
lh9ed821d2023-04-07 01:36:19 -07001/*
2 * Copyright 1994, 1995, 2000 Neil Russell.
3 * (See License)
4 * Copyright 2000, 2001 DENX Software Engineering, Wolfgang Denk, wd@denx.de
5 * Copyright 2011 Comelit Group SpA,
6 * Luca Ceresoli <luca.ceresoli@comelit.it>
7 */
8
9#include <common.h>
10#include <command.h>
11#include <net.h>
12#include "tftp.h"
13#include "bootp.h"
14#ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
15#include <flash.h>
16#endif
17extern uint32_t g_gmac_init_overtime;
18extern ulong time_over;
19/* Well known TFTP port # */
20#define WELL_KNOWN_PORT 69
21/* Millisecs to timeout for lost pkt */
22#define TIMEOUT 5000UL
23
24#ifndef CONFIG_NET_RETRY_COUNT
25/* # of timeouts before giving up */
26# define TIMEOUT_COUNT 10
27#else
28# define TIMEOUT_COUNT (CONFIG_NET_RETRY_COUNT * 2)
29#endif
30/* Number of "loading" hashes per line (for checking the image size) */
31#define HASHES_PER_LINE 65
32
33/*
34 * TFTP operations.
35 */
36#define TFTP_RRQ 1
37#define TFTP_WRQ 2
38#define TFTP_DATA 3
39#define TFTP_ACK 4
40#define TFTP_ERROR 5
41#define TFTP_OACK 6
42
43static ulong TftpTimeoutMSecs = TIMEOUT;
44static int TftpTimeoutCountMax = TIMEOUT_COUNT;
45static ulong time_start; /* Record time we started tftp */
46
47/*
48 * These globals govern the timeout behavior when attempting a connection to a
49 * TFTP server. TftpRRQTimeoutMSecs specifies the number of milliseconds to
50 * wait for the server to respond to initial connection. Second global,
51 * TftpRRQTimeoutCountMax, gives the number of such connection retries.
52 * TftpRRQTimeoutCountMax must be non-negative and TftpRRQTimeoutMSecs must be
53 * positive. The globals are meant to be set (and restored) by code needing
54 * non-standard timeout behavior when initiating a TFTP transfer.
55 */
56ulong TftpRRQTimeoutMSecs = TIMEOUT;
57int TftpRRQTimeoutCountMax = TIMEOUT_COUNT;
58
59enum {
60 TFTP_ERR_UNDEFINED = 0,
61 TFTP_ERR_FILE_NOT_FOUND = 1,
62 TFTP_ERR_ACCESS_DENIED = 2,
63 TFTP_ERR_DISK_FULL = 3,
64 TFTP_ERR_UNEXPECTED_OPCODE = 4,
65 TFTP_ERR_UNKNOWN_TRANSFER_ID = 5,
66 TFTP_ERR_FILE_ALREADY_EXISTS = 6,
67};
68
69static IPaddr_t TftpRemoteIP;
70/* The UDP port at their end */
71static int TftpRemotePort;
72/* The UDP port at our end */
73static int TftpOurPort;
74static int TftpTimeoutCount;
75/* packet sequence number */
76static ulong TftpBlock;
77/* last packet sequence number received */
78static ulong TftpLastBlock;
79/* count of sequence number wraparounds */
80static ulong TftpBlockWrap;
81/* memory offset due to wrapping */
82static ulong TftpBlockWrapOffset;
83static int TftpState;
84#ifdef CONFIG_TFTP_TSIZE
85/* The file size reported by the server */
86static int TftpTsize;
87/* The number of hashes we printed */
88static short TftpNumchars;
89#endif
90#ifdef CONFIG_CMD_TFTPPUT
91static int TftpWriting; /* 1 if writing, else 0 */
92static int TftpFinalBlock; /* 1 if we have sent the last block */
93#else
94#define TftpWriting 0
95#endif
96
97#define STATE_SEND_RRQ 1
98#define STATE_DATA 2
99#define STATE_TOO_LARGE 3
100#define STATE_BAD_MAGIC 4
101#define STATE_OACK 5
102#define STATE_RECV_WRQ 6
103#define STATE_SEND_WRQ 7
104
105/* default TFTP block size */
106#define TFTP_BLOCK_SIZE 512
107/* sequence number is 16 bit */
108#define TFTP_SEQUENCE_SIZE ((ulong)(1<<16))
109
110#define DEFAULT_NAME_LEN (8 + 4 + 1)
111static char default_filename[DEFAULT_NAME_LEN];
112
113#ifndef CONFIG_TFTP_FILE_NAME_MAX_LEN
114#define MAX_LEN 128
115#else
116#define MAX_LEN CONFIG_TFTP_FILE_NAME_MAX_LEN
117#endif
118
119static char tftp_filename[MAX_LEN];
120
121/* 512 is poor choice for ethernet, MTU is typically 1500.
122 * Minus eth.hdrs thats 1468. Can get 2x better throughput with
123 * almost-MTU block sizes. At least try... fall back to 512 if need be.
124 * (but those using CONFIG_IP_DEFRAG may want to set a larger block in cfg file)
125 */
126#ifdef CONFIG_TFTP_BLOCKSIZE
127#define TFTP_MTU_BLOCKSIZE CONFIG_TFTP_BLOCKSIZE
128#else
129#define TFTP_MTU_BLOCKSIZE 1468
130#endif
131
132static unsigned short TftpBlkSize = TFTP_BLOCK_SIZE;
133static unsigned short TftpBlkSizeOption = TFTP_MTU_BLOCKSIZE;
134int tftp_server_cnt = 0;
135
136#ifdef CONFIG_MCAST_TFTP
137#include <malloc.h>
138#define MTFTP_BITMAPSIZE 0x1000
139static unsigned *Bitmap;
140static int PrevBitmapHole, Mapsize = MTFTP_BITMAPSIZE;
141static uchar ProhibitMcast, MasterClient;
142static uchar Multicast;
143static int Mcast_port;
144static ulong TftpEndingBlock; /* can get 'last' block before done..*/
145
146static void parse_multicast_oack(char *pkt, int len);
147
148static void
149mcast_cleanup(void)
150{
151 if (Mcast_addr)
152 eth_mcast_join(Mcast_addr, 0);
153 if (Bitmap)
154 free(Bitmap);
155 Bitmap = NULL;
156 Mcast_addr = Multicast = Mcast_port = 0;
157 TftpEndingBlock = -1;
158}
159
160#endif /* CONFIG_MCAST_TFTP */
161
162static inline void
163store_block(int block, uchar *src, unsigned len)
164{
165 ulong offset = block * TftpBlkSize + TftpBlockWrapOffset;
166 ulong newsize = offset + len;
167#ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
168 int i, rc = 0;
169
170 for (i = 0; i < CONFIG_SYS_MAX_FLASH_BANKS; i++) {
171 /* start address in flash? */
172 if (flash_info[i].flash_id == FLASH_UNKNOWN)
173 continue;
174 if (load_addr + offset >= flash_info[i].start[0]) {
175 rc = 1;
176 break;
177 }
178 }
179
180 if (rc) { /* Flash is destination for this packet */
181 rc = flash_write((char *)src, (ulong)(load_addr+offset), len);
182 if (rc) {
183 flash_perror(rc);
184 net_set_state(NETLOOP_FAIL);
185 return;
186 }
187 } else
188#endif /* CONFIG_SYS_DIRECT_FLASH_TFTP */
189 {
190 (void)memcpy((void *)(load_addr + offset), src, len);
191 }
192#ifdef CONFIG_MCAST_TFTP
193 if (Multicast)
194 ext2_set_bit(block, Bitmap);
195#endif
196
197 if (NetBootFileXferSize < newsize)
198 NetBootFileXferSize = newsize;
199}
200
201/* Clear our state ready for a new transfer */
202static void new_transfer(void)
203{
204 TftpLastBlock = 0;
205 TftpBlockWrap = 0;
206 TftpBlockWrapOffset = 0;
207#ifdef CONFIG_CMD_TFTPPUT
208 TftpFinalBlock = 0;
209#endif
210}
211
212#ifdef CONFIG_CMD_TFTPPUT
213/**
214 * Load the next block from memory to be sent over tftp.
215 *
216 * @param block Block number to send
217 * @param dst Destination buffer for data
218 * @param len Number of bytes in block (this one and every other)
219 * @return number of bytes loaded
220 */
221static int load_block(unsigned block, uchar *dst, unsigned len)
222{
223 /* We may want to get the final block from the previous set */
224 ulong offset = ((int)block - 1) * len + TftpBlockWrapOffset;
225 ulong tosend = len;
226
227 tosend = min(NetBootFileXferSize - offset, tosend);
228 (void)memcpy(dst, (void *)(save_addr + offset), tosend);
229 debug("%s: block=%d, offset=%ld, len=%d, tosend=%ld\n", __func__,
230 block, offset, len, tosend);
231 return tosend;
232}
233#endif
234
235static int TftpSend(void);
236static int TftpTimeout(void);
237
238/**********************************************************************/
239
240static void show_block_marker(void)
241{
242#ifdef CONFIG_TFTP_TSIZE
243 if (TftpTsize) {
244 ulong pos = TftpBlock * TftpBlkSize + TftpBlockWrapOffset;
245
246 while (TftpNumchars < pos * 50 / TftpTsize) {
247 putc('#');
248 TftpNumchars++;
249 }
250 } else
251#endif
252 {
253 if (((TftpBlock - 1) % 10) == 0)
254 putc('#');
255 else if ((TftpBlock % (10 * HASHES_PER_LINE)) == 0)
256 puts("\n\t ");
257 }
258}
259
260/**
261 * restart the current transfer due to an error
262 *
263 * @param msg Message to print for user
264 */
265static void restart(const char *msg)
266{
267 printf("\n%s; starting again\n", msg);
268#ifdef CONFIG_MCAST_TFTP
269 mcast_cleanup();
270#endif
271 NetStartAgain();
272}
273
274/*
275 * Check if the block number has wrapped, and update progress
276 *
277 * TODO: The egregious use of global variables in this file should be tidied.
278 */
279static void update_block_number(void)
280{
281 /*
282 * RFC1350 specifies that the first data packet will
283 * have sequence number 1. If we receive a sequence
284 * number of 0 this means that there was a wrap
285 * around of the (16 bit) counter.
286 */
287 if (TftpBlock == 0) {
288 TftpBlockWrap++;
289 TftpBlockWrapOffset += TftpBlkSize * TFTP_SEQUENCE_SIZE;
290 TftpTimeoutCount = 0; /* we've done well, reset thhe timeout */
291 } else {
292 show_block_marker();
293 }
294}
295
296/* The TFTP get or put is complete */
297static void tftp_complete(void)
298{
299#ifdef CONFIG_TFTP_TSIZE
300 /* Print hash marks for the last packet received */
301 while (TftpTsize && TftpNumchars < 49) {
302 putc('#');
303 TftpNumchars++;
304 }
305#endif
306 time_start = get_timer(time_start);
307 if (time_start > 0) {
308 puts("\n\t "); /* Line up with "Loading: " */
309 print_size(NetBootFileXferSize /
310 time_start * 1000, "/s");
311 }
312 puts("\ndone\n");
313 net_set_state(NETLOOP_SUCCESS);
314}
315
316static int
317TftpSend(void)
318{
319 uchar *pkt;
320 uchar *xp;
321 int len = 0;
322 ushort *s;
323
324#ifdef CONFIG_MCAST_TFTP
325 /* Multicast TFTP.. non-MasterClients do not ACK data. */
326 if (Multicast
327 && (TftpState == STATE_DATA)
328 && (MasterClient == 0))
329 return;
330#endif
331 /*
332 * We will always be sending some sort of packet, so
333 * cobble together the packet headers now.
334 */
335 pkt = NetTxPacket + NetEthHdrSize() + IP_UDP_HDR_SIZE;
336
337 switch (TftpState) {
338 case STATE_SEND_RRQ:
339 case STATE_SEND_WRQ:
340 xp = pkt;
341 s = (ushort *)pkt;
342#ifdef CONFIG_CMD_TFTPPUT
343 *s++ = htons(TftpState == STATE_SEND_RRQ ? TFTP_RRQ :
344 TFTP_WRQ);
345#else
346 *s++ = htons(TFTP_RRQ);
347#endif
348 pkt = (uchar *)s;
349 strcpy((char *)pkt, tftp_filename);
350 pkt += strlen(tftp_filename) + 1;
351 strcpy((char *)pkt, "octet");
352 pkt += 5 /*strlen("octet")*/ + 1;
353 strcpy((char *)pkt, "timeout");
354 pkt += 7 /*strlen("timeout")*/ + 1;
355 sprintf((char *)pkt, "%lu", TftpTimeoutMSecs / 1000);
356 debug("send option \"timeout %s\"\n", (char *)pkt);
357 pkt += strlen((char *)pkt) + 1;
358#ifdef CONFIG_TFTP_TSIZE
359 pkt += sprintf((char *)pkt, "tsize%c%lu%c",
360 0, NetBootFileXferSize, 0);
361#endif
362 /* try for more effic. blk size */
363 pkt += sprintf((char *)pkt, "blksize%c%d%c",
364 0, TftpBlkSizeOption, 0);
365#ifdef CONFIG_MCAST_TFTP
366 /* Check all preconditions before even trying the option */
367 if (!ProhibitMcast) {
368 Bitmap = malloc(Mapsize);
369 if (Bitmap && eth_get_dev()->mcast) {
370 free(Bitmap);
371 Bitmap = NULL;
372 pkt += sprintf((char *)pkt, "multicast%c%c",
373 0, 0);
374 }
375 }
376#endif /* CONFIG_MCAST_TFTP */
377 len = pkt - xp;
378 break;
379
380 case STATE_OACK:
381#ifdef CONFIG_MCAST_TFTP
382 /* My turn! Start at where I need blocks I missed.*/
383 if (Multicast)
384 TftpBlock = ext2_find_next_zero_bit(Bitmap,
385 (Mapsize*8), 0);
386 /*..falling..*/
387#endif
388
389 case STATE_RECV_WRQ:
390 case STATE_DATA:
391 xp = pkt;
392 s = (ushort *)pkt;
393 s[0] = htons(TFTP_ACK);
394 s[1] = htons(TftpBlock);
395 pkt = (uchar *)(s + 2);
396#ifdef CONFIG_CMD_TFTPPUT
397 if (TftpWriting) {
398 int toload = TftpBlkSize;
399 int loaded = load_block(TftpBlock, pkt, toload);
400
401 s[0] = htons(TFTP_DATA);
402 pkt += loaded;
403 TftpFinalBlock = (loaded < toload);
404 }
405#endif
406 len = pkt - xp;
407 break;
408
409 case STATE_TOO_LARGE:
410 xp = pkt;
411 s = (ushort *)pkt;
412 *s++ = htons(TFTP_ERROR);
413 *s++ = htons(3);
414
415 pkt = (uchar *)s;
416 strcpy((char *)pkt, "File too large");
417 pkt += 14 /*strlen("File too large")*/ + 1;
418 len = pkt - xp;
419 break;
420
421 case STATE_BAD_MAGIC:
422 xp = pkt;
423 s = (ushort *)pkt;
424 *s++ = htons(TFTP_ERROR);
425 *s++ = htons(2);
426 pkt = (uchar *)s;
427 strcpy((char *)pkt, "File has bad magic");
428 pkt += 18 /*strlen("File has bad magic")*/ + 1;
429 len = pkt - xp;
430 break;
431 }
432 NetSendUDPPacket(NetServerEther, TftpRemoteIP, TftpRemotePort,
433 TftpOurPort, len);
434
435 return 0;
436}
437
438#ifdef CONFIG_CMD_TFTPPUT
439static void icmp_handler(unsigned type, unsigned code, unsigned dest,
440 IPaddr_t sip, unsigned src, uchar *pkt, unsigned len)
441{
442 if (type == ICMP_NOT_REACH && code == ICMP_NOT_REACH_PORT) {
443 /* Oh dear the other end has gone away */
444 restart("TFTP server died");
445 }
446}
447#endif
448
449static void
450TftpHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src,
451 unsigned len)
452{
453 ushort proto;
454 ushort *s;
455 int i;
456
457 if (dest != TftpOurPort) {
458#ifdef CONFIG_MCAST_TFTP
459 if (Multicast
460 && (!Mcast_port || (dest != Mcast_port)))
461#endif
462 return;
463 }
464 if (TftpState != STATE_SEND_RRQ && src != TftpRemotePort &&
465 TftpState != STATE_RECV_WRQ && TftpState != STATE_SEND_WRQ)
466 return;
467
468 if (len < 2)
469 return;
470 len -= 2;
471 /* warning: don't use increment (++) in ntohs() macros!! */
472 s = (ushort *)pkt;
473 proto = *s++;
474 pkt = (uchar *)s;
475 switch (ntohs(proto)) {
476
477 case TFTP_RRQ:
478 break;
479
480 case TFTP_ACK:
481
482#ifdef CONFIG_CMD_TFTPPUT
483
484 if (TftpWriting) {
485 if (TftpFinalBlock) {
486 tftp_complete();
487 } else {
488 /*
489 * Move to the next block. We want our block
490 * count to wrap just like the other end!
491 */
492 int block = ntohs(*s);
493 int ack_ok = (TftpBlock == block);
494
495 TftpBlock = (unsigned short)(block + 1);
496 update_block_number();
497 if (ack_ok)
498 TftpSend(); /* Send next data block */
499 }
500 }
501#endif
502 break;
503
504 default:
505 break;
506
507#ifdef CONFIG_CMD_TFTPSRV
508 case TFTP_WRQ:
509 debug("Got WRQ\n");
510 TftpRemoteIP = sip;
511 TftpRemotePort = src;
512 TftpOurPort = 1024 + (get_timer(0) % 3072);
513 new_transfer();
514 TftpSend(); /* Send ACK(0) */
515 break;
516#endif
517
518 case TFTP_OACK:
519 debug("Got OACK: %s %s\n",
520 pkt,
521 pkt + strlen((char *)pkt) + 1);
522 TftpState = STATE_OACK;
523 TftpRemotePort = src;
524 /*
525 * Check for 'blksize' option.
526 * Careful: "i" is signed, "len" is unsigned, thus
527 * something like "len-8" may give a *huge* number
528 */
529 for (i = 0; i+8 < len; i++) {
530 if (strcmp((char *)pkt+i, "blksize") == 0) {
531 TftpBlkSize = (unsigned short)
532 simple_strtoul((char *)pkt+i+8, NULL,
533 10);
534 debug("Blocksize ack: %s, %d\n",
535 (char *)pkt+i+8, TftpBlkSize);
536 }
537#ifdef CONFIG_TFTP_TSIZE
538 if (strcmp((char *)pkt+i, "tsize") == 0) {
539 TftpTsize = simple_strtoul((char *)pkt+i+6,
540 NULL, 10);
541 debug("size = %s, %d\n",
542 (char *)pkt+i+6, TftpTsize);
543 }
544#endif
545 }
546#ifdef CONFIG_MCAST_TFTP
547 parse_multicast_oack((char *)pkt, len-1);
548 if ((Multicast) && (!MasterClient))
549 TftpState = STATE_DATA; /* passive.. */
550 else
551#endif
552#ifdef CONFIG_CMD_TFTPPUT
553 if (TftpWriting) {
554 /* Get ready to send the first block */
555 TftpState = STATE_DATA;
556 TftpBlock++;
557 }
558#endif
559 TftpSend(); /* Send ACK or first data block */
560 break;
561 case TFTP_DATA:
562 if (len < 2)
563 return;
564 len -= 2;
565 TftpBlock = ntohs(*(ushort *)pkt);
566
567 update_block_number();
568
569 if (TftpState == STATE_SEND_RRQ)
570 debug("Server did not acknowledge timeout option!\n");
571
572 if (TftpState == STATE_SEND_RRQ || TftpState == STATE_OACK ||
573 TftpState == STATE_RECV_WRQ) {
574 /* first block received */
575 TftpState = STATE_DATA;
576 TftpRemotePort = src;
577 new_transfer();
578
579#ifdef CONFIG_MCAST_TFTP
580 if (Multicast) { /* start!=1 common if mcast */
581 TftpLastBlock = TftpBlock - 1;
582 } else
583#endif
584 if (TftpBlock != 1) { /* Assertion */
585 printf("\nTFTP error: "
586 "First block is not block 1 (%ld)\n"
587 "Starting again\n\n",
588 TftpBlock);
589 NetStartAgain();
590 break;
591 }
592 }
593
594 if (TftpBlock == TftpLastBlock) {
595 /*
596 * Same block again; ignore it.
597 */
598 break;
599 }
600
601 TftpLastBlock = TftpBlock;
602 TftpTimeoutCountMax = TIMEOUT_COUNT;
603 NetSetTimeout(TftpTimeoutMSecs, TftpTimeout);
604
605 store_block(TftpBlock - 1, pkt + 2, len);
606
607 /*
608 * Acknowledge the block just received, which will prompt
609 * the remote for the next one.
610 */
611#ifdef CONFIG_MCAST_TFTP
612 /* if I am the MasterClient, actively calculate what my next
613 * needed block is; else I'm passive; not ACKING
614 */
615 if (Multicast) {
616 if (len < TftpBlkSize) {
617 TftpEndingBlock = TftpBlock;
618 } else if (MasterClient) {
619 TftpBlock = PrevBitmapHole =
620 ext2_find_next_zero_bit(
621 Bitmap,
622 (Mapsize*8),
623 PrevBitmapHole);
624 if (TftpBlock > ((Mapsize*8) - 1)) {
625 printf("tftpfile too big\n");
626 /* try to double it and retry */
627 Mapsize <<= 1;
628 mcast_cleanup();
629 NetStartAgain();
630 return;
631 }
632 TftpLastBlock = TftpBlock;
633 }
634 }
635#endif
636 TftpSend();
637
638#ifdef CONFIG_MCAST_TFTP
639 if (Multicast) {
640 if (MasterClient && (TftpBlock >= TftpEndingBlock)) {
641 puts("\nMulticast tftp done\n");
642 mcast_cleanup();
643 net_set_state(NETLOOP_SUCCESS);
644 }
645 } else
646#endif
647 if (len < TftpBlkSize)
648 tftp_complete();
649 break;
650
651 case TFTP_ERROR:
652 printf("\nTFTP error: '%s' (%d)\n",
653 pkt + 2, ntohs(*(ushort *)pkt));
654
655 switch (ntohs(*(ushort *)pkt)) {
656 case TFTP_ERR_FILE_NOT_FOUND:
657 case TFTP_ERR_ACCESS_DENIED:
658 puts("Not retrying...\n");
659 eth_halt();
660 net_set_state(NETLOOP_FAIL);
661 break;
662 case TFTP_ERR_UNDEFINED:
663 case TFTP_ERR_DISK_FULL:
664 case TFTP_ERR_UNEXPECTED_OPCODE:
665 case TFTP_ERR_UNKNOWN_TRANSFER_ID:
666 case TFTP_ERR_FILE_ALREADY_EXISTS:
667 default:
668 puts("Starting again\n\n");
669#ifdef CONFIG_MCAST_TFTP
670 mcast_cleanup();
671#endif
672 NetStartAgain();
673 break;
674 }
675 break;
676 }
677}
678
679
680static int TftpTimeout(void)
681{
682 if (++TftpTimeoutCount > TftpTimeoutCountMax) {
683 ++ tftp_server_cnt ;
684 restart("Retry count exceeded");
685 } else {
686 puts("T ");
687 NetSetTimeout(time_over, TftpTimeout);
688 if (TftpState != STATE_RECV_WRQ)
689 {
690 TftpSend();
691 }
692 }
693 return 0;
694}
695
696
697int TftpStart(enum proto_t protocol)
698{
699 char *ep; /* Environment pointer */
700
701 /*
702 * Allow the user to choose TFTP blocksize and timeout.
703 * TFTP protocol has a minimal timeout of 1 second.
704 */
705 ep = getenv("tftpblocksize");
706 if (ep != NULL)
707 TftpBlkSizeOption = simple_strtol(ep, NULL, 10);
708
709 ep = getenv("tftptimeout");
710 if (ep != NULL)
711 TftpTimeoutMSecs = simple_strtol(ep, NULL, 10);
712
713 if (TftpTimeoutMSecs < 1000) {
714 printf("TFTP timeout (%ld ms) too low, "
715 "set minimum = 1000 ms\n",
716 TftpTimeoutMSecs);
717 TftpTimeoutMSecs = 1000;
718 }
719
720 debug("TFTP blocksize = %i, timeout = %ld ms\n",
721 TftpBlkSizeOption, TftpTimeoutMSecs);
722
723 TftpRemoteIP = NetServerIP;
724 if (BootFile[0] == '\0') {
725 sprintf(default_filename, "%02X%02X%02X%02X.img",
726 NetOurIP & 0xFF,
727 (NetOurIP >> 8) & 0xFF,
728 (NetOurIP >> 16) & 0xFF,
729 (NetOurIP >> 24) & 0xFF);
730
731 strncpy(tftp_filename, default_filename, MAX_LEN);
732 tftp_filename[MAX_LEN-1] = 0;
733
734 printf("*** Warning: no boot file name; using '%s'\n",
735 tftp_filename);
736 } else {
737 char *p = strchr(BootFile, ':');
738
739 if (p == NULL) {
740 strncpy(tftp_filename, BootFile, MAX_LEN - 1);
741 tftp_filename[MAX_LEN-1] = 0;
742 } else {
743 TftpRemoteIP = string_to_ip(BootFile);
744 strncpy(tftp_filename, p + 1, MAX_LEN - 1);
745 tftp_filename[MAX_LEN-1] = 0;
746 }
747 }
748
749 printf("Using %s device\n", eth_get_name());
750 printf("TFTP %s server %pI4; our IP address is %pI4",
751#ifdef CONFIG_CMD_TFTPPUT
752 protocol == TFTPPUT ? "to" : "from",
753#else
754 "from",
755#endif
756 &TftpRemoteIP, &NetOurIP);
757
758 /* Check if we need to send across this subnet */
759 if (NetOurGatewayIP && NetOurSubnetMask) {
760 IPaddr_t OurNet = NetOurIP & NetOurSubnetMask;
761 IPaddr_t RemoteNet = TftpRemoteIP & NetOurSubnetMask;
762
763 if (OurNet != RemoteNet)
764 printf("; sending through gateway %pI4",
765 &NetOurGatewayIP);
766 }
767 putc('\n');
768
769 printf("Filename '%s'.", tftp_filename);
770
771 if (NetBootFileSize) {
772 printf(" Size is 0x%x Bytes = ", NetBootFileSize<<9);
773 print_size(NetBootFileSize<<9, "");
774 }
775
776 putc('\n');
777#ifdef CONFIG_CMD_TFTPPUT
778 TftpWriting = (protocol == TFTPPUT);
779 if (TftpWriting) {
780 printf("Save address: 0x%lx\n", save_addr);
781 printf("Save size: 0x%lx\n", save_size);
782 NetBootFileXferSize = save_size;
783 puts("Saving: *\b");
784 TftpState = STATE_SEND_WRQ;
785 new_transfer();
786 } else
787#endif
788 {
789 printf("Load address: 0x%lx\n", load_addr);
790 puts("Loading: *\b");
791 TftpState = STATE_SEND_RRQ;
792 }
793
794 time_start = get_timer(0);
795 TftpTimeoutCountMax = TftpRRQTimeoutCountMax;
796
797 NetSetTimeout(TftpTimeoutMSecs, TftpTimeout);
798 net_set_udp_handler(TftpHandler);
799#ifdef CONFIG_CMD_TFTPPUT
800 net_set_icmp_handler(icmp_handler);
801#endif
802 TftpRemotePort = WELL_KNOWN_PORT;
803 TftpTimeoutCount = 0;
804 /* Use a pseudo-random port unless a specific port is set */
805 TftpOurPort = 1024 + (get_timer(0) % 3072);
806
807#ifdef CONFIG_TFTP_PORT
808 ep = getenv("tftpdstp");
809 if (ep != NULL)
810 TftpRemotePort = simple_strtol(ep, NULL, 10);
811 ep = getenv("tftpsrcp");
812 if (ep != NULL)
813 TftpOurPort = simple_strtol(ep, NULL, 10);
814#endif
815 TftpBlock = 0;
816
817 /* zero out server ether in case the server ip has changed */
818 memset(NetServerEther, 0, 6);
819 /* Revert TftpBlkSize to dflt */
820 TftpBlkSize = TFTP_BLOCK_SIZE;
821#ifdef CONFIG_MCAST_TFTP
822 mcast_cleanup();
823#endif
824#ifdef CONFIG_TFTP_TSIZE
825 TftpTsize = 0;
826 TftpNumchars = 0;
827#endif
828
829 TftpSend();
830
831 return 0;
832}
833
834#ifdef CONFIG_CMD_TFTPSRV
835void
836TftpStartServer(void)
837{
838 tftp_filename[0] = 0;
839
840 printf("Using %s device\n", eth_get_name());
841 printf("Listening for TFTP transfer on %pI4\n", &NetOurIP);
842 printf("Load address: 0x%lx\n", load_addr);
843
844 puts("Loading: *\b");
845
846 TftpTimeoutCountMax = TIMEOUT_COUNT;
847 TftpTimeoutCount = 0;
848 TftpTimeoutMSecs = TIMEOUT;
849 NetSetTimeout(TftpTimeoutMSecs, TftpTimeout);
850
851 /* Revert TftpBlkSize to dflt */
852 TftpBlkSize = TFTP_BLOCK_SIZE;
853 TftpBlock = 0;
854 TftpOurPort = WELL_KNOWN_PORT;
855
856#ifdef CONFIG_TFTP_TSIZE
857 TftpTsize = 0;
858 TftpNumchars = 0;
859#endif
860
861 TftpState = STATE_RECV_WRQ;
862 net_set_udp_handler(TftpHandler);
863}
864#endif /* CONFIG_CMD_TFTPSRV */
865
866#ifdef CONFIG_MCAST_TFTP
867/* Credits: atftp project.
868 */
869
870/* pick up BcastAddr, Port, and whether I am [now] the master-client. *
871 * Frame:
872 * +-------+-----------+---+-------~~-------+---+
873 * | opc | multicast | 0 | addr, port, mc | 0 |
874 * +-------+-----------+---+-------~~-------+---+
875 * The multicast addr/port becomes what I listen to, and if 'mc' is '1' then
876 * I am the new master-client so must send ACKs to DataBlocks. If I am not
877 * master-client, I'm a passive client, gathering what DataBlocks I may and
878 * making note of which ones I got in my bitmask.
879 * In theory, I never go from master->passive..
880 * .. this comes in with pkt already pointing just past opc
881 */
882static void parse_multicast_oack(char *pkt, int len)
883{
884 int i;
885 IPaddr_t addr;
886 char *mc_adr, *port, *mc;
887
888 mc_adr = port = mc = NULL;
889 /* march along looking for 'multicast\0', which has to start at least
890 * 14 bytes back from the end.
891 */
892 for (i = 0; i < len-14; i++)
893 if (strcmp(pkt+i, "multicast") == 0)
894 break;
895 if (i >= (len-14)) /* non-Multicast OACK, ign. */
896 return;
897
898 i += 10; /* strlen multicast */
899 mc_adr = pkt+i;
900 for (; i < len; i++) {
901 if (*(pkt+i) == ',') {
902 *(pkt+i) = '\0';
903 if (port) {
904 mc = pkt+i+1;
905 break;
906 } else {
907 port = pkt+i+1;
908 }
909 }
910 }
911 if (!port || !mc_adr || !mc)
912 return;
913 if (Multicast && MasterClient) {
914 printf("I got a OACK as master Client, WRONG!\n");
915 return;
916 }
917 /* ..I now accept packets destined for this MCAST addr, port */
918 if (!Multicast) {
919 if (Bitmap) {
920 printf("Internal failure! no mcast.\n");
921 free(Bitmap);
922 Bitmap = NULL;
923 ProhibitMcast = 1;
924 return ;
925 }
926 /* I malloc instead of pre-declare; so that if the file ends
927 * up being too big for this bitmap I can retry
928 */
929 Bitmap = malloc(Mapsize);
930 if (!Bitmap) {
931 printf("No Bitmap, no multicast. Sorry.\n");
932 ProhibitMcast = 1;
933 return;
934 }
935 memset(Bitmap, 0, Mapsize);
936 PrevBitmapHole = 0;
937 Multicast = 1;
938 }
939 addr = string_to_ip(mc_adr);
940 if (Mcast_addr != addr) {
941 if (Mcast_addr)
942 eth_mcast_join(Mcast_addr, 0);
943 Mcast_addr = addr;
944 if (eth_mcast_join(Mcast_addr, 1)) {
945 printf("Fail to set mcast, revert to TFTP\n");
946 ProhibitMcast = 1;
947 mcast_cleanup();
948 NetStartAgain();
949 }
950 }
951 MasterClient = (unsigned char)simple_strtoul((char *)mc, NULL, 10);
952 Mcast_port = (unsigned short)simple_strtoul(port, NULL, 10);
953 printf("Multicast: %s:%d [%d]\n", mc_adr, Mcast_port, MasterClient);
954 return;
955}
956
957#endif /* Multicast TFTP */