tftp.c 22.2 KB
Newer Older
W
wdenk 已提交
1
/*
2 3 4
 * Copyright 1994, 1995, 2000 Neil Russell.
 * (See License)
 * Copyright 2000, 2001 DENX Software Engineering, Wolfgang Denk, wd@denx.de
5 6
 * Copyright 2011 Comelit Group SpA,
 *                Luca Ceresoli <luca.ceresoli@comelit.it>
W
wdenk 已提交
7 8 9 10 11 12 13 14
 */

#include <common.h>
#include <command.h>
#include <net.h>
#include "tftp.h"
#include "bootp.h"

15 16 17 18
/* Well known TFTP port # */
#define WELL_KNOWN_PORT	69
/* Millisecs to timeout for lost pkt */
#define TIMEOUT		5000UL
W
wdenk 已提交
19
#ifndef	CONFIG_NET_RETRY_COUNT
20 21
/* # of timeouts before giving up */
# define TIMEOUT_COUNT	10
W
wdenk 已提交
22 23 24
#else
# define TIMEOUT_COUNT  (CONFIG_NET_RETRY_COUNT * 2)
#endif
25 26
/* Number of "loading" hashes per line (for checking the image size) */
#define HASHES_PER_LINE	65
W
wdenk 已提交
27 28 29 30 31 32 33 34 35

/*
 *	TFTP operations.
 */
#define TFTP_RRQ	1
#define TFTP_WRQ	2
#define TFTP_DATA	3
#define TFTP_ACK	4
#define TFTP_ERROR	5
W
wdenk 已提交
36
#define TFTP_OACK	6
W
wdenk 已提交
37

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
static ulong TftpTimeoutMSecs = TIMEOUT;
static int TftpTimeoutCountMax = TIMEOUT_COUNT;

/*
 * These globals govern the timeout behavior when attempting a connection to a
 * TFTP server. TftpRRQTimeoutMSecs specifies the number of milliseconds to
 * wait for the server to respond to initial connection. Second global,
 * TftpRRQTimeoutCountMax, gives the number of such connection retries.
 * TftpRRQTimeoutCountMax must be non-negative and TftpRRQTimeoutMSecs must be
 * positive. The globals are meant to be set (and restored) by code needing
 * non-standard timeout behavior when initiating a TFTP transfer.
 */
ulong TftpRRQTimeoutMSecs = TIMEOUT;
int TftpRRQTimeoutCountMax = TIMEOUT_COUNT;

53 54 55 56 57 58 59 60 61 62
enum {
	TFTP_ERR_UNDEFINED           = 0,
	TFTP_ERR_FILE_NOT_FOUND      = 1,
	TFTP_ERR_ACCESS_DENIED       = 2,
	TFTP_ERR_DISK_FULL           = 3,
	TFTP_ERR_UNEXPECTED_OPCODE   = 4,
	TFTP_ERR_UNKNOWN_TRANSFER_ID  = 5,
	TFTP_ERR_FILE_ALREADY_EXISTS = 6,
};

63
static IPaddr_t TftpRemoteIP;
64
/* The UDP port at their end */
65
static int	TftpRemotePort;
66 67
/* The UDP port at our end */
static int	TftpOurPort;
W
wdenk 已提交
68
static int	TftpTimeoutCount;
69 70 71 72 73 74 75 76
/* packet sequence number */
static ulong	TftpBlock;
/* last packet sequence number received */
static ulong	TftpLastBlock;
/* count of sequence number wraparounds */
static ulong	TftpBlockWrap;
/* memory offset due to wrapping */
static ulong	TftpBlockWrapOffset;
W
wdenk 已提交
77
static int	TftpState;
R
Robin Getz 已提交
78
#ifdef CONFIG_TFTP_TSIZE
79 80 81 82
/* The file size reported by the server */
static int	TftpTsize;
/* The number of hashes we printed */
static short	TftpNumchars;
R
Robin Getz 已提交
83
#endif
S
Simon Glass 已提交
84 85 86 87 88 89
#ifdef CONFIG_CMD_TFTPPUT
static int	TftpWriting;	/* 1 if writing, else 0 */
static int	TftpFinalBlock;	/* 1 if we have sent the last block */
#else
#define TftpWriting	0
#endif
W
wdenk 已提交
90

91
#define STATE_SEND_RRQ	1
W
wdenk 已提交
92 93 94
#define STATE_DATA	2
#define STATE_TOO_LARGE	3
#define STATE_BAD_MAGIC	4
W
wdenk 已提交
95
#define STATE_OACK	5
96
#define STATE_RECV_WRQ	6
S
Simon Glass 已提交
97
#define STATE_SEND_WRQ	7
W
wdenk 已提交
98

99 100 101 102
/* default TFTP block size */
#define TFTP_BLOCK_SIZE		512
/* sequence number is 16 bit */
#define TFTP_SEQUENCE_SIZE	((ulong)(1<<16))
W
wdenk 已提交
103

W
wdenk 已提交
104 105
#define DEFAULT_NAME_LEN	(8 + 4 + 1)
static char default_filename[DEFAULT_NAME_LEN];
106 107 108 109 110 111 112 113

#ifndef CONFIG_TFTP_FILE_NAME_MAX_LEN
#define MAX_LEN 128
#else
#define MAX_LEN CONFIG_TFTP_FILE_NAME_MAX_LEN
#endif

static char tftp_filename[MAX_LEN];
W
wdenk 已提交
114

115
#ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
116
extern flash_info_t flash_info[];
W
wdenk 已提交
117 118
#endif

119 120
/* 512 is poor choice for ethernet, MTU is typically 1500.
 * Minus eth.hdrs thats 1468.  Can get 2x better throughput with
D
David Updegraff 已提交
121
 * almost-MTU block sizes.  At least try... fall back to 512 if need be.
122
 * (but those using CONFIG_IP_DEFRAG may want to set a larger block in cfg file)
D
David Updegraff 已提交
123
 */
124 125 126
#ifdef CONFIG_TFTP_BLOCKSIZE
#define TFTP_MTU_BLOCKSIZE CONFIG_TFTP_BLOCKSIZE
#else
D
David Updegraff 已提交
127
#define TFTP_MTU_BLOCKSIZE 1468
128 129
#endif

130 131
static unsigned short TftpBlkSize = TFTP_BLOCK_SIZE;
static unsigned short TftpBlkSizeOption = TFTP_MTU_BLOCKSIZE;
D
David Updegraff 已提交
132 133 134 135 136

#ifdef CONFIG_MCAST_TFTP
#include <malloc.h>
#define MTFTP_BITMAPSIZE	0x1000
static unsigned *Bitmap;
137
static int PrevBitmapHole, Mapsize = MTFTP_BITMAPSIZE;
138 139
static uchar ProhibitMcast, MasterClient;
static uchar Multicast;
D
David Updegraff 已提交
140 141 142 143
extern IPaddr_t Mcast_addr;
static int Mcast_port;
static ulong TftpEndingBlock; /* can get 'last' block before done..*/

144
static void parse_multicast_oack(char *pkt, int len);
D
David Updegraff 已提交
145 146 147 148

static void
mcast_cleanup(void)
{
149 150 151 152
	if (Mcast_addr)
		eth_mcast_join(Mcast_addr, 0);
	if (Bitmap)
		free(Bitmap);
153
	Bitmap = NULL;
D
David Updegraff 已提交
154 155 156 157 158 159
	Mcast_addr = Multicast = Mcast_port = 0;
	TftpEndingBlock = -1;
}

#endif	/* CONFIG_MCAST_TFTP */

W
wdenk 已提交
160
static __inline__ void
161
store_block(unsigned block, uchar *src, unsigned len)
W
wdenk 已提交
162
{
D
David Updegraff 已提交
163
	ulong offset = block * TftpBlkSize + TftpBlockWrapOffset;
W
wdenk 已提交
164
	ulong newsize = offset + len;
165
#ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
W
wdenk 已提交
166 167
	int i, rc = 0;

168
	for (i = 0; i < CONFIG_SYS_MAX_FLASH_BANKS; i++) {
W
wdenk 已提交
169
		/* start address in flash? */
J
Jochen Friedrich 已提交
170 171
		if (flash_info[i].flash_id == FLASH_UNKNOWN)
			continue;
W
wdenk 已提交
172 173 174 175 176 177 178
		if (load_addr + offset >= flash_info[i].start[0]) {
			rc = 1;
			break;
		}
	}

	if (rc) { /* Flash is destination for this packet */
179
		rc = flash_write((char *)src, (ulong)(load_addr+offset), len);
W
wdenk 已提交
180
		if (rc) {
181
			flash_perror(rc);
W
wdenk 已提交
182 183 184 185 186
			NetState = NETLOOP_FAIL;
			return;
		}
	}
	else
187
#endif /* CONFIG_SYS_DIRECT_FLASH_TFTP */
W
wdenk 已提交
188 189 190
	{
		(void)memcpy((void *)(load_addr + offset), src, len);
	}
D
David Updegraff 已提交
191 192 193 194
#ifdef CONFIG_MCAST_TFTP
	if (Multicast)
		ext2_set_bit(block, Bitmap);
#endif
W
wdenk 已提交
195 196 197 198 199

	if (NetBootFileXferSize < newsize)
		NetBootFileXferSize = newsize;
}

200
/* Clear our state ready for a new transfer */
201
static void new_transfer(void)
202 203 204 205 206 207 208 209 210
{
	TftpLastBlock = 0;
	TftpBlockWrap = 0;
	TftpBlockWrapOffset = 0;
#ifdef CONFIG_CMD_TFTPPUT
	TftpFinalBlock = 0;
#endif
}

S
Simon Glass 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
#ifdef CONFIG_CMD_TFTPPUT
/**
 * Load the next block from memory to be sent over tftp.
 *
 * @param block	Block number to send
 * @param dst	Destination buffer for data
 * @param len	Number of bytes in block (this one and every other)
 * @return number of bytes loaded
 */
static int load_block(unsigned block, uchar *dst, unsigned len)
{
	/* We may want to get the final block from the previous set */
	ulong offset = ((int)block - 1) * len + TftpBlockWrapOffset;
	ulong tosend = len;

	tosend = min(NetBootFileXferSize - offset, tosend);
	(void)memcpy(dst, (void *)(save_addr + offset), tosend);
	debug("%s: block=%d, offset=%ld, len=%d, tosend=%ld\n", __func__,
		block, offset, len, tosend);
	return tosend;
}
#endif

234 235
static void TftpSend(void);
static void TftpTimeout(void);
W
wdenk 已提交
236 237 238

/**********************************************************************/

239 240 241 242 243 244 245 246 247 248
static void show_block_marker(void)
{
#ifdef CONFIG_TFTP_TSIZE
	if (TftpTsize) {
		ulong pos = TftpBlock * TftpBlkSize + TftpBlockWrapOffset;

		while (TftpNumchars < pos * 50 / TftpTsize) {
			putc('#');
			TftpNumchars++;
		}
S
Simon Glass 已提交
249
	} else
250
#endif
S
Simon Glass 已提交
251
	{
252 253 254 255 256 257 258
		if (((TftpBlock - 1) % 10) == 0)
			putc('#');
		else if ((TftpBlock % (10 * HASHES_PER_LINE)) == 0)
			puts("\n\t ");
	}
}

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
/**
 * restart the current transfer due to an error
 *
 * @param msg	Message to print for user
 */
static void restart(const char *msg)
{
	printf("\n%s; starting again\n", msg);
#ifdef CONFIG_MCAST_TFTP
	mcast_cleanup();
#endif
	NetStartAgain();
}

/*
 * Check if the block number has wrapped, and update progress
 *
 * TODO: The egregious use of global variables in this file should be tidied.
 */
static void update_block_number(void)
{
	/*
	 * RFC1350 specifies that the first data packet will
	 * have sequence number 1. If we receive a sequence
	 * number of 0 this means that there was a wrap
	 * around of the (16 bit) counter.
	 */
	if (TftpBlock == 0) {
		TftpBlockWrap++;
		TftpBlockWrapOffset += TftpBlkSize * TFTP_SEQUENCE_SIZE;
		TftpTimeoutCount = 0; /* we've done well, reset thhe timeout */
	} else {
		show_block_marker();
	}
}

295 296 297 298 299 300 301 302 303 304 305 306 307 308
/* The TFTP get or put is complete */
static void tftp_complete(void)
{
#ifdef CONFIG_TFTP_TSIZE
	/* Print hash marks for the last packet received */
	while (TftpTsize && TftpNumchars < 49) {
		putc('#');
		TftpNumchars++;
	}
#endif
	puts("\ndone\n");
	NetState = NETLOOP_SUCCESS;
}

W
wdenk 已提交
309
static void
310
TftpSend(void)
W
wdenk 已提交
311
{
S
Simon Glass 已提交
312
	uchar *pkt;
313 314
	volatile uchar *xp;
	int		len = 0;
W
Wolfgang Denk 已提交
315
	volatile ushort *s;
W
wdenk 已提交
316

317
#ifdef CONFIG_MCAST_TFTP
D
David Updegraff 已提交
318
	/* Multicast TFTP.. non-MasterClients do not ACK data. */
319 320 321
	if (Multicast
	 && (TftpState == STATE_DATA)
	 && (MasterClient == 0))
D
David Updegraff 已提交
322 323
		return;
#endif
W
wdenk 已提交
324 325 326 327
	/*
	 *	We will always be sending some sort of packet, so
	 *	cobble together the packet headers now.
	 */
S
Simon Glass 已提交
328
	pkt = (uchar *)(NetTxPacket + NetEthHdrSize() + IP_HDR_SIZE);
W
wdenk 已提交
329 330

	switch (TftpState) {
331
	case STATE_SEND_RRQ:
S
Simon Glass 已提交
332
	case STATE_SEND_WRQ:
W
wdenk 已提交
333
		xp = pkt;
W
Wolfgang Denk 已提交
334
		s = (ushort *)pkt;
335
#ifdef CONFIG_CMD_TFTPPUT
S
Simon Glass 已提交
336 337
		*s++ = htons(TftpState == STATE_SEND_RRQ ? TFTP_RRQ :
			TFTP_WRQ);
338 339 340
#else
		*s++ = htons(TFTP_RRQ);
#endif
W
Wolfgang Denk 已提交
341
		pkt = (uchar *)s;
342
		strcpy((char *)pkt, tftp_filename);
W
wdenk 已提交
343
		pkt += strlen(tftp_filename) + 1;
344
		strcpy((char *)pkt, "octet");
W
wdenk 已提交
345
		pkt += 5 /*strlen("octet")*/ + 1;
346
		strcpy((char *)pkt, "timeout");
W
wdenk 已提交
347
		pkt += 7 /*strlen("timeout")*/ + 1;
348
		sprintf((char *)pkt, "%lu", TftpTimeoutMSecs / 1000);
R
Robin Getz 已提交
349
		debug("send option \"timeout %s\"\n", (char *)pkt);
W
wdenk 已提交
350
		pkt += strlen((char *)pkt) + 1;
R
Robin Getz 已提交
351
#ifdef CONFIG_TFTP_TSIZE
S
Simon Glass 已提交
352 353
		pkt += sprintf((char *)pkt, "tsize%c%lu%c",
				0, NetBootFileXferSize, 0);
R
Robin Getz 已提交
354
#endif
D
David Updegraff 已提交
355
		/* try for more effic. blk size */
356 357
		pkt += sprintf((char *)pkt, "blksize%c%d%c",
				0, TftpBlkSizeOption, 0);
358
#ifdef CONFIG_MCAST_TFTP
D
David Updegraff 已提交
359
		/* Check all preconditions before even trying the option */
360
		if (!ProhibitMcast
361
		 && (Bitmap = malloc(Mapsize))
D
David Updegraff 已提交
362 363
		 && eth_get_dev()->mcast) {
			free(Bitmap);
364 365
			Bitmap = NULL;
			pkt += sprintf((char *)pkt, "multicast%c%c", 0, 0);
D
David Updegraff 已提交
366 367
		}
#endif /* CONFIG_MCAST_TFTP */
W
wdenk 已提交
368 369 370
		len = pkt - xp;
		break;

W
wdenk 已提交
371
	case STATE_OACK:
D
David Updegraff 已提交
372 373 374
#ifdef CONFIG_MCAST_TFTP
		/* My turn!  Start at where I need blocks I missed.*/
		if (Multicast)
375 376
			TftpBlock = ext2_find_next_zero_bit(Bitmap,
							    (Mapsize*8), 0);
D
David Updegraff 已提交
377 378
		/*..falling..*/
#endif
379 380

	case STATE_RECV_WRQ:
D
David Updegraff 已提交
381
	case STATE_DATA:
W
wdenk 已提交
382
		xp = pkt;
W
Wolfgang Denk 已提交
383
		s = (ushort *)pkt;
S
Simon Glass 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396
		s[0] = htons(TFTP_ACK);
		s[1] = htons(TftpBlock);
		pkt = (uchar *)(s + 2);
#ifdef CONFIG_CMD_TFTPPUT
		if (TftpWriting) {
			int toload = TftpBlkSize;
			int loaded = load_block(TftpBlock, pkt, toload);

			s[0] = htons(TFTP_DATA);
			pkt += loaded;
			TftpFinalBlock = (loaded < toload);
		}
#endif
W
wdenk 已提交
397 398 399 400 401
		len = pkt - xp;
		break;

	case STATE_TOO_LARGE:
		xp = pkt;
W
Wolfgang Denk 已提交
402 403
		s = (ushort *)pkt;
		*s++ = htons(TFTP_ERROR);
S
Simon Glass 已提交
404 405
			*s++ = htons(3);

W
Wolfgang Denk 已提交
406
		pkt = (uchar *)s;
407
		strcpy((char *)pkt, "File too large");
W
wdenk 已提交
408 409 410 411 412 413
		pkt += 14 /*strlen("File too large")*/ + 1;
		len = pkt - xp;
		break;

	case STATE_BAD_MAGIC:
		xp = pkt;
W
Wolfgang Denk 已提交
414 415 416 417
		s = (ushort *)pkt;
		*s++ = htons(TFTP_ERROR);
		*s++ = htons(2);
		pkt = (uchar *)s;
418
		strcpy((char *)pkt, "File has bad magic");
W
wdenk 已提交
419 420 421 422 423
		pkt += 18 /*strlen("File has bad magic")*/ + 1;
		len = pkt - xp;
		break;
	}

424
	NetSendUDPPacket(NetServerEther, TftpRemoteIP, TftpRemotePort,
425
			 TftpOurPort, len);
W
wdenk 已提交
426 427
}

428
#ifdef CONFIG_CMD_TFTPPUT
S
Simon Glass 已提交
429 430 431 432 433 434 435 436
static void icmp_handler(unsigned type, unsigned code, unsigned dest,
			 IPaddr_t sip, unsigned src, uchar *pkt, unsigned len)
{
	if (type == ICMP_NOT_REACH && code == ICMP_NOT_REACH_PORT) {
		/* Oh dear the other end has gone away */
		restart("TFTP server died");
	}
}
437
#endif
S
Simon Glass 已提交
438

W
wdenk 已提交
439
static void
440 441
TftpHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src,
	    unsigned len)
