2 * Copyright 1994, 1995, 2000 Neil Russell.
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>
15 /* Well known TFTP port # */
16 #define WELL_KNOWN_PORT 69
17 /* Millisecs to timeout for lost pkt */
18 #define TIMEOUT 5000UL
19 #ifndef CONFIG_NET_RETRY_COUNT
20 /* # of timeouts before giving up */
21 # define TIMEOUT_COUNT 10
23 # define TIMEOUT_COUNT (CONFIG_NET_RETRY_COUNT * 2)
25 /* Number of "loading" hashes per line (for checking the image size) */
26 #define HASHES_PER_LINE 65
38 static ulong TftpTimeoutMSecs
= TIMEOUT
;
39 static int TftpTimeoutCountMax
= TIMEOUT_COUNT
;
42 * These globals govern the timeout behavior when attempting a connection to a
43 * TFTP server. TftpRRQTimeoutMSecs specifies the number of milliseconds to
44 * wait for the server to respond to initial connection. Second global,
45 * TftpRRQTimeoutCountMax, gives the number of such connection retries.
46 * TftpRRQTimeoutCountMax must be non-negative and TftpRRQTimeoutMSecs must be
47 * positive. The globals are meant to be set (and restored) by code needing
48 * non-standard timeout behavior when initiating a TFTP transfer.
50 ulong TftpRRQTimeoutMSecs
= TIMEOUT
;
51 int TftpRRQTimeoutCountMax
= TIMEOUT_COUNT
;
54 TFTP_ERR_UNDEFINED
= 0,
55 TFTP_ERR_FILE_NOT_FOUND
= 1,
56 TFTP_ERR_ACCESS_DENIED
= 2,
57 TFTP_ERR_DISK_FULL
= 3,
58 TFTP_ERR_UNEXPECTED_OPCODE
= 4,
59 TFTP_ERR_UNKNOWN_TRANSFER_ID
= 5,
60 TFTP_ERR_FILE_ALREADY_EXISTS
= 6,
63 static IPaddr_t TftpRemoteIP
;
64 /* The UDP port at their end */
65 static int TftpRemotePort
;
66 /* The UDP port at our end */
67 static int TftpOurPort
;
68 static int TftpTimeoutCount
;
69 /* packet sequence number */
70 static ulong TftpBlock
;
71 /* last packet sequence number received */
72 static ulong TftpLastBlock
;
73 /* count of sequence number wraparounds */
74 static ulong TftpBlockWrap
;
75 /* memory offset due to wrapping */
76 static ulong TftpBlockWrapOffset
;
78 #ifdef CONFIG_TFTP_TSIZE
79 /* The file size reported by the server */
81 /* The number of hashes we printed */
82 static short TftpNumchars
;
85 #define STATE_SEND_RRQ 1
87 #define STATE_TOO_LARGE 3
88 #define STATE_BAD_MAGIC 4
90 #define STATE_RECV_WRQ 6
92 /* default TFTP block size */
93 #define TFTP_BLOCK_SIZE 512
94 /* sequence number is 16 bit */
95 #define TFTP_SEQUENCE_SIZE ((ulong)(1<<16))
97 #define DEFAULT_NAME_LEN (8 + 4 + 1)
98 static char default_filename
[DEFAULT_NAME_LEN
];
100 #ifndef CONFIG_TFTP_FILE_NAME_MAX_LEN
103 #define MAX_LEN CONFIG_TFTP_FILE_NAME_MAX_LEN
106 static char tftp_filename
[MAX_LEN
];
108 #ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
109 extern flash_info_t flash_info
[];
112 /* 512 is poor choice for ethernet, MTU is typically 1500.
113 * Minus eth.hdrs thats 1468. Can get 2x better throughput with
114 * almost-MTU block sizes. At least try... fall back to 512 if need be.
115 * (but those using CONFIG_IP_DEFRAG may want to set a larger block in cfg file)
117 #ifdef CONFIG_TFTP_BLOCKSIZE
118 #define TFTP_MTU_BLOCKSIZE CONFIG_TFTP_BLOCKSIZE
120 #define TFTP_MTU_BLOCKSIZE 1468
123 static unsigned short TftpBlkSize
= TFTP_BLOCK_SIZE
;
124 static unsigned short TftpBlkSizeOption
= TFTP_MTU_BLOCKSIZE
;
126 #ifdef CONFIG_MCAST_TFTP
128 #define MTFTP_BITMAPSIZE 0x1000
129 static unsigned *Bitmap
;
130 static int PrevBitmapHole
, Mapsize
= MTFTP_BITMAPSIZE
;
131 static uchar ProhibitMcast
, MasterClient
;
132 static uchar Multicast
;
133 extern IPaddr_t Mcast_addr
;
134 static int Mcast_port
;
135 static ulong TftpEndingBlock
; /* can get 'last' block before done..*/
137 static void parse_multicast_oack(char *pkt
, int len
);
143 eth_mcast_join(Mcast_addr
, 0);
147 Mcast_addr
= Multicast
= Mcast_port
= 0;
148 TftpEndingBlock
= -1;
151 #endif /* CONFIG_MCAST_TFTP */
153 static __inline__
void
154 store_block(unsigned block
, uchar
*src
, unsigned len
)
156 ulong offset
= block
* TftpBlkSize
+ TftpBlockWrapOffset
;
157 ulong newsize
= offset
+ len
;
158 #ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
161 for (i
= 0; i
< CONFIG_SYS_MAX_FLASH_BANKS
; i
++) {
162 /* start address in flash? */
163 if (flash_info
[i
].flash_id
== FLASH_UNKNOWN
)
165 if (load_addr
+ offset
>= flash_info
[i
].start
[0]) {
171 if (rc
) { /* Flash is destination for this packet */
172 rc
= flash_write((char *)src
, (ulong
)(load_addr
+offset
), len
);
175 NetState
= NETLOOP_FAIL
;
180 #endif /* CONFIG_SYS_DIRECT_FLASH_TFTP */
182 (void)memcpy((void *)(load_addr
+ offset
), src
, len
);
184 #ifdef CONFIG_MCAST_TFTP
186 ext2_set_bit(block
, Bitmap
);
189 if (NetBootFileXferSize
< newsize
)
190 NetBootFileXferSize
= newsize
;
193 /* Clear our state ready for a new transfer */
194 void new_transfer(void)
198 TftpBlockWrapOffset
= 0;
199 #ifdef CONFIG_CMD_TFTPPUT
204 static void TftpSend(void);
205 static void TftpTimeout(void);
207 /**********************************************************************/
209 static void show_block_marker(void)
211 #ifdef CONFIG_TFTP_TSIZE
213 ulong pos
= TftpBlock
* TftpBlkSize
+ TftpBlockWrapOffset
;
215 while (TftpNumchars
< pos
* 50 / TftpTsize
) {
222 if (((TftpBlock
- 1) % 10) == 0)
224 else if ((TftpBlock
% (10 * HASHES_PER_LINE
)) == 0)
230 * restart the current transfer due to an error
232 * @param msg Message to print for user
234 static void restart(const char *msg
)
236 printf("\n%s; starting again\n", msg
);
237 #ifdef CONFIG_MCAST_TFTP
244 * Check if the block number has wrapped, and update progress
246 * TODO: The egregious use of global variables in this file should be tidied.
248 static void update_block_number(void)
251 * RFC1350 specifies that the first data packet will
252 * have sequence number 1. If we receive a sequence
253 * number of 0 this means that there was a wrap
254 * around of the (16 bit) counter.
256 if (TftpBlock
== 0) {
258 TftpBlockWrapOffset
+= TftpBlkSize
* TFTP_SEQUENCE_SIZE
;
259 TftpTimeoutCount
= 0; /* we've done well, reset thhe timeout */
265 /* The TFTP get or put is complete */
266 static void tftp_complete(void)
268 #ifdef CONFIG_TFTP_TSIZE
269 /* Print hash marks for the last packet received */
270 while (TftpTsize
&& TftpNumchars
< 49) {
276 NetState
= NETLOOP_SUCCESS
;
287 #ifdef CONFIG_MCAST_TFTP
288 /* Multicast TFTP.. non-MasterClients do not ACK data. */
290 && (TftpState
== STATE_DATA
)
291 && (MasterClient
== 0))
295 * We will always be sending some sort of packet, so
296 * cobble together the packet headers now.
298 pkt
= NetTxPacket
+ NetEthHdrSize() + IP_HDR_SIZE
;
305 *s
++ = htons(TFTP_RRQ
);
307 strcpy((char *)pkt
, tftp_filename
);
308 pkt
+= strlen(tftp_filename
) + 1;
309 strcpy((char *)pkt
, "octet");
310 pkt
+= 5 /*strlen("octet")*/ + 1;
311 strcpy((char *)pkt
, "timeout");
312 pkt
+= 7 /*strlen("timeout")*/ + 1;
313 sprintf((char *)pkt
, "%lu", TftpTimeoutMSecs
/ 1000);
314 debug("send option \"timeout %s\"\n", (char *)pkt
);
315 pkt
+= strlen((char *)pkt
) + 1;
316 #ifdef CONFIG_TFTP_TSIZE
317 memcpy((char *)pkt
, "tsize\0000\0", 8);
320 /* try for more effic. blk size */
321 pkt
+= sprintf((char *)pkt
, "blksize%c%d%c",
322 0, TftpBlkSizeOption
, 0);
323 #ifdef CONFIG_MCAST_TFTP
324 /* Check all preconditions before even trying the option */
326 && (Bitmap
= malloc(Mapsize
))
327 && eth_get_dev()->mcast
) {
330 pkt
+= sprintf((char *)pkt
, "multicast%c%c", 0, 0);
332 #endif /* CONFIG_MCAST_TFTP */
337 #ifdef CONFIG_MCAST_TFTP
338 /* My turn! Start at where I need blocks I missed.*/
340 TftpBlock
= ext2_find_next_zero_bit(Bitmap
,
349 *s
++ = htons(TFTP_ACK
);
350 *s
++ = htons(TftpBlock
);
355 case STATE_TOO_LARGE
:
358 *s
++ = htons(TFTP_ERROR
);
361 strcpy((char *)pkt
, "File too large");
362 pkt
+= 14 /*strlen("File too large")*/ + 1;
366 case STATE_BAD_MAGIC
:
369 *s
++ = htons(TFTP_ERROR
);
372 strcpy((char *)pkt
, "File has bad magic");
373 pkt
+= 18 /*strlen("File has bad magic")*/ + 1;
378 NetSendUDPPacket(NetServerEther
, TftpRemoteIP
, TftpRemotePort
,
384 TftpHandler(uchar
*pkt
, unsigned dest
, IPaddr_t sip
, unsigned src
,
391 if (dest
!= TftpOurPort
) {
392 #ifdef CONFIG_MCAST_TFTP
394 && (!Mcast_port
|| (dest
!= Mcast_port
)))
398 if (TftpState
!= STATE_SEND_RRQ
&& src
!= TftpRemotePort
&&
399 TftpState
!= STATE_RECV_WRQ
)
405 /* warning: don't use increment (++) in ntohs() macros!! */
409 switch (ntohs(proto
)) {
417 #ifdef CONFIG_CMD_TFTPSRV
421 TftpRemotePort
= src
;
422 TftpOurPort
= 1024 + (get_timer(0) % 3072);
424 TftpSend(); /* Send ACK(0) */
429 debug("Got OACK: %s %s\n",
431 pkt
+ strlen((char *)pkt
) + 1);
432 TftpState
= STATE_OACK
;
433 TftpRemotePort
= src
;
435 * Check for 'blksize' option.
436 * Careful: "i" is signed, "len" is unsigned, thus
437 * something like "len-8" may give a *huge* number
439 for (i
= 0; i
+8 < len
; i
++) {
440 if (strcmp((char *)pkt
+i
, "blksize") == 0) {
441 TftpBlkSize
= (unsigned short)
442 simple_strtoul((char *)pkt
+i
+8, NULL
,
444 debug("Blocksize ack: %s, %d\n",
445 (char *)pkt
+i
+8, TftpBlkSize
);
447 #ifdef CONFIG_TFTP_TSIZE
448 if (strcmp((char *)pkt
+i
, "tsize") == 0) {
449 TftpTsize
= simple_strtoul((char *)pkt
+i
+6,
451 debug("size = %s, %d\n",
452 (char *)pkt
+i
+6, TftpTsize
);
456 #ifdef CONFIG_MCAST_TFTP
457 parse_multicast_oack((char *)pkt
, len
-1);
458 if ((Multicast
) && (!MasterClient
))
459 TftpState
= STATE_DATA
; /* passive.. */
462 TftpSend(); /* Send ACK */
468 TftpBlock
= ntohs(*(ushort
*)pkt
);
470 update_block_number();
472 if (TftpState
== STATE_SEND_RRQ
)
473 debug("Server did not acknowledge timeout option!\n");
475 if (TftpState
== STATE_SEND_RRQ
|| TftpState
== STATE_OACK
||
476 TftpState
== STATE_RECV_WRQ
) {
477 /* first block received */
478 TftpState
= STATE_DATA
;
479 TftpRemotePort
= src
;
482 #ifdef CONFIG_MCAST_TFTP
483 if (Multicast
) { /* start!=1 common if mcast */
484 TftpLastBlock
= TftpBlock
- 1;
487 if (TftpBlock
!= 1) { /* Assertion */
488 printf("\nTFTP error: "
489 "First block is not block 1 (%ld)\n"
490 "Starting again\n\n",
497 if (TftpBlock
== TftpLastBlock
) {
499 * Same block again; ignore it.
504 TftpLastBlock
= TftpBlock
;
505 TftpTimeoutCountMax
= TIMEOUT_COUNT
;
506 NetSetTimeout(TftpTimeoutMSecs
, TftpTimeout
);
508 store_block(TftpBlock
- 1, pkt
+ 2, len
);
511 * Acknowledge the block just received, which will prompt
512 * the remote for the next one.
514 #ifdef CONFIG_MCAST_TFTP
515 /* if I am the MasterClient, actively calculate what my next
516 * needed block is; else I'm passive; not ACKING
519 if (len
< TftpBlkSize
) {
520 TftpEndingBlock
= TftpBlock
;
521 } else if (MasterClient
) {
522 TftpBlock
= PrevBitmapHole
=
523 ext2_find_next_zero_bit(
527 if (TftpBlock
> ((Mapsize
*8) - 1)) {
528 printf("tftpfile too big\n");
529 /* try to double it and retry */
535 TftpLastBlock
= TftpBlock
;
541 #ifdef CONFIG_MCAST_TFTP
543 if (MasterClient
&& (TftpBlock
>= TftpEndingBlock
)) {
544 puts("\nMulticast tftp done\n");
546 NetState
= NETLOOP_SUCCESS
;
551 if (len
< TftpBlkSize
)
556 printf("\nTFTP error: '%s' (%d)\n",
557 pkt
+ 2, ntohs(*(ushort
*)pkt
));
559 switch (ntohs(*(ushort
*)pkt
)) {
560 case TFTP_ERR_FILE_NOT_FOUND
:
561 case TFTP_ERR_ACCESS_DENIED
:
562 puts("Not retrying...\n");
564 NetState
= NETLOOP_FAIL
;
566 case TFTP_ERR_UNDEFINED
:
567 case TFTP_ERR_DISK_FULL
:
568 case TFTP_ERR_UNEXPECTED_OPCODE
:
569 case TFTP_ERR_UNKNOWN_TRANSFER_ID
:
570 case TFTP_ERR_FILE_ALREADY_EXISTS
:
572 puts("Starting again\n\n");
573 #ifdef CONFIG_MCAST_TFTP
587 if (++TftpTimeoutCount
> TftpTimeoutCountMax
) {
588 restart("Retry count exceeded");
591 NetSetTimeout(TftpTimeoutMSecs
, TftpTimeout
);
592 if (TftpState
!= STATE_RECV_WRQ
)
601 char *ep
; /* Environment pointer */
604 * Allow the user to choose TFTP blocksize and timeout.
605 * TFTP protocol has a minimal timeout of 1 second.
607 ep
= getenv("tftpblocksize");
609 TftpBlkSizeOption
= simple_strtol(ep
, NULL
, 10);
611 ep
= getenv("tftptimeout");
613 TftpTimeoutMSecs
= simple_strtol(ep
, NULL
, 10);
615 if (TftpTimeoutMSecs
< 1000) {
616 printf("TFTP timeout (%ld ms) too low, "
617 "set minimum = 1000 ms\n",
619 TftpTimeoutMSecs
= 1000;
622 debug("TFTP blocksize = %i, timeout = %ld ms\n",
623 TftpBlkSizeOption
, TftpTimeoutMSecs
);
625 TftpRemoteIP
= NetServerIP
;
626 if (BootFile
[0] == '\0') {
627 sprintf(default_filename
, "%02lX%02lX%02lX%02lX.img",
629 (NetOurIP
>> 8) & 0xFF,
630 (NetOurIP
>> 16) & 0xFF,
631 (NetOurIP
>> 24) & 0xFF);
633 strncpy(tftp_filename
, default_filename
, MAX_LEN
);
634 tftp_filename
[MAX_LEN
-1] = 0;
636 printf("*** Warning: no boot file name; using '%s'\n",
639 char *p
= strchr(BootFile
, ':');
642 strncpy(tftp_filename
, BootFile
, MAX_LEN
);
643 tftp_filename
[MAX_LEN
-1] = 0;
645 TftpRemoteIP
= string_to_ip(BootFile
);
646 strncpy(tftp_filename
, p
+ 1, MAX_LEN
);
647 tftp_filename
[MAX_LEN
-1] = 0;
651 printf("Using %s device\n", eth_get_name());
652 printf("TFTP from server %pI4"
653 "; our IP address is %pI4", &TftpRemoteIP
, &NetOurIP
);
655 /* Check if we need to send across this subnet */
656 if (NetOurGatewayIP
&& NetOurSubnetMask
) {
657 IPaddr_t OurNet
= NetOurIP
& NetOurSubnetMask
;
658 IPaddr_t RemoteNet
= TftpRemoteIP
& NetOurSubnetMask
;
660 if (OurNet
!= RemoteNet
)
661 printf("; sending through gateway %pI4",
666 printf("Filename '%s'.", tftp_filename
);
668 if (NetBootFileSize
) {
669 printf(" Size is 0x%x Bytes = ", NetBootFileSize
<<9);
670 print_size(NetBootFileSize
<<9, "");
675 printf("Load address: 0x%lx\n", load_addr
);
677 puts("Loading: *\b");
679 TftpTimeoutCountMax
= TftpRRQTimeoutCountMax
;
681 NetSetTimeout(TftpTimeoutMSecs
, TftpTimeout
);
682 NetSetHandler(TftpHandler
);
684 TftpRemotePort
= WELL_KNOWN_PORT
;
685 TftpTimeoutCount
= 0;
686 TftpState
= STATE_SEND_RRQ
;
687 /* Use a pseudo-random port unless a specific port is set */
688 TftpOurPort
= 1024 + (get_timer(0) % 3072);
690 #ifdef CONFIG_TFTP_PORT
691 ep
= getenv("tftpdstp");
693 TftpRemotePort
= simple_strtol(ep
, NULL
, 10);
694 ep
= getenv("tftpsrcp");
696 TftpOurPort
= simple_strtol(ep
, NULL
, 10);
700 /* zero out server ether in case the server ip has changed */
701 memset(NetServerEther
, 0, 6);
702 /* Revert TftpBlkSize to dflt */
703 TftpBlkSize
= TFTP_BLOCK_SIZE
;
704 #ifdef CONFIG_MCAST_TFTP
707 #ifdef CONFIG_TFTP_TSIZE
715 #ifdef CONFIG_CMD_TFTPSRV
717 TftpStartServer(void)
719 tftp_filename
[0] = 0;
721 printf("Using %s device\n", eth_get_name());
722 printf("Listening for TFTP transfer on %pI4\n", &NetOurIP
);
723 printf("Load address: 0x%lx\n", load_addr
);
725 puts("Loading: *\b");
727 TftpTimeoutCountMax
= TIMEOUT_COUNT
;
728 TftpTimeoutCount
= 0;
729 TftpTimeoutMSecs
= TIMEOUT
;
730 NetSetTimeout(TftpTimeoutMSecs
, TftpTimeout
);
732 /* Revert TftpBlkSize to dflt */
733 TftpBlkSize
= TFTP_BLOCK_SIZE
;
735 TftpOurPort
= WELL_KNOWN_PORT
;
737 #ifdef CONFIG_TFTP_TSIZE
742 TftpState
= STATE_RECV_WRQ
;
743 NetSetHandler(TftpHandler
);
745 #endif /* CONFIG_CMD_TFTPSRV */
747 #ifdef CONFIG_MCAST_TFTP
748 /* Credits: atftp project.
751 /* pick up BcastAddr, Port, and whether I am [now] the master-client. *
753 * +-------+-----------+---+-------~~-------+---+
754 * | opc | multicast | 0 | addr, port, mc | 0 |
755 * +-------+-----------+---+-------~~-------+---+
756 * The multicast addr/port becomes what I listen to, and if 'mc' is '1' then
757 * I am the new master-client so must send ACKs to DataBlocks. If I am not
758 * master-client, I'm a passive client, gathering what DataBlocks I may and
759 * making note of which ones I got in my bitmask.
760 * In theory, I never go from master->passive..
761 * .. this comes in with pkt already pointing just past opc
763 static void parse_multicast_oack(char *pkt
, int len
)
767 char *mc_adr
, *port
, *mc
;
769 mc_adr
= port
= mc
= NULL
;
770 /* march along looking for 'multicast\0', which has to start at least
771 * 14 bytes back from the end.
773 for (i
= 0; i
< len
-14; i
++)
774 if (strcmp(pkt
+i
, "multicast") == 0)
776 if (i
>= (len
-14)) /* non-Multicast OACK, ign. */
779 i
+= 10; /* strlen multicast */
781 for (; i
< len
; i
++) {
782 if (*(pkt
+i
) == ',') {
792 if (!port
|| !mc_adr
|| !mc
)
794 if (Multicast
&& MasterClient
) {
795 printf("I got a OACK as master Client, WRONG!\n");
798 /* ..I now accept packets destined for this MCAST addr, port */
801 printf("Internal failure! no mcast.\n");
807 /* I malloc instead of pre-declare; so that if the file ends
808 * up being too big for this bitmap I can retry
810 Bitmap
= malloc(Mapsize
);
812 printf("No Bitmap, no multicast. Sorry.\n");
816 memset(Bitmap
, 0, Mapsize
);
820 addr
= string_to_ip(mc_adr
);
821 if (Mcast_addr
!= addr
) {
823 eth_mcast_join(Mcast_addr
, 0);
825 if (eth_mcast_join(Mcast_addr
, 1)) {
826 printf("Fail to set mcast, revert to TFTP\n");
832 MasterClient
= (unsigned char)simple_strtoul((char *)mc
, NULL
, 10);
833 Mcast_port
= (unsigned short)simple_strtoul(port
, NULL
, 10);
834 printf("Multicast: %s:%d [%d]\n", mc_adr
, Mcast_port
, MasterClient
);
838 #endif /* Multicast TFTP */