tftp: fix thinko in code shrink
[oweals/busybox.git] / networking / tftp.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * A simple tftp client/server for busybox.
4  * Tries to follow RFC1350.
5  * Only "octet" mode supported.
6  * Optional blocksize negotiation (RFC2347 + RFC2348)
7  *
8  * Copyright (C) 2001 Magnus Damm <damm@opensource.se>
9  *
10  * Parts of the code based on:
11  *
12  * atftp:  Copyright (C) 2000 Jean-Pierre Lefebvre <helix@step.polymtl.ca>
13  *                        and Remi Lefebvre <remi@debian.org>
14  *
15  * utftp:  Copyright (C) 1999 Uwe Ohse <uwe@ohse.de>
16  *
17  * tftpd added by Denys Vlasenko & Vladimir Dronnikov
18  *
19  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
20  */
21 //config:config TFTP
22 //config:       bool "tftp (11 kb)"
23 //config:       default y
24 //config:       help
25 //config:       Trivial File Transfer Protocol client. TFTP is usually used
26 //config:       for simple, small transfers such as a root image
27 //config:       for a network-enabled bootloader.
28 //config:
29 //config:config FEATURE_TFTP_PROGRESS_BAR
30 //config:       bool "Enable progress bar"
31 //config:       default y
32 //config:       depends on TFTP
33 //config:
34 //config:config FEATURE_TFTP_HPA_COMPAT
35 //config:       bool "tftp-hpa compat (support -c get/put FILE)"
36 //config:       default y
37 //config:       depends on TFTP
38 //config:
39 //config:config TFTPD
40 //config:       bool "tftpd (10 kb)"
41 //config:       default y
42 //config:       help
43 //config:       Trivial File Transfer Protocol server.
44 //config:       It expects that stdin is a datagram socket and a packet
45 //config:       is already pending on it. It will exit after one transfer.
46 //config:       In other words: it should be run from inetd in nowait mode,
47 //config:       or from udpsvd. Example: "udpsvd -E 0 69 tftpd DIR"
48 //config:
49 //config:config FEATURE_TFTP_GET
50 //config:       bool "Enable 'tftp get' and/or tftpd upload code"
51 //config:       default y
52 //config:       depends on TFTP || TFTPD
53 //config:       help
54 //config:       Add support for the GET command within the TFTP client. This allows
55 //config:       a client to retrieve a file from a TFTP server.
56 //config:       Also enable upload support in tftpd, if tftpd is selected.
57 //config:
58 //config:       Note: this option does _not_ make tftpd capable of download
59 //config:       (the usual operation people need from it)!
60 //config:
61 //config:config FEATURE_TFTP_PUT
62 //config:       bool "Enable 'tftp put' and/or tftpd download code"
63 //config:       default y
64 //config:       depends on TFTP || TFTPD
65 //config:       help
66 //config:       Add support for the PUT command within the TFTP client. This allows
67 //config:       a client to transfer a file to a TFTP server.
68 //config:       Also enable download support in tftpd, if tftpd is selected.
69 //config:
70 //config:config FEATURE_TFTP_BLOCKSIZE
71 //config:       bool "Enable 'blksize' and 'tsize' protocol options"
72 //config:       default y
73 //config:       depends on TFTP || TFTPD
74 //config:       help
75 //config:       Allow tftp to specify block size, and tftpd to understand
76 //config:       "blksize" and "tsize" options.
77 //config:
78 //config:config TFTP_DEBUG
79 //config:       bool "Enable debug"
80 //config:       default n
81 //config:       depends on TFTP || TFTPD
82 //config:       help
83 //config:       Make tftp[d] print debugging messages on stderr.
84 //config:       This is useful if you are diagnosing a bug in tftp[d].
85
86 //applet:#if ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT
87 //applet:IF_TFTP(APPLET(tftp, BB_DIR_USR_BIN, BB_SUID_DROP))
88 //applet:IF_TFTPD(APPLET(tftpd, BB_DIR_USR_SBIN, BB_SUID_DROP))
89 //applet:#endif
90
91 //kbuild:lib-$(CONFIG_TFTP) += tftp.o
92 //kbuild:lib-$(CONFIG_TFTPD) += tftp.o
93
94 //usage:#define tftp_trivial_usage
95 //usage:       "[OPTIONS] HOST [PORT]"
96 //usage:#define tftp_full_usage "\n\n"
97 //usage:       "Transfer a file from/to tftp server\n"
98 //usage:     "\n        -l FILE Local FILE"
99 //usage:     "\n        -r FILE Remote FILE"
100 //usage:        IF_FEATURE_TFTP_GET(
101 //usage:     "\n        -g      Get file"
102 //usage:        )
103 //usage:        IF_FEATURE_TFTP_PUT(
104 //usage:     "\n        -p      Put file"
105 //usage:        )
106 //usage:        IF_FEATURE_TFTP_BLOCKSIZE(
107 //usage:     "\n        -b SIZE Transfer blocks of SIZE octets"
108 //usage:        )
109 ///////:     "\n        -m STR  Accepted and ignored ('-m binary' compat with tftp-hpa 5.2)"
110 //usage:
111 //usage:#define tftpd_trivial_usage
112 //usage:       "[-crl] [-u USER] [DIR]"
113 //usage:#define tftpd_full_usage "\n\n"
114 //usage:       "Transfer a file on tftp client's request\n"
115 //usage:       "\n"
116 //usage:       "tftpd should be used as an inetd service.\n"
117 //usage:       "tftpd's line for inetd.conf:\n"
118 //usage:       "        69 dgram udp nowait root tftpd tftpd -l /files/to/serve\n"
119 //usage:       "It also can be ran from udpsvd:\n"
120 //usage:       "        udpsvd -vE 0.0.0.0 69 tftpd /files/to/serve\n"
121 //usage:     "\n        -r      Prohibit upload"
122 //usage:     "\n        -c      Allow file creation via upload"
123 //usage:     "\n        -u      Access files as USER"
124 //usage:     "\n        -l      Log to syslog (inetd mode requires this)"
125
126 #include "libbb.h"
127 #include "common_bufsiz.h"
128 #include <syslog.h>
129
130 #if ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT
131
132 #define TFTP_BLKSIZE_DEFAULT       512  /* according to RFC 1350, don't change */
133 #define TFTP_BLKSIZE_DEFAULT_STR "512"
134 /* Was 50 ms but users asked to bump it up a bit */
135 #define TFTP_TIMEOUT_MS            100
136 #define TFTP_MAXTIMEOUT_MS        2000
137 #define TFTP_NUM_RETRIES            12  /* number of backed-off retries */
138
139 /* opcodes we support */
140 #define TFTP_RRQ   1
141 #define TFTP_WRQ   2
142 #define TFTP_DATA  3
143 #define TFTP_ACK   4
144 #define TFTP_ERROR 5
145 #define TFTP_OACK  6
146
147 /* error codes sent over network (we use only 0, 1, 3 and 8) */
148 /* generic (error message is included in the packet) */
149 #define ERR_UNSPEC   0
150 #define ERR_NOFILE   1
151 #define ERR_ACCESS   2
152 /* disk full or allocation exceeded */
153 #define ERR_WRITE    3
154 #define ERR_OP       4
155 #define ERR_BAD_ID   5
156 #define ERR_EXIST    6
157 #define ERR_BAD_USER 7
158 #define ERR_BAD_OPT  8
159
160 /* masks coming from getopt32 */
161 enum {
162         TFTP_OPT_GET = (1 << 0),
163         TFTP_OPT_PUT = (1 << 1),
164         /* pseudo option: if set, it's tftpd */
165         TFTPD_OPT = (1 << 7) * ENABLE_TFTPD,
166         TFTPD_OPT_r = (1 << 8) * ENABLE_TFTPD,
167         TFTPD_OPT_c = (1 << 9) * ENABLE_TFTPD,
168         TFTPD_OPT_u = (1 << 10) * ENABLE_TFTPD,
169         TFTPD_OPT_l = (1 << 11) * ENABLE_TFTPD,
170 };
171
172 #if ENABLE_FEATURE_TFTP_GET && !ENABLE_FEATURE_TFTP_PUT
173 #define IF_GETPUT(...)
174 #define CMD_GET(cmd) 1
175 #define CMD_PUT(cmd) 0
176 #elif !ENABLE_FEATURE_TFTP_GET && ENABLE_FEATURE_TFTP_PUT
177 #define IF_GETPUT(...)
178 #define CMD_GET(cmd) 0
179 #define CMD_PUT(cmd) 1
180 #else
181 #define IF_GETPUT(...) __VA_ARGS__
182 #define CMD_GET(cmd) ((cmd) & TFTP_OPT_GET)
183 #define CMD_PUT(cmd) ((cmd) & TFTP_OPT_PUT)
184 #endif
185 /* NB: in the code below
186  * CMD_GET(cmd) and CMD_PUT(cmd) are mutually exclusive
187  */
188
189
190 struct globals {
191         /* u16 TFTP_ERROR; u16 reason; both network-endian, then error text: */
192         uint8_t error_pkt[4 + 32];
193         struct passwd *pw;
194         /* Used in tftpd_main() for initial packet */
195         /* Some HP PA-RISC firmware always sends fixed 516-byte requests */
196         char block_buf[516];
197         char block_buf_tail[1];
198 #if ENABLE_FEATURE_TFTP_PROGRESS_BAR
199         off_t pos;
200         off_t size;
201         const char *file;
202         bb_progress_t pmt;
203 #endif
204 } FIX_ALIASING;
205 #define G (*(struct globals*)bb_common_bufsiz1)
206 #define INIT_G() do { \
207         setup_common_bufsiz(); \
208         BUILD_BUG_ON(sizeof(G) > COMMON_BUFSIZE); \
209 } while (0)
210
211 #define G_error_pkt_reason (G.error_pkt[3])
212 #define G_error_pkt_str    ((char*)(G.error_pkt + 4))
213
214 #if ENABLE_FEATURE_TFTP_PROGRESS_BAR && ENABLE_FEATURE_TFTP_BLOCKSIZE
215 static void tftp_progress_update(void)
216 {
217         bb_progress_update(&G.pmt, 0, G.pos, G.size);
218 }
219 static void tftp_progress_init(void)
220 {
221         bb_progress_init(&G.pmt, G.file);
222         tftp_progress_update();
223 }
224 static void tftp_progress_done(void)
225 {
226         if (is_bb_progress_inited(&G.pmt)) {
227                 tftp_progress_update();
228                 bb_putchar_stderr('\n');
229                 bb_progress_free(&G.pmt);
230         }
231 }
232 #else
233 # define tftp_progress_update() ((void)0)
234 # define tftp_progress_init() ((void)0)
235 # define tftp_progress_done() ((void)0)
236 #endif
237
238 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
239
240 static int tftp_blksize_check(const char *blksize_str, int maxsize)
241 {
242         /* Check if the blksize is valid:
243          * RFC2348 says between 8 and 65464,
244          * but our implementation makes it impossible
245          * to use blksizes smaller than 22 octets. */
246         unsigned blksize = bb_strtou(blksize_str, NULL, 10);
247         if (errno
248          || (blksize < 24) || (blksize > maxsize)
249         ) {
250                 bb_error_msg("bad blocksize '%s'", blksize_str);
251                 return -1;
252         }
253 # if ENABLE_TFTP_DEBUG
254         bb_info_msg("using blksize %u", blksize);
255 # endif
256         return blksize;
257 }
258
259 static char *tftp_get_option(const char *option, char *buf, int len)
260 {
261         int opt_val = 0;
262         int opt_found = 0;
263         int k;
264
265         /* buf points to:
266          * "opt_name<NUL>opt_val<NUL>opt_name2<NUL>opt_val2<NUL>..." */
267
268         while (len > 0) {
269                 /* Make sure options are terminated correctly */
270                 for (k = 0; k < len; k++) {
271                         if (buf[k] == '\0') {
272                                 goto nul_found;
273                         }
274                 }
275                 return NULL;
276  nul_found:
277                 if (opt_val == 0) { /* it's "name" part */
278                         if (strcasecmp(buf, option) == 0) {
279                                 opt_found = 1;
280                         }
281                 } else if (opt_found) {
282                         return buf;
283                 }
284
285                 k++;
286                 buf += k;
287                 len -= k;
288                 opt_val ^= 1;
289         }
290
291         return NULL;
292 }
293
294 #endif
295
296 static int tftp_protocol(
297                 /* NULL if tftp, !NULL if tftpd: */
298                 len_and_sockaddr *our_lsa,
299                 len_and_sockaddr *peer_lsa,
300                 const char *local_file
301                 IF_TFTP(, const char *remote_file)
302 #if !ENABLE_TFTP
303 # define remote_file NULL
304 #endif
305                 /* 1 for tftp; 1/0 for tftpd depending whether client asked about it: */
306                 IF_FEATURE_TFTP_BLOCKSIZE(, int want_transfer_size)
307                 IF_FEATURE_TFTP_BLOCKSIZE(, int blksize))
308 {
309 #if !ENABLE_FEATURE_TFTP_BLOCKSIZE
310         enum { blksize = TFTP_BLKSIZE_DEFAULT };
311 #endif
312
313         struct pollfd pfd[1];
314 #define socket_fd (pfd[0].fd)
315         int len;
316         int send_len;
317         IF_FEATURE_TFTP_BLOCKSIZE(smallint expect_OACK = 0;)
318         smallint finished = 0;
319         uint16_t opcode;
320         uint16_t block_nr;
321         uint16_t recv_blk;
322         int open_mode, local_fd;
323         int retries, waittime_ms;
324         int io_bufsize = blksize + 4;
325         char *cp;
326         /* Can't use RESERVE_CONFIG_BUFFER here since the allocation
327          * size varies meaning BUFFERS_GO_ON_STACK would fail.
328          *
329          * We must keep the transmit and receive buffers separate
330          * in case we rcv a garbage pkt - we need to rexmit the last pkt.
331          */
332         char *xbuf = xmalloc(io_bufsize);
333         char *rbuf = xmalloc(io_bufsize);
334
335         socket_fd = xsocket(peer_lsa->u.sa.sa_family, SOCK_DGRAM, 0);
336         setsockopt_reuseaddr(socket_fd);
337
338         if (!ENABLE_TFTP || our_lsa) { /* tftpd */
339                 /* Create a socket which is:
340                  * 1. bound to IP:port peer sent 1st datagram to,
341                  * 2. connected to peer's IP:port
342                  * This way we will answer from the IP:port peer
343                  * expects, will not get any other packets on
344                  * the socket, and also plain read/write will work. */
345                 xbind(socket_fd, &our_lsa->u.sa, our_lsa->len);
346                 xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
347
348                 /* Is there an error already? Send pkt and bail out */
349                 if (G_error_pkt_reason || G_error_pkt_str[0])
350                         goto send_err_pkt;
351
352                 if (G.pw) {
353                         change_identity(G.pw); /* initgroups, setgid, setuid */
354                 }
355         }
356
357         /* Prepare open mode */
358         if (CMD_PUT(option_mask32)) {
359                 open_mode = O_RDONLY;
360         } else {
361                 open_mode = O_WRONLY | O_TRUNC | O_CREAT;
362 #if ENABLE_TFTPD
363                 if ((option_mask32 & (TFTPD_OPT+TFTPD_OPT_c)) == TFTPD_OPT) {
364                         /* tftpd without -c */
365                         open_mode = O_WRONLY | O_TRUNC;
366                 }
367 #endif
368         }
369
370         /* Examples of network traffic.
371          * Note two cases when ACKs with block# of 0 are sent.
372          *
373          * Download without options:
374          * tftp -> "\0\1FILENAME\0octet\0"
375          *         "\0\3\0\1FILEDATA..." <- tftpd
376          * tftp -> "\0\4\0\1"
377          * ...
378          * Download with option of blksize 16384:
379          * tftp -> "\0\1FILENAME\0octet\0blksize\00016384\0"
380          *         "\0\6blksize\00016384\0" <- tftpd
381          * tftp -> "\0\4\0\0"
382          *         "\0\3\0\1FILEDATA..." <- tftpd
383          * tftp -> "\0\4\0\1"
384          * ...
385          * Upload without options:
386          * tftp -> "\0\2FILENAME\0octet\0"
387          *         "\0\4\0\0" <- tftpd
388          * tftp -> "\0\3\0\1FILEDATA..."
389          *         "\0\4\0\1" <- tftpd
390          * ...
391          * Upload with option of blksize 16384:
392          * tftp -> "\0\2FILENAME\0octet\0blksize\00016384\0"
393          *         "\0\6blksize\00016384\0" <- tftpd
394          * tftp -> "\0\3\0\1FILEDATA..."
395          *         "\0\4\0\1" <- tftpd
396          * ...
397          */
398         block_nr = 1;
399         cp = xbuf + 2;
400
401         if (!ENABLE_TFTP || our_lsa) { /* tftpd */
402                 /* Open file (must be after changing user) */
403                 local_fd = open(local_file, open_mode, 0666);
404                 if (local_fd < 0) {
405                         /* sanitize name, it came from untrusted remote side */
406                         unsigned char *p = (void *) local_file;
407                         while (*p) {
408                                 if (*p < ' ')
409                                         *p = '?';
410                                 p++;
411                         }
412                         bb_perror_msg("can't open '%s'", local_file);
413                         G_error_pkt_reason = ERR_NOFILE;
414                         strcpy(G_error_pkt_str, "can't open file");
415                         goto send_err_pkt_nomsg;
416                 }
417 /* gcc 4.3.1 would NOT optimize it out as it should! */
418 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
419                 if (blksize != TFTP_BLKSIZE_DEFAULT || want_transfer_size) {
420                         /* Create and send OACK packet. */
421                         /* For the download case, block_nr is still 1 -
422                          * we expect 1st ACK from peer to be for (block_nr-1),
423                          * that is, for "block 0" which is our OACK pkt */
424                         opcode = TFTP_OACK;
425                         goto add_blksize_opt;
426                 }
427 #endif
428                 if (CMD_GET(option_mask32)) {
429                         /* It's upload and we don't send OACK.
430                          * We must ACK 1st packet (with filename)
431                          * as if it is "block 0" */
432                         block_nr = 0;
433                 }
434         } else { /* tftp */
435                 /* Open file (must be after changing user) */
436                 local_fd = CMD_GET(option_mask32) ? STDOUT_FILENO : STDIN_FILENO;
437                 if (NOT_LONE_DASH(local_file))
438                         local_fd = xopen(local_file, open_mode);
439 /* Removing #if, or using if() statement instead of #if may lead to
440  * "warning: null argument where non-null required": */
441 #if ENABLE_TFTP
442                 /* tftp */
443
444                 /* We can't (and don't really need to) bind the socket:
445                  * we don't know from which local IP datagrams will be sent,
446                  * but kernel will pick the same IP every time (unless routing
447                  * table is changed), thus peer will see dgrams consistently
448                  * coming from the same IP.
449                  * We would like to connect the socket, but since peer's
450                  * UDP code can be less perfect than ours, _peer's_ IP:port
451                  * in replies may differ from IP:port we used to send
452                  * our first packet. We can connect() only when we get
453                  * first reply. */
454
455                 /* build opcode */
456                 opcode = TFTP_WRQ;
457                 if (CMD_GET(option_mask32)) {
458                         opcode = TFTP_RRQ;
459                 }
460                 /* add filename and mode */
461                 /* fill in packet if the filename fits into xbuf */
462                 len = strlen(remote_file);
463                 if (len + 3 + sizeof("octet") >= io_bufsize) {
464                         bb_simple_error_msg("remote filename is too long");
465                         goto ret;
466                 }
467                 cp = stpcpy(cp, remote_file) + 1;
468                 /* add "mode" part of the packet */
469                 cp = stpcpy(cp, "octet") + 1;
470
471 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
472                 if (blksize == TFTP_BLKSIZE_DEFAULT && !want_transfer_size)
473                         goto send_pkt;
474
475                 /* Need to add option to pkt */
476                 if ((&xbuf[io_bufsize - 1] - cp) < sizeof("blksize NNNNN tsize ") + sizeof(off_t)*3) {
477                         bb_simple_error_msg("remote filename is too long");
478                         goto ret;
479                 }
480                 expect_OACK = 1;
481 # endif
482 #endif /* ENABLE_TFTP */
483
484 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
485  add_blksize_opt:
486                 if (blksize != TFTP_BLKSIZE_DEFAULT) {
487                         /* add "blksize", <nul>, blksize, <nul> */
488                         strcpy(cp, "blksize");
489                         cp += sizeof("blksize");
490                         cp += snprintf(cp, 6, "%d", blksize) + 1;
491                 }
492                 if (want_transfer_size) {
493                         /* add "tsize", <nul>, size, <nul> (see RFC2349) */
494                         /* if tftp and downloading, we send "0" (since we opened local_fd with O_TRUNC)
495                          * and this makes server to send "tsize" option with the size */
496                         /* if tftp and uploading, we send file size (maybe dont, to not confuse old servers???) */
497                         /* if tftpd and downloading, we are answering to client's request */
498                         /* if tftpd and uploading: !want_transfer_size, this code is not executed */
499                         struct stat st;
500                         strcpy(cp, "tsize");
501                         cp += sizeof("tsize");
502                         st.st_size = 0;
503                         fstat(local_fd, &st);
504                         cp += sprintf(cp, "%"OFF_FMT"u", (off_t)st.st_size) + 1;
505 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
506                         /* Save for progress bar. If 0 (tftp downloading),
507                          * we look at server's reply later */
508                         G.size = st.st_size;
509                         if (remote_file && st.st_size)
510                                 tftp_progress_init();
511 # endif
512                 }
513 #endif
514                 /* First packet is built, so skip packet generation */
515                 goto send_pkt;
516         }
517
518         /* Using mostly goto's - continue/break will be less clear
519          * in where we actually jump to */
520         while (1) {
521                 /* Build ACK or DATA */
522                 cp = xbuf + 2;
523                 *((uint16_t*)cp) = htons(block_nr);
524                 cp += 2;
525                 block_nr++;
526                 opcode = TFTP_ACK;
527                 if (CMD_PUT(option_mask32)) {
528                         opcode = TFTP_DATA;
529                         len = full_read(local_fd, cp, blksize);
530                         if (len < 0) {
531                                 goto send_read_err_pkt;
532                         }
533                         if (len != blksize) {
534                                 finished = 1;
535                         }
536                         cp += len;
537                         IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += len;)
538                 }
539  send_pkt:
540                 /* Send packet */
541                 *((uint16_t*)xbuf) = htons(opcode); /* fill in opcode part */
542                 send_len = cp - xbuf;
543                 /* NB: send_len value is preserved in code below
544                  * for potential resend */
545
546                 retries = TFTP_NUM_RETRIES;  /* re-initialize */
547                 waittime_ms = TFTP_TIMEOUT_MS;
548
549  send_again:
550 #if ENABLE_TFTP_DEBUG
551                 fprintf(stderr, "sending %u bytes\n", send_len);
552                 for (cp = xbuf; cp < &xbuf[send_len]; cp++)
553                         fprintf(stderr, "%02x ", (unsigned char) *cp);
554                 fprintf(stderr, "\n");
555 #endif
556                 xsendto(socket_fd, xbuf, send_len, &peer_lsa->u.sa, peer_lsa->len);
557
558 #if ENABLE_FEATURE_TFTP_PROGRESS_BAR
559                 if (is_bb_progress_inited(&G.pmt))
560                         tftp_progress_update();
561 #endif
562                 /* Was it final ACK? then exit */
563                 if (finished && (opcode == TFTP_ACK))
564                         goto ret;
565
566  recv_again:
567                 /* Receive packet */
568                 /*pfd[0].fd = socket_fd;*/
569                 pfd[0].events = POLLIN;
570                 switch (safe_poll(pfd, 1, waittime_ms)) {
571                 default:
572                         /*bb_perror_msg("poll"); - done in safe_poll */
573                         goto ret;
574                 case 0:
575                         retries--;
576                         if (retries == 0) {
577                                 tftp_progress_done();
578                                 bb_simple_error_msg("timeout");
579                                 goto ret; /* no err packet sent */
580                         }
581
582                         /* exponential backoff with limit */
583                         waittime_ms += waittime_ms/2;
584                         if (waittime_ms > TFTP_MAXTIMEOUT_MS) {
585                                 waittime_ms = TFTP_MAXTIMEOUT_MS;
586                         }
587
588                         goto send_again; /* resend last sent pkt */
589                 case 1:
590                         if (!our_lsa) {
591                                 /* tftp (not tftpd!) receiving 1st packet */
592                                 our_lsa = ((void*)(ptrdiff_t)-1); /* not NULL */
593                                 len = recvfrom(socket_fd, rbuf, io_bufsize, 0,
594                                                 &peer_lsa->u.sa, &peer_lsa->len);
595                                 /* Our first dgram went to port 69
596                                  * but reply may come from different one.
597                                  * Remember and use this new port (and IP) */
598                                 if (len >= 0)
599                                         xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
600                         } else {
601                                 /* tftpd, or not the very first packet:
602                                  * socket is connect()ed, can just read from it. */
603                                 /* Don't full_read()!
604                                  * This is not TCP, one read == one pkt! */
605                                 len = safe_read(socket_fd, rbuf, io_bufsize);
606                         }
607                         if (len < 0) {
608                                 goto send_read_err_pkt;
609                         }
610                         if (len < 4) { /* too small? */
611                                 goto recv_again;
612                         }
613                 }
614
615                 /* Process recv'ed packet */
616                 opcode = ntohs( ((uint16_t*)rbuf)[0] );
617                 recv_blk = ntohs( ((uint16_t*)rbuf)[1] );
618 #if ENABLE_TFTP_DEBUG
619                 fprintf(stderr, "received %d bytes: %04x %04x\n", len, opcode, recv_blk);
620 #endif
621                 if (opcode == TFTP_ERROR) {
622                         static const char errcode_str[] ALIGN1 =
623                                 "\0"
624                                 "file not found\0"
625                                 "access violation\0"
626                                 "disk full\0"
627                                 "bad operation\0"
628                                 "unknown transfer id\0"
629                                 "file already exists\0"
630                                 "no such user\0"
631                                 "bad option";
632
633                         const char *msg = "";
634
635                         if (len > 4 && rbuf[4] != '\0') {
636                                 msg = &rbuf[4];
637                                 rbuf[io_bufsize - 1] = '\0'; /* paranoia */
638                         } else if (recv_blk <= 8) {
639                                 msg = nth_string(errcode_str, recv_blk);
640                         }
641                         bb_error_msg("server error: (%u) %s", recv_blk, msg);
642                         goto ret;
643                 }
644
645 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
646                 if (expect_OACK) {
647                         expect_OACK = 0;
648                         if (opcode == TFTP_OACK) {
649                                 /* server seems to support options */
650                                 char *res;
651
652                                 res = tftp_get_option("blksize", &rbuf[2], len - 2);
653                                 if (res) {
654                                         blksize = tftp_blksize_check(res, blksize);
655                                         if (blksize < 0) {
656                                                 G_error_pkt_reason = ERR_BAD_OPT;
657                                                 goto send_err_pkt;
658                                         }
659                                         io_bufsize = blksize + 4;
660                                 }
661 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
662                                 if (remote_file && G.size == 0) { /* if we don't know it yet */
663                                         res = tftp_get_option("tsize", &rbuf[2], len - 2);
664                                         if (res) {
665                                                 G.size = bb_strtoull(res, NULL, 10);
666                                                 if (G.size)
667                                                         tftp_progress_init();
668                                         }
669                                 }
670 # endif
671                                 if (CMD_GET(option_mask32)) {
672                                         /* We'll send ACK for OACK,
673                                          * such ACK has "block no" of 0 */
674                                         block_nr = 0;
675                                 }
676                                 continue;
677                         }
678                         /* rfc2347:
679                          * "An option not acknowledged by the server
680                          * must be ignored by the client and server
681                          * as if it were never requested." */
682                         if (blksize != TFTP_BLKSIZE_DEFAULT)
683                                 bb_simple_error_msg("falling back to blocksize "TFTP_BLKSIZE_DEFAULT_STR);
684                         blksize = TFTP_BLKSIZE_DEFAULT;
685                         io_bufsize = TFTP_BLKSIZE_DEFAULT + 4;
686                 }
687 #endif
688                 /* block_nr is already advanced to next block# we expect
689                  * to get / block# we are about to send next time */
690
691                 if (CMD_GET(option_mask32) && (opcode == TFTP_DATA)) {
692                         if (recv_blk == block_nr) {
693                                 int sz = full_write(local_fd, &rbuf[4], len - 4);
694                                 if (sz != len - 4) {
695                                         strcpy(G_error_pkt_str, bb_msg_write_error);
696                                         G_error_pkt_reason = ERR_WRITE;
697                                         goto send_err_pkt;
698                                 }
699                                 if (sz != blksize) {
700                                         finished = 1;
701                                 }
702                                 IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += sz;)
703                                 continue; /* send ACK */
704                         }
705 /* Disabled to cope with servers with Sorcerer's Apprentice Syndrome */
706 #if 0
707                         if (recv_blk == (block_nr - 1)) {
708                                 /* Server lost our TFTP_ACK.  Resend it */
709                                 block_nr = recv_blk;
710                                 continue;
711                         }
712 #endif
713                 }
714
715                 if (CMD_PUT(option_mask32) && (opcode == TFTP_ACK)) {
716                         /* did peer ACK our last DATA pkt? */
717                         if (recv_blk == (uint16_t) (block_nr - 1)) {
718                                 if (finished)
719                                         goto ret;
720                                 continue; /* send next block */
721                         }
722                 }
723                 /* Awww... recv'd packet is not recognized! */
724                 goto recv_again;
725                 /* why recv_again? - rfc1123 says:
726                  * "The sender (i.e., the side originating the DATA packets)
727                  *  must never resend the current DATA packet on receipt
728                  *  of a duplicate ACK".
729                  * DATA pkts are resent ONLY on timeout.
730                  * Thus "goto send_again" will be a bad mistake above.
731                  * See:
732                  * http://en.wikipedia.org/wiki/Sorcerer's_Apprentice_Syndrome
733                  */
734         } /* end of "while (1)" */
735  ret:
736         if (ENABLE_FEATURE_CLEAN_UP) {
737                 close(local_fd);
738                 close(socket_fd);
739                 free(xbuf);
740                 free(rbuf);
741         }
742         return finished == 0; /* returns 1 on failure */
743
744  send_read_err_pkt:
745         strcpy(G_error_pkt_str, bb_msg_read_error);
746  send_err_pkt:
747         if (G_error_pkt_str[0])
748                 bb_simple_error_msg(G_error_pkt_str);
749  send_err_pkt_nomsg:
750         G.error_pkt[1] = TFTP_ERROR;
751         xsendto(socket_fd, G.error_pkt, 4 + 1 + strlen(G_error_pkt_str),
752                         &peer_lsa->u.sa, peer_lsa->len);
753         return EXIT_FAILURE;
754 #undef remote_file
755 }
756
757 #if ENABLE_TFTP
758 int tftp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
759 int tftp_main(int argc UNUSED_PARAM, char **argv)
760 {
761         len_and_sockaddr *peer_lsa;
762         const char *local_file = NULL;
763         const char *remote_file = NULL;
764 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
765         const char *blksize_str = TFTP_BLKSIZE_DEFAULT_STR;
766         int blksize;
767 # endif
768         int result;
769         int port;
770         IF_GETPUT(int opt;)
771
772         INIT_G();
773
774         if (ENABLE_FEATURE_TFTP_HPA_COMPAT) {
775                 /* As of 2019, common tftp client in Linux distros
776                  * is one maintained by H. Peter Anvin:
777                  * I've seen "tftp-hpa 5.2" version.
778                  * Make the following command work:
779                  *  "tftp HOST [PORT] -m binary -c get/put FILE"
780                  * by mangling it into "....... -g/-p -r FILE"
781                  * and accepting and ignoring -m STR option.
782                  */
783                 unsigned i = 1;
784                 while (argv[i]) {
785                         /* Accept not only -c, but also
786                          * -lc, -cl, -llcclcllcc etc:
787                          * "-l Literal mode (do not recognize HOST:FILE)"
788                          * since we do not recognize that syntax anyway,
789                          * might as well allow the option.
790                          */
791                         if (argv[i][0] == '-' && strchr(argv[i], 'c')
792                          /*&& argv[i][1+strspn(argv[i]+1, "lc")] == '\0'*/
793                         ) {
794                                 if (!argv[++i])
795                                         break;
796                                 if (strcmp(argv[i], "get") == 0) {
797                                         argv[i-1] = (char*)"-g";
798                                         argv[i] = (char*)"-r";
799                                         break;
800                                 }
801                                 if (strcmp(argv[i], "put") == 0) {
802                                         argv[i-1] = (char*)"-p";
803                                         argv[i] = (char*)"-r";
804                                         break;
805                                 }
806                         }
807                         i++;
808                 }
809         }
810
811         IF_GETPUT(opt =) getopt32(argv, "^"
812                         IF_FEATURE_TFTP_GET("g") IF_FEATURE_TFTP_PUT("p")
813                         "l:r:" IF_FEATURE_TFTP_BLOCKSIZE("b:")
814                         IF_FEATURE_TFTP_HPA_COMPAT("m:")
815                         "\0"
816                         /* -p or -g is mandatory, and they are mutually exclusive */
817                         IF_FEATURE_TFTP_GET("g:") IF_FEATURE_TFTP_PUT("p:")
818                         IF_GETPUT("g--p:p--g:"),
819                         &local_file, &remote_file
820                         IF_FEATURE_TFTP_BLOCKSIZE(, &blksize_str)
821                         IF_FEATURE_TFTP_HPA_COMPAT(, NULL)
822         );
823         argv += optind;
824
825 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
826         /* Check if the blksize is valid:
827          * RFC2348 says between 8 and 65464 */
828         blksize = tftp_blksize_check(blksize_str, 65564);
829         if (blksize < 0) {
830                 //bb_error_msg("bad block size");
831                 return EXIT_FAILURE;
832         }
833 # endif
834
835         if (remote_file) {
836                 if (!local_file) {
837                         const char *slash = strrchr(remote_file, '/');
838                         local_file = slash ? slash + 1 : remote_file;
839                 }
840         } else {
841                 remote_file = local_file;
842         }
843
844         /* Error if filename or host is not known */
845         if (!remote_file || !argv[0])
846                 bb_show_usage();
847
848         port = bb_lookup_port(argv[1], "udp", 69);
849         peer_lsa = xhost2sockaddr(argv[0], port);
850
851 # if ENABLE_TFTP_DEBUG
852         fprintf(stderr, "using server '%s', remote_file '%s', local_file '%s'\n",
853                         xmalloc_sockaddr2dotted(&peer_lsa->u.sa),
854                         remote_file, local_file);
855 # endif
856
857 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
858         G.file = remote_file;
859 # endif
860         result = tftp_protocol(
861                 NULL /*our_lsa*/, peer_lsa,
862                 local_file, remote_file
863                 IF_FEATURE_TFTP_BLOCKSIZE(, 1 /* want_transfer_size */)
864                 IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
865         );
866         tftp_progress_done();
867
868         if (result != EXIT_SUCCESS && NOT_LONE_DASH(local_file) && CMD_GET(opt)) {
869                 unlink(local_file);
870         }
871         return result;
872 }
873 #endif /* ENABLE_TFTP */
874
875 #if ENABLE_TFTPD
876 int tftpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
877 int tftpd_main(int argc UNUSED_PARAM, char **argv)
878 {
879         len_and_sockaddr *our_lsa;
880         len_and_sockaddr *peer_lsa;
881         char *mode, *user_opt;
882         char *local_file = local_file;
883         const char *error_msg;
884         int opt, result, opcode;
885         IF_FEATURE_TFTP_BLOCKSIZE(int blksize = TFTP_BLKSIZE_DEFAULT;)
886         IF_FEATURE_TFTP_BLOCKSIZE(int want_transfer_size = 0;)
887
888         INIT_G();
889
890         our_lsa = get_sock_lsa(STDIN_FILENO);
891         if (!our_lsa) {
892                 /* This is confusing:
893                  *bb_error_msg_and_die("stdin is not a socket");
894                  * Better: */
895                 bb_show_usage();
896                 /* Help text says that tftpd must be used as inetd service,
897                  * which is by far the most usual cause of get_sock_lsa
898                  * failure */
899         }
900         peer_lsa = xzalloc(LSA_LEN_SIZE + our_lsa->len);
901         peer_lsa->len = our_lsa->len;
902
903         /* Shifting to not collide with TFTP_OPTs */
904         opt = option_mask32 = TFTPD_OPT | (getopt32(argv, "rcu:l", &user_opt) << 8);
905         argv += optind;
906         if (opt & TFTPD_OPT_l) {
907                 openlog(applet_name, LOG_PID, LOG_DAEMON);
908                 logmode = LOGMODE_SYSLOG;
909         }
910         if (opt & TFTPD_OPT_u) {
911                 /* Must be before xchroot */
912                 G.pw = xgetpwnam(user_opt);
913         }
914         if (argv[0]) {
915                 xchroot(argv[0]);
916         }
917
918         result = recv_from_to(STDIN_FILENO,
919                         G.block_buf, sizeof(G.block_buf) + 1,
920                         /* ^^^ sizeof+1 to reliably detect oversized input */
921                         0 /* flags */,
922                         &peer_lsa->u.sa, &our_lsa->u.sa, our_lsa->len);
923
924         error_msg = "malformed packet";
925         opcode = ntohs(*(uint16_t*)G.block_buf);
926         if (result < 4 || result > sizeof(G.block_buf)
927         /*|| G.block_buf[result-1] != '\0' - bug compatibility, see below */
928          || (IF_FEATURE_TFTP_PUT(opcode != TFTP_RRQ) /* not download */
929              IF_GETPUT(&&)
930              IF_FEATURE_TFTP_GET(opcode != TFTP_WRQ) /* not upload */
931             )
932         ) {
933                 goto err;
934         }
935         /* Some HP PA-RISC firmware always sends fixed 516-byte requests,
936          * with trailing garbage.
937          * Support that by not requiring NUL to be the last byte (see above).
938          * To make strXYZ() ops safe, force NUL termination:
939          */
940         G.block_buf_tail[0] = '\0';
941
942         local_file = G.block_buf + 2;
943         if (local_file[0] == '.' || strstr(local_file, "/.")) {
944                 error_msg = "dot in file name";
945                 goto err;
946         }
947         mode = local_file + strlen(local_file) + 1;
948         /* RFC 1350 says mode string is case independent */
949         if (mode >= G.block_buf + result || strcasecmp(mode, "octet") != 0) {
950                 error_msg = "mode is not 'octet'";
951                 goto err;
952         }
953 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
954         {
955                 char *res;
956                 char *opt_str = mode + sizeof("octet");
957                 int opt_len = G.block_buf + result - opt_str;
958                 if (opt_len > 0) {
959                         res = tftp_get_option("blksize", opt_str, opt_len);
960                         if (res) {
961                                 blksize = tftp_blksize_check(res, 65564);
962                                 if (blksize < 0) {
963                                         G_error_pkt_reason = ERR_BAD_OPT;
964                                         /* will just send error pkt */
965                                         goto do_proto;
966                                 }
967                         }
968                         if (opcode != TFTP_WRQ /* download? */
969                         /* did client ask us about file size? */
970                          && tftp_get_option("tsize", opt_str, opt_len)
971                         ) {
972                                 want_transfer_size = 1;
973                         }
974                 }
975         }
976 # endif
977
978         if (!ENABLE_FEATURE_TFTP_PUT || opcode == TFTP_WRQ) {
979                 if (opt & TFTPD_OPT_r) {
980                         /* This would mean "disk full" - not true */
981                         /*G_error_pkt_reason = ERR_WRITE;*/
982                         error_msg = bb_msg_write_error;
983                         goto err;
984                 }
985                 IF_GETPUT(option_mask32 |= TFTP_OPT_GET;) /* will receive file's data */
986         } else {
987                 IF_GETPUT(option_mask32 |= TFTP_OPT_PUT;) /* will send file's data */
988         }
989
990         /* NB: if G_error_pkt_str or G_error_pkt_reason is set up,
991          * tftp_protocol() just sends one error pkt and returns */
992
993  do_proto:
994         close(STDIN_FILENO); /* close old, possibly wildcard socket */
995         /* tftp_protocol() will create new one, bound to particular local IP */
996         result = tftp_protocol(
997                 our_lsa, peer_lsa,
998                 local_file
999                 IF_TFTP(, NULL /*remote_file*/)
1000                 IF_FEATURE_TFTP_BLOCKSIZE(, want_transfer_size)
1001                 IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
1002         );
1003
1004         return result;
1005  err:
1006         strcpy(G_error_pkt_str, error_msg);
1007         goto do_proto;
1008 }
1009 #endif /* ENABLE_TFTPD */
1010
1011 #endif /* ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT */