]> Git Repo - J-u-boot.git/blob - net/tftp.c
Merge tag 'v2024.07-rc5' into next
[J-u-boot.git] / net / tftp.c
1 /*
2  * Copyright 1994, 1995, 2000 Neil Russell.
3  * (See License)
4  * Copyright 2000, 2001 DENX Software Engineering, Wolfgang Denk, [email protected]
5  * Copyright 2011 Comelit Group SpA,
6  *                Luca Ceresoli <[email protected]>
7  */
8 #include <command.h>
9 #include <display_options.h>
10 #include <efi_loader.h>
11 #include <env.h>
12 #include <image.h>
13 #include <lmb.h>
14 #include <log.h>
15 #include <mapmem.h>
16 #include <net.h>
17 #include <net6.h>
18 #include <asm/global_data.h>
19 #include <net/tftp.h>
20 #include "bootp.h"
21
22 DECLARE_GLOBAL_DATA_PTR;
23
24 /* Well known TFTP port # */
25 #define WELL_KNOWN_PORT 69
26 /* Millisecs to timeout for lost pkt */
27 #define TIMEOUT         5000UL
28 /* Number of "loading" hashes per line (for checking the image size) */
29 #define HASHES_PER_LINE 65
30
31 /*
32  *      TFTP operations.
33  */
34 #define TFTP_RRQ        1
35 #define TFTP_WRQ        2
36 #define TFTP_DATA       3
37 #define TFTP_ACK        4
38 #define TFTP_ERROR      5
39 #define TFTP_OACK       6
40
41 static ulong timeout_ms = TIMEOUT;
42 static int timeout_count_max = (CONFIG_NET_RETRY_COUNT * 2);
43 static ulong time_start;   /* Record time we started tftp */
44 static struct in6_addr tftp_remote_ip6;
45
46 /*
47  * These globals govern the timeout behavior when attempting a connection to a
48  * TFTP server. tftp_timeout_ms specifies the number of milliseconds to
49  * wait for the server to respond to initial connection. Second global,
50  * tftp_timeout_count_max, gives the number of such connection retries.
51  * tftp_timeout_count_max must be non-negative and tftp_timeout_ms must be
52  * positive. The globals are meant to be set (and restored) by code needing
53  * non-standard timeout behavior when initiating a TFTP transfer.
54  */
55 ulong tftp_timeout_ms = TIMEOUT;
56 int tftp_timeout_count_max = (CONFIG_NET_RETRY_COUNT * 2);
57
58 enum {
59         TFTP_ERR_UNDEFINED           = 0,
60         TFTP_ERR_FILE_NOT_FOUND      = 1,
61         TFTP_ERR_ACCESS_DENIED       = 2,
62         TFTP_ERR_DISK_FULL           = 3,
63         TFTP_ERR_UNEXPECTED_OPCODE   = 4,
64         TFTP_ERR_UNKNOWN_TRANSFER_ID  = 5,
65         TFTP_ERR_FILE_ALREADY_EXISTS = 6,
66         TFTP_ERR_OPTION_NEGOTIATION = 8,
67 };
68
69 static struct in_addr tftp_remote_ip;
70 /* The UDP port at their end */
71 static int      tftp_remote_port;
72 /* The UDP port at our end */
73 static int      tftp_our_port;
74 static int      timeout_count;
75 /* packet sequence number */
76 static ulong    tftp_cur_block;
77 /* last packet sequence number received */
78 static ulong    tftp_prev_block;
79 /* count of sequence number wraparounds */
80 static ulong    tftp_block_wrap;
81 /* memory offset due to wrapping */
82 static ulong    tftp_block_wrap_offset;
83 static int      tftp_state;
84 static ulong    tftp_load_addr;
85 #ifdef CONFIG_LMB
86 static ulong    tftp_load_size;
87 #endif
88 #ifdef CONFIG_TFTP_TSIZE
89 /* The file size reported by the server */
90 static int      tftp_tsize;
91 /* The number of hashes we printed */
92 static short    tftp_tsize_num_hash;
93 #endif
94 /* The window size negotiated */
95 static ushort   tftp_windowsize;
96 /* Next block to send ack to */
97 static ushort   tftp_next_ack;
98 /* Last nack block we send */
99 static ushort   tftp_last_nack;
100 #ifdef CONFIG_CMD_TFTPPUT
101 /* 1 if writing, else 0 */
102 static int      tftp_put_active;
103 /* 1 if we have sent the last block */
104 static int      tftp_put_final_block_sent;
105 #else
106 #define tftp_put_active 0
107 #endif
108
109 #define STATE_SEND_RRQ  1
110 #define STATE_DATA      2
111 #define STATE_TOO_LARGE 3
112 #define STATE_BAD_MAGIC 4
113 #define STATE_OACK      5
114 #define STATE_RECV_WRQ  6
115 #define STATE_SEND_WRQ  7
116 #define STATE_INVALID_OPTION    8
117
118 /* default TFTP block size */
119 #define TFTP_BLOCK_SIZE         512
120 #define TFTP_MTU_BLOCKSIZE6 (CONFIG_TFTP_BLOCKSIZE - 20)
121 /* sequence number is 16 bit */
122 #define TFTP_SEQUENCE_SIZE      ((ulong)(1<<16))
123
124 #define DEFAULT_NAME_LEN        (8 + 4 + 1)
125 static char default_filename[DEFAULT_NAME_LEN];
126
127 #ifndef CONFIG_TFTP_FILE_NAME_MAX_LEN
128 #define MAX_LEN 128
129 #else
130 #define MAX_LEN CONFIG_TFTP_FILE_NAME_MAX_LEN
131 #endif
132
133 static char tftp_filename[MAX_LEN];
134
135 /* 512 is poor choice for ethernet, MTU is typically 1500.
136  * Minus eth.hdrs thats 1468.  Can get 2x better throughput with
137  * almost-MTU block sizes.  At least try... fall back to 512 if need be.
138  * (but those using CONFIG_IP_DEFRAG may want to set a larger block in cfg file)
139  */
140
141 /* When windowsize is defined to 1,
142  * tftp behaves the same way as it was
143  * never declared
144  */
145 #ifdef CONFIG_TFTP_WINDOWSIZE
146 #define TFTP_WINDOWSIZE CONFIG_TFTP_WINDOWSIZE
147 #else
148 #define TFTP_WINDOWSIZE 1
149 #endif
150
151 static unsigned short tftp_block_size = TFTP_BLOCK_SIZE;
152 static unsigned short tftp_block_size_option = CONFIG_TFTP_BLOCKSIZE;
153 static unsigned short tftp_window_size_option = TFTP_WINDOWSIZE;
154
155 static inline int store_block(int block, uchar *src, unsigned int len)
156 {
157         ulong offset = block * tftp_block_size + tftp_block_wrap_offset -
158                         tftp_block_size;
159         ulong newsize = offset + len;
160         ulong store_addr = tftp_load_addr + offset;
161         void *ptr;
162
163 #ifdef CONFIG_LMB
164         ulong end_addr = tftp_load_addr + tftp_load_size;
165
166         if (!end_addr)
167                 end_addr = ULONG_MAX;
168
169         if (store_addr < tftp_load_addr ||
170             store_addr + len > end_addr) {
171                 puts("\nTFTP error: ");
172                 puts("trying to overwrite reserved memory...\n");
173                 return -1;
174         }
175 #endif
176         ptr = map_sysmem(store_addr, len);
177         memcpy(ptr, src, len);
178         unmap_sysmem(ptr);
179
180         if (net_boot_file_size < newsize)
181                 net_boot_file_size = newsize;
182
183         return 0;
184 }
185
186 /* Clear our state ready for a new transfer */
187 static void new_transfer(void)
188 {
189         tftp_prev_block = 0;
190         tftp_block_wrap = 0;
191         tftp_block_wrap_offset = 0;
192 #ifdef CONFIG_CMD_TFTPPUT
193         tftp_put_final_block_sent = 0;
194 #endif
195 }
196
197 #ifdef CONFIG_CMD_TFTPPUT
198 /**
199  * Load the next block from memory to be sent over tftp.
200  *
201  * @param block Block number to send
202  * @param dst   Destination buffer for data
203  * @param len   Number of bytes in block (this one and every other)
204  * Return: number of bytes loaded
205  */
206 static int load_block(unsigned block, uchar *dst, unsigned len)
207 {
208         /* We may want to get the final block from the previous set */
209         ulong offset = block * tftp_block_size + tftp_block_wrap_offset -
210                        tftp_block_size;
211         ulong tosend = len;
212
213         tosend = min(net_boot_file_size - offset, tosend);
214         (void)memcpy(dst, (void *)(image_save_addr + offset), tosend);
215         debug("%s: block=%u, offset=%lu, len=%u, tosend=%lu\n", __func__,
216               block, offset, len, tosend);
217         return tosend;
218 }
219 #endif
220
221 static void tftp_send(void);
222 static void tftp_timeout_handler(void);
223
224 /**********************************************************************/
225
226 static void show_block_marker(void)
227 {
228         ulong pos;
229
230 #ifdef CONFIG_TFTP_TSIZE
231         if (tftp_tsize) {
232                 pos = tftp_cur_block * tftp_block_size +
233                         tftp_block_wrap_offset;
234                 if (pos > tftp_tsize)
235                         pos = tftp_tsize;
236
237                 while (tftp_tsize_num_hash < pos * 50 / tftp_tsize) {
238                         putc('#');
239                         tftp_tsize_num_hash++;
240                 }
241         } else
242 #endif
243         {
244                 pos = (tftp_cur_block - 1) +
245                         (tftp_block_wrap * TFTP_SEQUENCE_SIZE);
246                 if ((pos % 10) == 0)
247                         putc('#');
248                 else if (((pos + 1) % (10 * HASHES_PER_LINE)) == 0)
249                         puts("\n\t ");
250         }
251 }
252
253 /**
254  * restart the current transfer due to an error
255  *
256  * @param msg   Message to print for user
257  */
258 static void restart(const char *msg)
259 {
260         printf("\n%s; starting again\n", msg);
261         net_start_again();
262 }
263
264 /*
265  * Check if the block number has wrapped, and update progress
266  *
267  * TODO: The egregious use of global variables in this file should be tidied.
268  */
269 static void update_block_number(void)
270 {
271         /*
272          * RFC1350 specifies that the first data packet will
273          * have sequence number 1. If we receive a sequence
274          * number of 0 this means that there was a wrap
275          * around of the (16 bit) counter.
276          */
277         if (tftp_cur_block == 0 && tftp_prev_block != 0) {
278                 tftp_block_wrap++;
279                 tftp_block_wrap_offset += tftp_block_size * TFTP_SEQUENCE_SIZE;
280                 timeout_count = 0; /* we've done well, reset the timeout */
281         }
282         show_block_marker();
283 }
284
285 /* The TFTP get or put is complete */
286 static void tftp_complete(void)
287 {
288 #ifdef CONFIG_TFTP_TSIZE
289         /* Print hash marks for the last packet received */
290         while (tftp_tsize && tftp_tsize_num_hash < 49) {
291                 putc('#');
292                 tftp_tsize_num_hash++;
293         }
294         puts("  ");
295         print_size(tftp_tsize, "");
296 #endif
297         time_start = get_timer(time_start);
298         if (time_start > 0) {
299                 puts("\n\t ");  /* Line up with "Loading: " */
300                 print_size(net_boot_file_size /
301                         time_start * 1000, "/s");
302         }
303         puts("\ndone\n");
304         if (!tftp_put_active)
305                 efi_set_bootdev("Net", "", tftp_filename,
306                                 map_sysmem(tftp_load_addr, 0),
307                                 net_boot_file_size);
308         net_set_state(NETLOOP_SUCCESS);
309 }
310
311 static void tftp_send(void)
312 {
313         uchar *pkt;
314         uchar *xp;
315         int len = 0;
316         ushort *s;
317         bool err_pkt = false;
318
319         /*
320          *      We will always be sending some sort of packet, so
321          *      cobble together the packet headers now.
322          */
323         if (IS_ENABLED(CONFIG_IPV6) && use_ip6)
324                 pkt = net_tx_packet + net_eth_hdr_size() +
325                       IP6_HDR_SIZE + UDP_HDR_SIZE;
326         else
327                 pkt = net_tx_packet + net_eth_hdr_size() + IP_UDP_HDR_SIZE;
328
329         switch (tftp_state) {
330         case STATE_SEND_RRQ:
331         case STATE_SEND_WRQ:
332                 xp = pkt;
333                 s = (ushort *)pkt;
334 #ifdef CONFIG_CMD_TFTPPUT
335                 *s++ = htons(tftp_state == STATE_SEND_RRQ ? TFTP_RRQ :
336                         TFTP_WRQ);
337 #else
338                 *s++ = htons(TFTP_RRQ);
339 #endif
340                 pkt = (uchar *)s;
341                 strcpy((char *)pkt, tftp_filename);
342                 pkt += strlen(tftp_filename) + 1;
343                 strcpy((char *)pkt, "octet");
344                 pkt += 5 /*strlen("octet")*/ + 1;
345                 strcpy((char *)pkt, "timeout");
346                 pkt += 7 /*strlen("timeout")*/ + 1;
347                 sprintf((char *)pkt, "%lu", timeout_ms / 1000);
348                 debug("send option \"timeout %s\"\n", (char *)pkt);
349                 pkt += strlen((char *)pkt) + 1;
350 #ifdef CONFIG_TFTP_TSIZE
351                 pkt += sprintf((char *)pkt, "tsize%c%u%c",
352                                 0, net_boot_file_size, 0);
353 #endif
354                 /* try for more effic. blk size */
355                 pkt += sprintf((char *)pkt, "blksize%c%d%c",
356                                 0, tftp_block_size_option, 0);
357
358                 /* try for more effic. window size.
359                  * Implemented only for tftp get.
360                  * Don't bother sending if it's 1
361                  */
362                 if (tftp_state == STATE_SEND_RRQ && tftp_window_size_option > 1)
363                         pkt += sprintf((char *)pkt, "windowsize%c%d%c",
364                                         0, tftp_window_size_option, 0);
365                 len = pkt - xp;
366                 break;
367
368         case STATE_OACK:
369
370         case STATE_RECV_WRQ:
371         case STATE_DATA:
372                 xp = pkt;
373                 s = (ushort *)pkt;
374                 s[0] = htons(TFTP_ACK);
375                 s[1] = htons(tftp_cur_block);
376                 pkt = (uchar *)(s + 2);
377 #ifdef CONFIG_CMD_TFTPPUT
378                 if (tftp_put_active) {
379                         int toload = tftp_block_size;
380                         int loaded = load_block(tftp_cur_block, pkt, toload);
381
382                         s[0] = htons(TFTP_DATA);
383                         pkt += loaded;
384                         tftp_put_final_block_sent = (loaded < toload);
385                 }
386 #endif
387                 len = pkt - xp;
388                 break;
389
390         case STATE_TOO_LARGE:
391                 xp = pkt;
392                 s = (ushort *)pkt;
393                 *s++ = htons(TFTP_ERROR);
394                         *s++ = htons(3);
395
396                 pkt = (uchar *)s;
397                 strcpy((char *)pkt, "File too large");
398                 pkt += 14 /*strlen("File too large")*/ + 1;
399                 len = pkt - xp;
400                 err_pkt = true;
401                 break;
402
403         case STATE_BAD_MAGIC:
404                 xp = pkt;
405                 s = (ushort *)pkt;
406                 *s++ = htons(TFTP_ERROR);
407                 *s++ = htons(2);
408                 pkt = (uchar *)s;
409                 strcpy((char *)pkt, "File has bad magic");
410                 pkt += 18 /*strlen("File has bad magic")*/ + 1;
411                 len = pkt - xp;
412                 err_pkt = true;
413                 break;
414
415         case STATE_INVALID_OPTION:
416                 xp = pkt;
417                 s = (ushort *)pkt;
418                 *s++ = htons(TFTP_ERROR);
419                 *s++ = htons(TFTP_ERR_OPTION_NEGOTIATION);
420                 pkt = (uchar *)s;
421                 strcpy((char *)pkt, "Option Negotiation Failed");
422                 /* strlen("Option Negotiation Failed") + NULL*/
423                 pkt += 25 + 1;
424                 len = pkt - xp;
425                 err_pkt = true;
426                 break;
427         }
428
429         if (IS_ENABLED(CONFIG_IPV6) && use_ip6)
430                 net_send_udp_packet6(net_server_ethaddr,
431                                      &tftp_remote_ip6,
432                                      tftp_remote_port,
433                                      tftp_our_port, len);
434         else
435                 net_send_udp_packet(net_server_ethaddr, tftp_remote_ip,
436                                     tftp_remote_port, tftp_our_port, len);
437
438         if (err_pkt)
439                 net_set_state(NETLOOP_FAIL);
440 }
441
442 #ifdef CONFIG_CMD_TFTPPUT
443 static void icmp_handler(unsigned type, unsigned code, unsigned dest,
444                          struct in_addr sip, unsigned src, uchar *pkt,
445                          unsigned len)
446 {
447         if (type == ICMP_NOT_REACH && code == ICMP_NOT_REACH_PORT) {
448                 /* Oh dear the other end has gone away */
449                 restart("TFTP server died");
450         }
451 }
452 #endif
453
454 static void tftp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
455                          unsigned src, unsigned len)
456 {
457         __be16 proto;
458         __be16 *s;
459         int i;
460         u16 timeout_val_rcvd;
461
462         if (dest != tftp_our_port) {
463                         return;
464         }
465         if (tftp_state != STATE_SEND_RRQ && src != tftp_remote_port &&
466             tftp_state != STATE_RECV_WRQ && tftp_state != STATE_SEND_WRQ)
467                 return;
468
469         if (len < 2)
470                 return;
471         len -= 2;
472         /* warning: don't use increment (++) in ntohs() macros!! */
473         s = (__be16 *)pkt;
474         proto = *s++;
475         pkt = (uchar *)s;
476         switch (ntohs(proto)) {
477         case TFTP_RRQ:
478                 break;
479
480         case TFTP_ACK:
481 #ifdef CONFIG_CMD_TFTPPUT
482                 if (tftp_put_active) {
483                         if (tftp_put_final_block_sent) {
484                                 tftp_complete();
485                         } else {
486                                 /*
487                                  * Move to the next block. We want our block
488                                  * count to wrap just like the other end!
489                                  */
490                                 int block = ntohs(*s);
491                                 int ack_ok = (tftp_cur_block == block);
492
493                                 tftp_prev_block = tftp_cur_block;
494                                 tftp_cur_block = (unsigned short)(block + 1);
495                                 update_block_number();
496                                 if (ack_ok)
497                                         tftp_send(); /* Send next data block */
498                         }
499                 }
500 #endif
501                 break;
502
503         default:
504                 break;
505
506 #ifdef CONFIG_CMD_TFTPSRV
507         case TFTP_WRQ:
508                 debug("Got WRQ\n");
509                 tftp_remote_ip = sip;
510                 tftp_remote_port = src;
511                 tftp_our_port = 1024 + (get_timer(0) % 3072);
512                 new_transfer();
513                 tftp_send(); /* Send ACK(0) */
514                 break;
515 #endif
516
517         case TFTP_OACK:
518                 debug("Got OACK: ");
519                 for (i = 0; i < len; i++) {
520                         if (pkt[i] == '\0')
521                                 debug(" ");
522                         else
523                                 debug("%c", pkt[i]);
524                 }
525                 debug("\n");
526                 tftp_state = STATE_OACK;
527                 tftp_remote_port = src;
528                 /*
529                  * Check for 'blksize' option.
530                  * Careful: "i" is signed, "len" is unsigned, thus
531                  * something like "len-8" may give a *huge* number
532                  */
533                 for (i = 0; i+8 < len; i++) {
534                         if (strcasecmp((char *)pkt + i, "blksize") == 0) {
535                                 tftp_block_size = (unsigned short)
536                                         dectoul((char *)pkt + i + 8, NULL);
537                                 debug("Blocksize oack: %s, %d\n",
538                                       (char *)pkt + i + 8, tftp_block_size);
539                                 if (tftp_block_size > tftp_block_size_option) {
540                                         printf("Invalid blk size(=%d)\n",
541                                                tftp_block_size);
542                                         tftp_state = STATE_INVALID_OPTION;
543                                 }
544                         }
545                         if (strcasecmp((char *)pkt + i, "timeout") == 0) {
546                                 timeout_val_rcvd = (unsigned short)
547                                         dectoul((char *)pkt + i + 8, NULL);
548                                 debug("Timeout oack: %s, %d\n",
549                                       (char *)pkt + i + 8, timeout_val_rcvd);
550                                 if (timeout_val_rcvd != (timeout_ms / 1000)) {
551                                         printf("Invalid timeout val(=%d s)\n",
552                                                timeout_val_rcvd);
553                                         tftp_state = STATE_INVALID_OPTION;
554                                 }
555                         }
556 #ifdef CONFIG_TFTP_TSIZE
557                         if (strcasecmp((char *)pkt + i, "tsize") == 0) {
558                                 tftp_tsize = dectoul((char *)pkt + i + 6,
559                                                      NULL);
560                                 debug("size = %s, %d\n",
561                                       (char *)pkt + i + 6, tftp_tsize);
562                         }
563 #endif
564                         if (strcasecmp((char *)pkt + i,  "windowsize") == 0) {
565                                 tftp_windowsize =
566                                         dectoul((char *)pkt + i + 11, NULL);
567                                 debug("windowsize = %s, %d\n",
568                                       (char *)pkt + i + 11, tftp_windowsize);
569                         }
570                 }
571
572                 tftp_next_ack = tftp_windowsize;
573
574 #ifdef CONFIG_CMD_TFTPPUT
575                 if (tftp_put_active && tftp_state == STATE_OACK) {
576                         /* Get ready to send the first block */
577                         tftp_state = STATE_DATA;
578                         tftp_cur_block++;
579                 }
580 #endif
581                 tftp_send(); /* Send ACK or first data block */
582                 break;
583         case TFTP_DATA:
584                 if (len < 2)
585                         return;
586                 len -= 2;
587
588                 if (ntohs(*(__be16 *)pkt) != (ushort)(tftp_cur_block + 1)) {
589                         debug("Received unexpected block: %d, expected: %d\n",
590                               ntohs(*(__be16 *)pkt),
591                               (ushort)(tftp_cur_block + 1));
592                         /*
593                          * Only ACK if the block count received is greater than
594                          * the expected block count, otherwise skip ACK.
595                          * (required to properly handle the server retransmitting
596                          *  the window)
597                          */
598                         if ((ushort)(tftp_cur_block + 1) - (short)(ntohs(*(__be16 *)pkt)) > 0)
599                                 break;
600                         /*
601                          * If one packet is dropped most likely
602                          * all other buffers in the window
603                          * that will arrive will cause a sending NACK.
604                          * This just overwellms the server, let's just send one.
605                          */
606                         if (tftp_last_nack != tftp_cur_block) {
607                                 tftp_send();
608                                 tftp_last_nack = tftp_cur_block;
609                                 tftp_next_ack = (ushort)(tftp_cur_block +
610                                                          tftp_windowsize);
611                         }
612                         break;
613                 }
614
615                 tftp_cur_block++;
616                 tftp_cur_block %= TFTP_SEQUENCE_SIZE;
617
618                 if (tftp_state == STATE_SEND_RRQ) {
619                         debug("Server did not acknowledge any options!\n");
620                         tftp_next_ack = tftp_windowsize;
621                 }
622
623                 if (tftp_state == STATE_SEND_RRQ || tftp_state == STATE_OACK ||
624                     tftp_state == STATE_RECV_WRQ) {
625                         /* first block received */
626                         tftp_state = STATE_DATA;
627                         tftp_remote_port = src;
628                         new_transfer();
629
630                         if (tftp_cur_block != 1) {      /* Assertion */
631                                 puts("\nTFTP error: ");
632                                 printf("First block is not block 1 (%ld)\n",
633                                        tftp_cur_block);
634                                 puts("Starting again\n\n");
635                                 net_start_again();
636                                 break;
637                         }
638                 }
639
640                 if (tftp_cur_block == tftp_prev_block) {
641                         /* Same block again; ignore it. */
642                         break;
643                 }
644
645                 update_block_number();
646                 tftp_prev_block = tftp_cur_block;
647                 timeout_count_max = tftp_timeout_count_max;
648                 net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
649
650                 if (store_block(tftp_cur_block, pkt + 2, len)) {
651                         eth_halt();
652                         net_set_state(NETLOOP_FAIL);
653                         break;
654                 }
655
656                 if (len < tftp_block_size) {
657                         tftp_send();
658                         tftp_complete();
659                         break;
660                 }
661
662                 /*
663                  *      Acknowledge the block just received, which will prompt
664                  *      the remote for the next one.
665                  */
666                 if (tftp_cur_block == tftp_next_ack) {
667                         tftp_send();
668                         tftp_next_ack += tftp_windowsize;
669                 }
670                 break;
671
672         case TFTP_ERROR:
673                 printf("\nTFTP error: '%s' (%d)\n",
674                        pkt + 2, ntohs(*(__be16 *)pkt));
675
676                 switch (ntohs(*(__be16 *)pkt)) {
677                 case TFTP_ERR_FILE_NOT_FOUND:
678                 case TFTP_ERR_ACCESS_DENIED:
679                         puts("Not retrying...\n");
680                         eth_halt();
681                         net_set_state(NETLOOP_FAIL);
682                         break;
683                 case TFTP_ERR_UNDEFINED:
684                 case TFTP_ERR_DISK_FULL:
685                 case TFTP_ERR_UNEXPECTED_OPCODE:
686                 case TFTP_ERR_UNKNOWN_TRANSFER_ID:
687                 case TFTP_ERR_FILE_ALREADY_EXISTS:
688                 default:
689                         puts("Starting again\n\n");
690                         net_start_again();
691                         break;
692                 }
693                 break;
694         }
695 }
696
697
698 static void tftp_timeout_handler(void)
699 {
700         if (++timeout_count > timeout_count_max) {
701                 restart("Retry count exceeded");
702         } else {
703                 puts("T ");
704                 net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
705                 if (tftp_state != STATE_RECV_WRQ)
706                         tftp_send();
707         }
708 }
709
710 /* Initialize tftp_load_addr and tftp_load_size from image_load_addr and lmb */
711 static int tftp_init_load_addr(void)
712 {
713 #ifdef CONFIG_LMB
714         struct lmb lmb;
715         phys_size_t max_size;
716
717         lmb_init_and_reserve(&lmb, gd->bd, (void *)gd->fdt_blob);
718
719         max_size = lmb_get_free_size(&lmb, image_load_addr);
720         if (!max_size)
721                 return -1;
722
723         tftp_load_size = max_size;
724 #endif
725         tftp_load_addr = image_load_addr;
726         return 0;
727 }
728
729 static int saved_tftp_block_size_option;
730 static void sanitize_tftp_block_size_option(enum proto_t protocol)
731 {
732         int cap, max_defrag;
733
734         switch (protocol) {
735         case TFTPGET:
736                 max_defrag = config_opt_enabled(CONFIG_IP_DEFRAG, CONFIG_NET_MAXDEFRAG, 0);
737                 if (max_defrag) {
738                         /* Account for IP, UDP and TFTP headers. */
739                         cap = max_defrag - (20 + 8 + 4);
740                         /* RFC2348 sets a hard upper limit. */
741                         cap = min(cap, 65464);
742                         break;
743                 }
744                 /*
745                  * If not CONFIG_IP_DEFRAG, cap at the same value as
746                  * for tftp put, namely normal MTU minus protocol
747                  * overhead.
748                  */
749                 fallthrough;
750         case TFTPPUT:
751         default:
752                 /*
753                  * U-Boot does not support IP fragmentation on TX, so
754                  * this must be small enough that it fits normal MTU
755                  * (and small enough that it fits net_tx_packet which
756                  * has room for PKTSIZE_ALIGN bytes).
757                  */
758                 cap = 1468;
759         }
760         if (tftp_block_size_option > cap) {
761                 printf("Capping tftp block size option to %d (was %d)\n",
762                        cap, tftp_block_size_option);
763                 saved_tftp_block_size_option = tftp_block_size_option;
764                 tftp_block_size_option = cap;
765         }
766 }
767
768 void tftp_start(enum proto_t protocol)
769 {
770         __maybe_unused char *ep;             /* Environment pointer */
771
772         if (saved_tftp_block_size_option) {
773                 tftp_block_size_option = saved_tftp_block_size_option;
774                 saved_tftp_block_size_option = 0;
775         }
776
777         if (IS_ENABLED(CONFIG_NET_TFTP_VARS)) {
778
779                 /*
780                  * Allow the user to choose TFTP blocksize and timeout.
781                  * TFTP protocol has a minimal timeout of 1 second.
782                  */
783
784                 ep = env_get("tftpblocksize");
785                 if (ep != NULL)
786                         tftp_block_size_option = simple_strtol(ep, NULL, 10);
787
788                 ep = env_get("tftpwindowsize");
789                 if (ep != NULL)
790                         tftp_window_size_option = simple_strtol(ep, NULL, 10);
791
792                 ep = env_get("tftptimeout");
793                 if (ep != NULL)
794                         timeout_ms = simple_strtol(ep, NULL, 10);
795
796                 if (timeout_ms < 1000) {
797                         printf("TFTP timeout (%ld ms) too low, set min = 1000 ms\n",
798                                timeout_ms);
799                         timeout_ms = 1000;
800                 }
801
802                 ep = env_get("tftptimeoutcountmax");
803                 if (ep != NULL)
804                         tftp_timeout_count_max = simple_strtol(ep, NULL, 10);
805
806                 if (tftp_timeout_count_max < 0) {
807                         printf("TFTP timeout count max (%d ms) negative, set to 0\n",
808                                tftp_timeout_count_max);
809                         tftp_timeout_count_max = 0;
810                 }
811         }
812
813         sanitize_tftp_block_size_option(protocol);
814
815         debug("TFTP blocksize = %i, TFTP windowsize = %d timeout = %ld ms\n",
816               tftp_block_size_option, tftp_window_size_option, timeout_ms);
817
818         if (IS_ENABLED(CONFIG_IPV6))
819                 tftp_remote_ip6 = net_server_ip6;
820
821         tftp_remote_ip = net_server_ip;
822         if (!net_parse_bootfile(&tftp_remote_ip, tftp_filename, MAX_LEN)) {
823                 sprintf(default_filename, "%02X%02X%02X%02X.img",
824                         net_ip.s_addr & 0xFF,
825                         (net_ip.s_addr >>  8) & 0xFF,
826                         (net_ip.s_addr >> 16) & 0xFF,
827                         (net_ip.s_addr >> 24) & 0xFF);
828
829                 strncpy(tftp_filename, default_filename, DEFAULT_NAME_LEN);
830                 tftp_filename[DEFAULT_NAME_LEN - 1] = 0;
831
832                 printf("*** Warning: no boot file name; using '%s'\n",
833                        tftp_filename);
834         }
835
836         if (IS_ENABLED(CONFIG_IPV6)) {
837                 if (use_ip6) {
838                         char *s, *e;
839                         size_t len;
840
841                         s = strchr(net_boot_file_name, '[');
842                         e = strchr(net_boot_file_name, ']');
843                         len = e - s;
844                         if (s && e) {
845                                 string_to_ip6(s + 1, len - 1, &tftp_remote_ip6);
846                                 strlcpy(tftp_filename, e + 2, MAX_LEN);
847                         } else {
848                                 strlcpy(tftp_filename, net_boot_file_name, MAX_LEN);
849                                 tftp_filename[MAX_LEN - 1] = 0;
850                         }
851                 }
852         }
853
854         printf("Using %s device\n", eth_get_name());
855
856         if (IS_ENABLED(CONFIG_IPV6) && use_ip6) {
857                 printf("TFTP from server %pI6c; our IP address is %pI6c",
858                        &tftp_remote_ip6, &net_ip6);
859
860                 if (tftp_block_size_option > TFTP_MTU_BLOCKSIZE6)
861                         tftp_block_size_option = TFTP_MTU_BLOCKSIZE6;
862         } else {
863                 printf("TFTP %s server %pI4; our IP address is %pI4",
864 #ifdef CONFIG_CMD_TFTPPUT
865                protocol == TFTPPUT ? "to" : "from",
866 #else
867                "from",
868 #endif
869                &tftp_remote_ip, &net_ip);
870         }
871
872         /* Check if we need to send across this subnet */
873         if (IS_ENABLED(CONFIG_IPV6) && use_ip6) {
874                 if (!ip6_addr_in_subnet(&net_ip6, &tftp_remote_ip6,
875                                         net_prefix_length))
876                         printf("; sending through gateway %pI6c",
877                                &net_gateway6);
878         } else if (net_gateway.s_addr && net_netmask.s_addr) {
879                 struct in_addr our_net;
880                 struct in_addr remote_net;
881
882                 our_net.s_addr = net_ip.s_addr & net_netmask.s_addr;
883                 remote_net.s_addr = tftp_remote_ip.s_addr & net_netmask.s_addr;
884                 if (our_net.s_addr != remote_net.s_addr)
885                         printf("; sending through gateway %pI4", &net_gateway);
886         }
887         putc('\n');
888
889         printf("Filename '%s'.", tftp_filename);
890
891         if (net_boot_file_expected_size_in_blocks) {
892                 printf(" Size is 0x%x Bytes = ",
893                        net_boot_file_expected_size_in_blocks << 9);
894                 print_size(net_boot_file_expected_size_in_blocks << 9, "");
895         }
896
897         putc('\n');
898 #ifdef CONFIG_CMD_TFTPPUT
899         tftp_put_active = (protocol == TFTPPUT);
900         if (tftp_put_active) {
901                 printf("Save address: 0x%lx\n", image_save_addr);
902                 printf("Save size:    0x%lx\n", image_save_size);
903                 net_boot_file_size = image_save_size;
904                 puts("Saving: *\b");
905                 tftp_state = STATE_SEND_WRQ;
906                 new_transfer();
907         } else
908 #endif
909         {
910                 if (tftp_init_load_addr()) {
911                         eth_halt();
912                         net_set_state(NETLOOP_FAIL);
913                         puts("\nTFTP error: ");
914                         puts("trying to overwrite reserved memory...\n");
915                         return;
916                 }
917                 printf("Load address: 0x%lx\n", tftp_load_addr);
918                 puts("Loading: *\b");
919                 tftp_state = STATE_SEND_RRQ;
920         }
921
922         time_start = get_timer(0);
923         timeout_count_max = tftp_timeout_count_max;
924
925         net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
926         net_set_udp_handler(tftp_handler);
927 #ifdef CONFIG_CMD_TFTPPUT
928         net_set_icmp_handler(icmp_handler);
929 #endif
930         tftp_remote_port = WELL_KNOWN_PORT;
931         timeout_count = 0;
932         /* Use a pseudo-random port unless a specific port is set */
933         tftp_our_port = 1024 + (get_timer(0) % 3072);
934
935 #ifdef CONFIG_TFTP_PORT
936         ep = env_get("tftpdstp");
937         if (ep != NULL)
938                 tftp_remote_port = simple_strtol(ep, NULL, 10);
939         ep = env_get("tftpsrcp");
940         if (ep != NULL)
941                 tftp_our_port = simple_strtol(ep, NULL, 10);
942 #endif
943         tftp_cur_block = 0;
944         tftp_windowsize = 1;
945         tftp_last_nack = 0;
946         /* zero out server ether in case the server ip has changed */
947         memset(net_server_ethaddr, 0, 6);
948         /* Revert tftp_block_size to dflt */
949         tftp_block_size = TFTP_BLOCK_SIZE;
950 #ifdef CONFIG_TFTP_TSIZE
951         tftp_tsize = 0;
952         tftp_tsize_num_hash = 0;
953 #endif
954
955         tftp_send();
956 }
957
958 #ifdef CONFIG_CMD_TFTPSRV
959 void tftp_start_server(void)
960 {
961         tftp_filename[0] = 0;
962
963         if (tftp_init_load_addr()) {
964                 eth_halt();
965                 net_set_state(NETLOOP_FAIL);
966                 puts("\nTFTP error: trying to overwrite reserved memory...\n");
967                 return;
968         }
969         printf("Using %s device\n", eth_get_name());
970         printf("Listening for TFTP transfer on %pI4\n", &net_ip);
971         printf("Load address: 0x%lx\n", tftp_load_addr);
972
973         puts("Loading: *\b");
974
975         timeout_count_max = tftp_timeout_count_max;
976         timeout_count = 0;
977         timeout_ms = TIMEOUT;
978         net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
979
980         /* Revert tftp_block_size to dflt */
981         tftp_block_size = TFTP_BLOCK_SIZE;
982         tftp_cur_block = 0;
983         tftp_our_port = WELL_KNOWN_PORT;
984         tftp_windowsize = 1;
985         tftp_next_ack = tftp_windowsize;
986
987 #ifdef CONFIG_TFTP_TSIZE
988         tftp_tsize = 0;
989         tftp_tsize_num_hash = 0;
990 #endif
991
992         tftp_state = STATE_RECV_WRQ;
993         net_set_udp_handler(tftp_handler);
994
995         /* zero out server ether in case the server ip has changed */
996         memset(net_server_ethaddr, 0, 6);
997 }
998 #endif /* CONFIG_CMD_TFTPSRV */
This page took 0.079639 seconds and 4 git commands to generate.