W
wdenk 已提交
442 443
{
	ushort proto;
W
Wolfgang Denk 已提交
444
	ushort *s;
445
	int i;
W
wdenk 已提交
446 447

	if (dest != TftpOurPort) {
D
David Updegraff 已提交
448
#ifdef CONFIG_MCAST_TFTP
449
		if (Multicast
D
David Updegraff 已提交
450 451
		 && (!Mcast_port || (dest != Mcast_port)))
#endif
452
			return;
W
wdenk 已提交
453
	}
454
	if (TftpState != STATE_SEND_RRQ && src != TftpRemotePort &&
S
Simon Glass 已提交
455
	    TftpState != STATE_RECV_WRQ && TftpState != STATE_SEND_WRQ)
W
wdenk 已提交
456 457
		return;

458
	if (len < 2)
W
wdenk 已提交
459 460 461
		return;
	len -= 2;
	/* warning: don't use increment (++) in ntohs() macros!! */
W
Wolfgang Denk 已提交
462 463 464
	s = (ushort *)pkt;
	proto = *s++;
	pkt = (uchar *)s;
W
wdenk 已提交
465 466 467
	switch (ntohs(proto)) {

	case TFTP_RRQ:
S
Simon Glass 已提交
468 469
		break;

W
wdenk 已提交
470
	case TFTP_ACK:
S
Simon Glass 已提交
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
#ifdef CONFIG_CMD_TFTPPUT
		if (TftpWriting) {
			if (TftpFinalBlock) {
				tftp_complete();
			} else {
				/*
				 * Move to the next block. We want our block
				 * count to wrap just like the other end!
				 */
				int block = ntohs(*s);
				int ack_ok = (TftpBlock == block);

				TftpBlock = (unsigned short)(block + 1);
				update_block_number();
				if (ack_ok)
					TftpSend(); /* Send next data block */
			}
		}
#endif
W
wdenk 已提交
490
		break;
S
Simon Glass 已提交
491

W
wdenk 已提交
492 493 494
	default:
		break;

495 496 497 498 499 500
#ifdef CONFIG_CMD_TFTPSRV
	case TFTP_WRQ:
		debug("Got WRQ\n");
		TftpRemoteIP = sip;
		TftpRemotePort = src;
		TftpOurPort = 1024 + (get_timer(0) % 3072);
501
		new_transfer();
502 503 504 505
		TftpSend(); /* Send ACK(0) */
		break;
#endif

W
wdenk 已提交
506
	case TFTP_OACK:
507 508 509
		debug("Got OACK: %s %s\n",
			pkt,
			pkt + strlen((char *)pkt) + 1);
W
wdenk 已提交
510
		TftpState = STATE_OACK;
511
		TftpRemotePort = src;
512 513 514 515 516
		/*
		 * Check for 'blksize' option.
		 * Careful: "i" is signed, "len" is unsigned, thus
		 * something like "len-8" may give a *huge* number
		 */
517
		for (i = 0; i+8 < len; i++) {
518
			if (strcmp((char *)pkt+i, "blksize") == 0) {
519
				TftpBlkSize = (unsigned short)
520
					simple_strtoul((char *)pkt+i+8, NULL,
521
						       10);
R
Robin Getz 已提交
522
				debug("Blocksize ack: %s, %d\n",
523
					(char *)pkt+i+8, TftpBlkSize);
524
			}
R
Robin Getz 已提交
525
#ifdef CONFIG_TFTP_TSIZE
526 527
			if (strcmp((char *)pkt+i, "tsize") == 0) {
				TftpTsize = simple_strtoul((char *)pkt+i+6,
528
							   NULL, 10);
R
Robin Getz 已提交
529
				debug("size = %s, %d\n",
530
					 (char *)pkt+i+6, TftpTsize);
R
Robin Getz 已提交
531 532
			}
#endif
D
David Updegraff 已提交
533 534
		}
#ifdef CONFIG_MCAST_TFTP
535
		parse_multicast_oack((char *)pkt, len-1);
536
		if ((Multicast) && (!MasterClient))
D
David Updegraff 已提交
537 538 539
			TftpState = STATE_DATA;	/* passive.. */
		else
#endif
S
Simon Glass 已提交
540 541 542 543 544 545 546 547
#ifdef CONFIG_CMD_TFTPPUT
		if (TftpWriting) {
			/* Get ready to send the first block */
			TftpState = STATE_DATA;
			TftpBlock++;
		}
#endif
		TftpSend(); /* Send ACK or first data block */
W
wdenk 已提交
548
		break;
W
wdenk 已提交
549 550 551 552 553
	case TFTP_DATA:
		if (len < 2)
			return;
		len -= 2;
		TftpBlock = ntohs(*(ushort *)pkt);
W
wdenk 已提交
554

555
		update_block_number();
W
wdenk 已提交
556

557
		if (TftpState == STATE_SEND_RRQ)
R
Robin Getz 已提交
558
			debug("Server did not acknowledge timeout option!\n");
W
wdenk 已提交
559

560 561
		if (TftpState == STATE_SEND_RRQ || TftpState == STATE_OACK ||
		    TftpState == STATE_RECV_WRQ) {
W
wdenk 已提交
562
			/* first block received */
W
wdenk 已提交
563
			TftpState = STATE_DATA;
564
			TftpRemotePort = src;
565
			new_transfer();
W
wdenk 已提交
566

D
David Updegraff 已提交
567 568 569 570 571
#ifdef CONFIG_MCAST_TFTP
			if (Multicast) { /* start!=1 common if mcast */
				TftpLastBlock = TftpBlock - 1;
			} else
#endif
W
wdenk 已提交
572
			if (TftpBlock != 1) {	/* Assertion */
573 574 575
				printf("\nTFTP error: "
				       "First block is not block 1 (%ld)\n"
				       "Starting again\n\n",
W
wdenk 已提交
576
					TftpBlock);
577
				NetStartAgain();
W
wdenk 已提交
578 579 580 581 582 583 584 585 586 587 588 589
				break;
			}
		}

		if (TftpBlock == TftpLastBlock) {
			/*
			 *	Same block again; ignore it.
			 */
			break;
		}

		TftpLastBlock = TftpBlock;
590
		TftpTimeoutCountMax = TIMEOUT_COUNT;
591
		NetSetTimeout(TftpTimeoutMSecs, TftpTimeout);
W
wdenk 已提交
592

593
		store_block(TftpBlock - 1, pkt + 2, len);
W
wdenk 已提交
594 595

		/*
L
Luca Ceresoli 已提交
596
		 *	Acknowledge the block just received, which will prompt
597
		 *	the remote for the next one.
W
wdenk 已提交
598
		 */
D
David Updegraff 已提交
599
#ifdef CONFIG_MCAST_TFTP
600 601
		/* if I am the MasterClient, actively calculate what my next
		 * needed block is; else I'm passive; not ACKING
602
		 */
D
David Updegraff 已提交
603 604 605 606
		if (Multicast) {
			if (len < TftpBlkSize)  {
				TftpEndingBlock = TftpBlock;
			} else if (MasterClient) {
607
				TftpBlock = PrevBitmapHole =
D
David Updegraff 已提交
608 609 610 611 612
					ext2_find_next_zero_bit(
						Bitmap,
						(Mapsize*8),
						PrevBitmapHole);
				if (TftpBlock > ((Mapsize*8) - 1)) {
613
					printf("tftpfile too big\n");
D
David Updegraff 已提交
614
					/* try to double it and retry */
615
					Mapsize <<= 1;
D
David Updegraff 已提交
616
					mcast_cleanup();
617
					NetStartAgain();
D
David Updegraff 已提交
618 619 620 621 622 623
					return;
				}
				TftpLastBlock = TftpBlock;
			}
		}
#endif
624
		TftpSend();
W
wdenk 已提交
625

D
David Updegraff 已提交
626 627 628
#ifdef CONFIG_MCAST_TFTP
		if (Multicast) {
			if (MasterClient && (TftpBlock >= TftpEndingBlock)) {
629
				puts("\nMulticast tftp done\n");
D
David Updegraff 已提交
630 631
				mcast_cleanup();
				NetState = NETLOOP_SUCCESS;
632
			}
D
David Updegraff 已提交
633 634 635
		}
		else
#endif
636 637
		if (len < TftpBlkSize)
			tftp_complete();
W
wdenk 已提交
638 639 640
		break;

	case TFTP_ERROR:
641 642
		printf("\nTFTP error: '%s' (%d)\n",
		       pkt + 2, ntohs(*(ushort *)pkt));
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657

		switch (ntohs(*(ushort *)pkt)) {
		case TFTP_ERR_FILE_NOT_FOUND:
		case TFTP_ERR_ACCESS_DENIED:
			puts("Not retrying...\n");
			eth_halt();
			NetState = NETLOOP_FAIL;
			break;
		case TFTP_ERR_UNDEFINED:
		case TFTP_ERR_DISK_FULL:
		case TFTP_ERR_UNEXPECTED_OPCODE:
		case TFTP_ERR_UNKNOWN_TRANSFER_ID:
		case TFTP_ERR_FILE_ALREADY_EXISTS:
		default:
			puts("Starting again\n\n");
D
David Updegraff 已提交
658
#ifdef CONFIG_MCAST_TFTP
659
			mcast_cleanup();
D
David Updegraff 已提交
660
#endif
661 662 663
			NetStartAgain();
			break;
		}
W
wdenk 已提交
664 665 666 667 668 669
		break;
	}
}


static void
670
TftpTimeout(void)
W
wdenk 已提交
671
{
672
	if (++TftpTimeoutCount > TftpTimeoutCountMax) {
673
		restart("Retry count exceeded");
W
wdenk 已提交
674
	} else {
675 676
		puts("T ");
		NetSetTimeout(TftpTimeoutMSecs, TftpTimeout);
677 678
		if (TftpState != STATE_RECV_WRQ)
			TftpSend();
W
wdenk 已提交
679 680 681 682
	}
}


683
void TftpStart(enum proto_t protocol)
W
wdenk 已提交
684
{
685
	char *ep;             /* Environment pointer */
686

687 688 689 690
	/*
	 * Allow the user to choose TFTP blocksize and timeout.
	 * TFTP protocol has a minimal timeout of 1 second.
	 */
691 692
	ep = getenv("tftpblocksize");
	if (ep != NULL)
693
		TftpBlkSizeOption = simple_strtol(ep, NULL, 10);
694

695 696
	ep = getenv("tftptimeout");
	if (ep != NULL)
697 698 699 700 701 702 703 704 705 706 707
		TftpTimeoutMSecs = simple_strtol(ep, NULL, 10);

	if (TftpTimeoutMSecs < 1000) {
		printf("TFTP timeout (%ld ms) too low, "
			"set minimum = 1000 ms\n",
			TftpTimeoutMSecs);
		TftpTimeoutMSecs = 1000;
	}

	debug("TFTP blocksize = %i, timeout = %ld ms\n",
		TftpBlkSizeOption, TftpTimeoutMSecs);
708

709
	TftpRemoteIP = NetServerIP;
W
wdenk 已提交
710
	if (BootFile[0] == '\0') {
711
		sprintf(default_filename, "%02X%02X%02X%02X.img",
712 713 714
			NetOurIP & 0xFF,
			(NetOurIP >>  8) & 0xFF,
			(NetOurIP >> 16) & 0xFF,
715
			(NetOurIP >> 24) & 0xFF);
716 717 718

		strncpy(tftp_filename, default_filename, MAX_LEN);
		tftp_filename[MAX_LEN-1] = 0;
W
wdenk 已提交
719

720
		printf("*** Warning: no boot file name; using '%s'\n",
W
wdenk 已提交
721 722
			tftp_filename);
	} else {
723
		char *p = strchr(BootFile, ':');
724 725 726 727 728

		if (p == NULL) {
			strncpy(tftp_filename, BootFile, MAX_LEN);
			tftp_filename[MAX_LEN-1] = 0;
		} else {
729
			TftpRemoteIP = string_to_ip(BootFile);
P
Peter Tyser 已提交
730
			strncpy(tftp_filename, p + 1, MAX_LEN);
731 732
			tftp_filename[MAX_LEN-1] = 0;
		}
W
wdenk 已提交
733 734
	}

735
	printf("Using %s device\n", eth_get_name());
S
Simon Glass 已提交
736
	printf("TFTP %s server %pI4; our IP address is %pI4",
737 738 739 740 741 742
#ifdef CONFIG_CMD_TFTPPUT
	       protocol == TFTPPUT ? "to" : "from",
#else
		"from",
#endif
		&TftpRemoteIP, &NetOurIP);
W
wdenk 已提交
743 744 745

	/* Check if we need to send across this subnet */
	if (NetOurGatewayIP && NetOurSubnetMask) {
746
		IPaddr_t OurNet	= NetOurIP    & NetOurSubnetMask;
747
		IPaddr_t RemoteNet	= TftpRemoteIP & NetOurSubnetMask;
W
wdenk 已提交
748

749
		if (OurNet != RemoteNet)
750 751
			printf("; sending through gateway %pI4",
			       &NetOurGatewayIP);
W
wdenk 已提交
752
	}
753
	putc('\n');
W
wdenk 已提交
754

755
	printf("Filename '%s'.", tftp_filename);
W
wdenk 已提交
756 757

	if (NetBootFileSize) {
758 759
		printf(" Size is 0x%x Bytes = ", NetBootFileSize<<9);
		print_size(NetBootFileSize<<9, "");
W
wdenk 已提交
760 761
	}

762
	putc('\n');
S
Simon Glass 已提交
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
#ifdef CONFIG_CMD_TFTPPUT
	TftpWriting = (protocol == TFTPPUT);
	if (TftpWriting) {
		printf("Save address: 0x%lx\n", save_addr);
		printf("Save size:    0x%lx\n", save_size);
		NetBootFileXferSize = save_size;
		puts("Saving: *\b");
		TftpState = STATE_SEND_WRQ;
		new_transfer();
	} else
#endif
	{
		printf("Load address: 0x%lx\n", load_addr);
		puts("Loading: *\b");
		TftpState = STATE_SEND_RRQ;
	}
W
wdenk 已提交
779

780 781
	TftpTimeoutCountMax = TftpRRQTimeoutCountMax;

782 783
	NetSetTimeout(TftpTimeoutMSecs, TftpTimeout);
	NetSetHandler(TftpHandler);
784
#ifdef CONFIG_CMD_TFTPPUT
S
Simon Glass 已提交
785
	net_set_icmp_handler(icmp_handler);
786
#endif
787
	TftpRemotePort = WELL_KNOWN_PORT;
W
wdenk 已提交
788
	TftpTimeoutCount = 0;
789
	/* Use a pseudo-random port unless a specific port is set */
W
wdenk 已提交
790
	TftpOurPort = 1024 + (get_timer(0) % 3072);
D
David Updegraff 已提交
791

792
#ifdef CONFIG_TFTP_PORT
793
	ep = getenv("tftpdstp");
794
	if (ep != NULL)
795
		TftpRemotePort = simple_strtol(ep, NULL, 10);
796
	ep = getenv("tftpsrcp");
797
	if (ep != NULL)
798
		TftpOurPort = simple_strtol(ep, NULL, 10);
799
#endif
W
wdenk 已提交
800
	TftpBlock = 0;
W
wdenk 已提交
801

W
wdenk 已提交
802 803
	/* zero out server ether in case the server ip has changed */
	memset(NetServerEther, 0, 6);
D
David Updegraff 已提交
804 805 806
	/* Revert TftpBlkSize to dflt */
	TftpBlkSize = TFTP_BLOCK_SIZE;
#ifdef CONFIG_MCAST_TFTP
807
	mcast_cleanup();
D
David Updegraff 已提交
808
#endif
R
Robin Getz 已提交
809 810 811 812
#ifdef CONFIG_TFTP_TSIZE
	TftpTsize = 0;
	TftpNumchars = 0;
#endif
W
wdenk 已提交
813

814
	TftpSend();
W
wdenk 已提交
815 816
}

817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
#ifdef CONFIG_CMD_TFTPSRV
void
TftpStartServer(void)
{
	tftp_filename[0] = 0;

	printf("Using %s device\n", eth_get_name());
	printf("Listening for TFTP transfer on %pI4\n", &NetOurIP);
	printf("Load address: 0x%lx\n", load_addr);

	puts("Loading: *\b");

	TftpTimeoutCountMax = TIMEOUT_COUNT;
	TftpTimeoutCount = 0;
	TftpTimeoutMSecs = TIMEOUT;
	NetSetTimeout(TftpTimeoutMSecs, TftpTimeout);

	/* Revert TftpBlkSize to dflt */
	TftpBlkSize = TFTP_BLOCK_SIZE;
	TftpBlock = 0;
	TftpOurPort = WELL_KNOWN_PORT;

#ifdef CONFIG_TFTP_TSIZE
	TftpTsize = 0;
	TftpNumchars = 0;
#endif

	TftpState = STATE_RECV_WRQ;
	NetSetHandler(TftpHandler);
}
#endif /* CONFIG_CMD_TFTPSRV */

D
David Updegraff 已提交
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
#ifdef CONFIG_MCAST_TFTP
/* Credits: atftp project.
 */

/* pick up BcastAddr, Port, and whether I am [now] the master-client. *
 * Frame:
 *    +-------+-----------+---+-------~~-------+---+
 *    |  opc  | multicast | 0 | addr, port, mc | 0 |
 *    +-------+-----------+---+-------~~-------+---+
 * The multicast addr/port becomes what I listen to, and if 'mc' is '1' then
 * I am the new master-client so must send ACKs to DataBlocks.  If I am not
 * master-client, I'm a passive client, gathering what DataBlocks I may and
 * making note of which ones I got in my bitmask.
 * In theory, I never go from master->passive..
 * .. this comes in with pkt already pointing just past opc
 */
static void parse_multicast_oack(char *pkt, int len)
{
867 868 869
	int i;
	IPaddr_t addr;
	char *mc_adr, *port,  *mc;
D
David Updegraff 已提交
870

871
	mc_adr = port = mc = NULL;
D
David Updegraff 已提交
872 873 874
	/* march along looking for 'multicast\0', which has to start at least
	 * 14 bytes back from the end.
	 */
875 876
	for (i = 0; i < len-14; i++)
		if (strcmp(pkt+i, "multicast") == 0)
D
David Updegraff 已提交
877 878 879
			break;
	if (i >= (len-14)) /* non-Multicast OACK, ign. */
		return;
880

881
	i += 10; /* strlen multicast */
D
David Updegraff 已提交
882
	mc_adr = pkt+i;
883
	for (; i < len; i++) {
D
David Updegraff 已提交
884 885 886 887 888 889 890 891 892 893
		if (*(pkt+i) == ',') {
			*(pkt+i) = '\0';
			if (port) {
				mc = pkt+i+1;
				break;
			} else {
				port = pkt+i+1;
			}
		}
	}
894 895
	if (!port || !mc_adr || !mc)
		return;
D
David Updegraff 已提交
896
	if (Multicast && MasterClient) {
897
		printf("I got a OACK as master Client, WRONG!\n");
D
David Updegraff 已提交
898 899 900 901 902
		return;
	}
	/* ..I now accept packets destined for this MCAST addr, port */
	if (!Multicast) {
		if (Bitmap) {
903
			printf("Internal failure! no mcast.\n");
D
David Updegraff 已提交
904
			free(Bitmap);
905 906
			Bitmap = NULL;
			ProhibitMcast = 1;
D
David Updegraff 已提交
907 908 909
			return ;
		}
		/* I malloc instead of pre-declare; so that if the file ends
910 911
		 * up being too big for this bitmap I can retry
		 */
912 913
		Bitmap = malloc(Mapsize);
		if (!Bitmap) {
914 915
			printf("No Bitmap, no multicast. Sorry.\n");
			ProhibitMcast = 1;
D
David Updegraff 已提交
916 917
			return;
		}
918
		memset(Bitmap, 0, Mapsize);
D
David Updegraff 已提交
919 920 921 922 923 924 925
		PrevBitmapHole = 0;
		Multicast = 1;
	}
	addr = string_to_ip(mc_adr);
	if (Mcast_addr != addr) {
		if (Mcast_addr)
			eth_mcast_join(Mcast_addr, 0);
926 927
		Mcast_addr = addr;
		if (eth_mcast_join(Mcast_addr, 1)) {
928 929
			printf("Fail to set mcast, revert to TFTP\n");
			ProhibitMcast = 1;
D
David Updegraff 已提交
930 931 932 933
			mcast_cleanup();
			NetStartAgain();
		}
	}
934 935 936
	MasterClient = (unsigned char)simple_strtoul((char *)mc, NULL, 10);
	Mcast_port = (unsigned short)simple_strtoul(port, NULL, 10);
	printf("Multicast: %s:%d [%d]\n", mc_adr, Mcast_port, MasterClient);
D
David Updegraff 已提交
937 938 939 940
	return;
}

#endif /* Multicast TFTP */