tftp: on download, open local file only when first bit of data arrived
[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 local_fd = -1;
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         /* Examples of network traffic.
358          * Note two cases when ACKs with block# of 0 are sent.
359          *
360          * Download without options:
361          * tftp -> "\0\1FILENAME\0octet\0"
362          *         "\0\3\0\1FILEDATA..." <- tftpd
363          * tftp -> "\0\4\0\1"
364          * ...
365          * Download with option of blksize 16384:
366          * tftp -> "\0\1FILENAME\0octet\0blksize\00016384\0"
367          *         "\0\6blksize\00016384\0" <- tftpd
368          * tftp -> "\0\4\0\0"
369          *         "\0\3\0\1FILEDATA..." <- tftpd
370          * tftp -> "\0\4\0\1"
371          * ...
372          * Upload without options:
373          * tftp -> "\0\2FILENAME\0octet\0"
374          *         "\0\4\0\0" <- tftpd
375          * tftp -> "\0\3\0\1FILEDATA..."
376          *         "\0\4\0\1" <- tftpd
377          * ...
378          * Upload with option of blksize 16384:
379          * tftp -> "\0\2FILENAME\0octet\0blksize\00016384\0"
380          *         "\0\6blksize\00016384\0" <- tftpd
381          * tftp -> "\0\3\0\1FILEDATA..."
382          *         "\0\4\0\1" <- tftpd
383          * ...
384          */
385         block_nr = 1;
386         cp = xbuf + 2;
387
388         if (!ENABLE_TFTP || our_lsa) { /* tftpd */
389                 /* Open file (must be after changing user) */
390                 int open_mode = O_RDONLY;
391                 if (CMD_GET(option_mask32)) {
392                         open_mode = O_WRONLY | O_TRUNC | O_CREAT;
393                         if ((option_mask32 & (TFTPD_OPT+TFTPD_OPT_c)) == TFTPD_OPT) {
394                                 /* tftpd without -c */
395                                 open_mode = O_WRONLY | O_TRUNC;
396                         }
397                 }
398                 local_fd = open(local_file, open_mode, 0666);
399                 if (local_fd < 0) {
400                         /* sanitize name, it came from untrusted remote side */
401                         unsigned char *p = (void *) local_file;
402                         while (*p) {
403                                 if (*p < ' ')
404                                         *p = '?';
405                                 p++;
406                         }
407                         bb_perror_msg("can't open '%s'", local_file);
408                         G_error_pkt_reason = ERR_NOFILE;
409                         strcpy(G_error_pkt_str, "can't open file");
410                         goto send_err_pkt_nomsg;
411                 }
412
413 /* gcc 4.3.1 would NOT optimize it out as it should! */
414 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
415                 if (blksize != TFTP_BLKSIZE_DEFAULT || want_transfer_size) {
416                         /* Create and send OACK packet. */
417                         /* For the download case, block_nr is still 1 -
418                          * we expect 1st ACK from peer to be for (block_nr-1),
419                          * that is, for "block 0" which is our OACK pkt */
420                         opcode = TFTP_OACK;
421                         goto add_blksize_opt;
422                 }
423 #endif
424                 if (CMD_GET(option_mask32)) {
425                         /* It's upload and we don't send OACK.
426                          * We must ACK 1st packet (with filename)
427                          * as if it is "block 0" */
428                         block_nr = 0;
429                 }
430         } else { /* tftp */
431                 if (CMD_PUT(option_mask32)) {
432                         local_fd = STDIN_FILENO;
433                         if (local_file)
434                                 local_fd = xopen(local_file, O_RDONLY);
435                 }
436 /* Removing #if, or using if() statement instead of #if may lead to
437  * "warning: null argument where non-null required": */
438 #if ENABLE_TFTP
439                 /* tftp */
440
441                 /* We can't (and don't really need to) bind the socket:
442                  * we don't know from which local IP datagrams will be sent,
443                  * but kernel will pick the same IP every time (unless routing
444                  * table is changed), thus peer will see dgrams consistently
445                  * coming from the same IP.
446                  * We would like to connect the socket, but since peer's
447                  * UDP code can be less perfect than ours, _peer's_ IP:port
448                  * in replies may differ from IP:port we used to send
449                  * our first packet. We can connect() only when we get
450                  * first reply. */
451
452                 /* build opcode */
453                 opcode = TFTP_WRQ;
454                 if (CMD_GET(option_mask32)) {
455                         opcode = TFTP_RRQ;
456                 }
457                 /* add filename and mode */
458                 /* fill in packet if the filename fits into xbuf */
459                 len = strlen(remote_file);
460                 if (len + 3 + sizeof("octet") >= io_bufsize) {
461                         bb_simple_error_msg("remote filename is too long");
462                         goto ret;
463                 }
464                 cp = stpcpy(cp, remote_file) + 1;
465                 /* add "mode" part of the packet */
466                 cp = stpcpy(cp, "octet") + 1;
467
468 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
469                 if (blksize == TFTP_BLKSIZE_DEFAULT && !want_transfer_size)
470                         goto send_pkt;
471
472                 /* Need to add option to pkt */
473                 if ((&xbuf[io_bufsize - 1] - cp) < sizeof("blksize NNNNN tsize ") + sizeof(off_t)*3) {
474                         bb_simple_error_msg("remote filename is too long");
475                         goto ret;
476                 }
477                 expect_OACK = 1;
478 # endif
479 #endif /* ENABLE_TFTP */
480
481 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
482  add_blksize_opt:
483                 if (blksize != TFTP_BLKSIZE_DEFAULT) {
484                         /* add "blksize", <nul>, blksize, <nul> */
485                         strcpy(cp, "blksize");
486                         cp += sizeof("blksize");
487                         cp += snprintf(cp, 6, "%d", blksize) + 1;
488                 }
489                 if (want_transfer_size) {
490                         /* add "tsize", <nul>, size, <nul> (see RFC2349) */
491                         /* if tftp and downloading, we send "0" (local_fd is not open yet)
492                          * and this makes server to send "tsize" option with the size */
493                         /* if tftp and uploading, we send file size (maybe dont, to not confuse old servers???) */
494                         /* if tftpd and downloading, we are answering to client's request */
495                         /* if tftpd and uploading: !want_transfer_size, this code is not executed */
496                         struct stat st;
497                         strcpy(cp, "tsize");
498                         cp += sizeof("tsize");
499                         st.st_size = 0;
500                         if (local_fd >= 0)
501                                 fstat(local_fd, &st);
502                         cp += sprintf(cp, "%"OFF_FMT"u", (off_t)st.st_size) + 1;
503 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
504                         /* Save for progress bar. If 0 (tftp downloading),
505                          * we look at server's reply later */
506                         G.size = st.st_size;
507                         if (remote_file && st.st_size)
508                                 tftp_progress_init();
509 # endif
510                 }
511 #endif
512                 /* First packet is built, so skip packet generation */
513                 goto send_pkt;
514         }
515
516         /* Using mostly goto's - continue/break will be less clear
517          * in where we actually jump to */
518         while (1) {
519                 /* Build ACK or DATA */
520                 cp = xbuf + 2;
521                 *((uint16_t*)cp) = htons(block_nr);
522                 cp += 2;
523                 block_nr++;
524                 opcode = TFTP_ACK;
525                 if (CMD_PUT(option_mask32)) {
526                         opcode = TFTP_DATA;
527                         len = full_read(local_fd, cp, blksize);
528                         if (len < 0) {
529                                 goto send_read_err_pkt;
530                         }
531                         if (len != blksize) {
532                                 finished = 1;
533                         }
534                         cp += len;
535                         IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += len;)
536                 }
537  send_pkt:
538                 /* Send packet */
539                 *((uint16_t*)xbuf) = htons(opcode); /* fill in opcode part */
540                 send_len = cp - xbuf;
541                 /* NB: send_len value is preserved in code below
542                  * for potential resend */
543
544                 retries = TFTP_NUM_RETRIES;  /* re-initialize */
545                 waittime_ms = TFTP_TIMEOUT_MS;
546
547  send_again:
548 #if ENABLE_TFTP_DEBUG
549                 fprintf(stderr, "sending %u bytes\n", send_len);
550                 for (cp = xbuf; cp < &xbuf[send_len]; cp++)
551                         fprintf(stderr, "%02x ", (unsigned char) *cp);
552                 fprintf(stderr, "\n");
553 #endif
554                 xsendto(socket_fd, xbuf, send_len, &peer_lsa->u.sa, peer_lsa->len);
555
556 #if ENABLE_FEATURE_TFTP_PROGRESS_BAR
557                 if (is_bb_progress_inited(&G.pmt))
558                         tftp_progress_update();
559 #endif
560                 /* Was it final ACK? then exit */
561                 if (finished && (opcode == TFTP_ACK))
562                         goto ret;
563
564  recv_again:
565                 /* Receive packet */
566                 /*pfd[0].fd = socket_fd;*/
567                 pfd[0].events = POLLIN;
568                 switch (safe_poll(pfd, 1, waittime_ms)) {
569                 default:
570                         /*bb_perror_msg("poll"); - done in safe_poll */
571                         goto ret;
572                 case 0:
573                         retries--;
574                         if (retries == 0) {
575                                 tftp_progress_done();
576                                 bb_simple_error_msg("timeout");
577                                 goto ret; /* no err packet sent */
578                         }
579
580                         /* exponential backoff with limit */
581                         waittime_ms += waittime_ms/2;
582                         if (waittime_ms > TFTP_MAXTIMEOUT_MS) {
583                                 waittime_ms = TFTP_MAXTIMEOUT_MS;
584                         }
585
586                         goto send_again; /* resend last sent pkt */
587                 case 1:
588                         if (!our_lsa) {
589                                 /* tftp (not tftpd!) receiving 1st packet */
590                                 our_lsa = ((void*)(ptrdiff_t)-1); /* not NULL */
591                                 len = recvfrom(socket_fd, rbuf, io_bufsize, 0,
592                                                 &peer_lsa->u.sa, &peer_lsa->len);
593                                 /* Our first dgram went to port 69
594                                  * but reply may come from different one.
595                                  * Remember and use this new port (and IP) */
596                                 if (len >= 0)
597                                         xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
598                         } else {
599                                 /* tftpd, or not the very first packet:
600                                  * socket is connect()ed, can just read from it. */
601                                 /* Don't full_read()!
602                                  * This is not TCP, one read == one pkt! */
603                                 len = safe_read(socket_fd, rbuf, io_bufsize);
604                         }
605                         if (len < 0) {
606                                 goto send_read_err_pkt;
607                         }
608                         if (len < 4) { /* too small? */
609                                 goto recv_again;
610                         }
611                 }
612
613                 /* Process recv'ed packet */
614                 opcode = ntohs( ((uint16_t*)rbuf)[0] );
615                 recv_blk = ntohs( ((uint16_t*)rbuf)[1] );
616 #if ENABLE_TFTP_DEBUG
617                 fprintf(stderr, "received %d bytes: %04x %04x\n", len, opcode, recv_blk);
618 #endif
619                 if (opcode == TFTP_ERROR) {
620                         static const char errcode_str[] ALIGN1 =
621                                 "\0"
622                                 "file not found\0"
623                                 "access violation\0"
624                                 "disk full\0"
625                                 "bad operation\0"
626                                 "unknown transfer id\0"
627                                 "file already exists\0"
628                                 "no such user\0"
629                                 "bad option";
630
631                         const char *msg = "";
632
633                         if (len > 4 && rbuf[4] != '\0') {
634                                 msg = &rbuf[4];
635                                 rbuf[io_bufsize - 1] = '\0'; /* paranoia */
636                         } else if (recv_blk <= 8) {
637                                 msg = nth_string(errcode_str, recv_blk);
638                         }
639                         bb_error_msg("server error: (%u) %s", recv_blk, msg);
640                         goto ret;
641                 }
642
643 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
644                 if (expect_OACK) {
645                         expect_OACK = 0;
646                         if (opcode == TFTP_OACK) {
647                                 /* server seems to support options */
648                                 char *res;
649
650                                 res = tftp_get_option("blksize", &rbuf[2], len - 2);
651                                 if (res) {
652                                         blksize = tftp_blksize_check(res, blksize);
653                                         if (blksize < 0) {
654                                                 G_error_pkt_reason = ERR_BAD_OPT;
655                                                 goto send_err_pkt;
656                                         }
657                                         io_bufsize = blksize + 4;
658                                 }
659 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
660                                 if (remote_file && G.size == 0) { /* if we don't know it yet */
661                                         res = tftp_get_option("tsize", &rbuf[2], len - 2);
662                                         if (res) {
663                                                 G.size = bb_strtoull(res, NULL, 10);
664                                                 if (G.size)
665                                                         tftp_progress_init();
666                                         }
667                                 }
668 # endif
669                                 if (CMD_GET(option_mask32)) {
670                                         /* We'll send ACK for OACK,
671                                          * such ACK has "block no" of 0 */
672                                         block_nr = 0;
673                                 }
674                                 continue;
675                         }
676                         /* rfc2347:
677                          * "An option not acknowledged by the server
678                          * must be ignored by the client and server
679                          * as if it were never requested." */
680                         if (blksize != TFTP_BLKSIZE_DEFAULT)
681                                 bb_simple_error_msg("falling back to blocksize "TFTP_BLKSIZE_DEFAULT_STR);
682                         blksize = TFTP_BLKSIZE_DEFAULT;
683                         io_bufsize = TFTP_BLKSIZE_DEFAULT + 4;
684                 }
685 #endif
686                 /* block_nr is already advanced to next block# we expect
687                  * to get / block# we are about to send next time */
688
689                 if (CMD_GET(option_mask32) && (opcode == TFTP_DATA)) {
690                         if (recv_blk == block_nr) {
691                                 int sz;
692                                 if (local_fd == -1) {
693                                         local_fd = STDOUT_FILENO;
694                                         if (local_file)
695                                                 local_fd = xopen(local_file, O_WRONLY | O_TRUNC | O_CREAT);
696                                 }
697                                 sz = full_write(local_fd, &rbuf[4], len - 4);
698                                 if (sz != len - 4) {
699                                         strcpy(G_error_pkt_str, bb_msg_write_error);
700                                         G_error_pkt_reason = ERR_WRITE;
701                                         goto send_err_pkt;
702                                 }
703                                 if (sz != blksize) {
704                                         finished = 1;
705                                 }
706                                 IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += sz;)
707                                 continue; /* send ACK */
708                         }
709 /* Disabled to cope with servers with Sorcerer's Apprentice Syndrome */
710 #if 0
711                         if (recv_blk == (block_nr - 1)) {
712                                 /* Server lost our TFTP_ACK.  Resend it */
713                                 block_nr = recv_blk;
714                                 continue;
715                         }
716 #endif
717                 }
718
719                 if (CMD_PUT(option_mask32) && (opcode == TFTP_ACK)) {
720                         /* did peer ACK our last DATA pkt? */
721                         if (recv_blk == (uint16_t) (block_nr - 1)) {
722                                 if (finished)
723                                         goto ret;
724                                 continue; /* send next block */
725                         }
726                 }
727                 /* Awww... recv'd packet is not recognized! */
728                 goto recv_again;
729                 /* why recv_again? - rfc1123 says:
730                  * "The sender (i.e., the side originating the DATA packets)
731                  *  must never resend the current DATA packet on receipt
732                  *  of a duplicate ACK".
733                  * DATA pkts are resent ONLY on timeout.
734                  * Thus "goto send_again" will be a bad mistake above.
735                  * See:
736                  * http://en.wikipedia.org/wiki/Sorcerer's_Apprentice_Syndrome
737                  */
738         } /* end of "while (1)" */
739  ret:
740         if (ENABLE_FEATURE_CLEAN_UP) {
741                 close(local_fd);
742                 close(socket_fd);
743                 free(xbuf);
744                 free(rbuf);
745         }
746         if (!finished)
747                 goto err;
748         return EXIT_SUCCESS;
749
750  send_read_err_pkt:
751         strcpy(G_error_pkt_str, bb_msg_read_error);
752  send_err_pkt:
753         if (G_error_pkt_str[0])
754                 bb_simple_error_msg(G_error_pkt_str);
755  send_err_pkt_nomsg:
756         G.error_pkt[1] = TFTP_ERROR;
757         xsendto(socket_fd, G.error_pkt, 4 + 1 + strlen(G_error_pkt_str),
758                         &peer_lsa->u.sa, peer_lsa->len);
759  err:
760         if (local_fd >= 0 && CMD_GET(option_mask32) && local_file)
761                 unlink(local_file);
762         return EXIT_FAILURE;
763 #undef remote_file
764 }
765
766 #if ENABLE_TFTP
767 int tftp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
768 int tftp_main(int argc UNUSED_PARAM, char **argv)
769 {
770         len_and_sockaddr *peer_lsa;
771         const char *local_file = NULL;
772         const char *remote_file = NULL;
773 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
774         const char *blksize_str = TFTP_BLKSIZE_DEFAULT_STR;
775         int blksize;
776 # endif
777         int result;
778         int port;
779
780         INIT_G();
781
782         if (ENABLE_FEATURE_TFTP_HPA_COMPAT) {
783                 /* As of 2019, common tftp client in Linux distros
784                  * is one maintained by H. Peter Anvin:
785                  * I've seen "tftp-hpa 5.2" version.
786                  * Make the following command work:
787                  *  "tftp HOST [PORT] -m binary -c get/put FILE"
788                  * by mangling it into "....... -g/-p -r FILE"
789                  * and accepting and ignoring -m STR option.
790                  */
791                 unsigned i = 1;
792                 while (argv[i]) {
793                         /* Accept not only -c, but also
794                          * -lc, -cl, -llcclcllcc etc:
795                          * "-l Literal mode (do not recognize HOST:FILE)"
796                          * since we do not recognize that syntax anyway,
797                          * might as well allow the option.
798                          */
799                         if (argv[i][0] == '-' && strchr(argv[i], 'c')
800                          /*&& argv[i][1+strspn(argv[i]+1, "lc")] == '\0'*/
801                         ) {
802                                 if (!argv[++i])
803                                         break;
804                                 if (strcmp(argv[i], "get") == 0) {
805                                         argv[i-1] = (char*)"-g";
806                                         argv[i] = (char*)"-r";
807                                         break;
808                                 }
809                                 if (strcmp(argv[i], "put") == 0) {
810                                         argv[i-1] = (char*)"-p";
811                                         argv[i] = (char*)"-r";
812                                         break;
813                                 }
814                         }
815                         i++;
816                 }
817         }
818
819         getopt32(argv, "^"
820                         IF_FEATURE_TFTP_GET("g") IF_FEATURE_TFTP_PUT("p")
821                         "l:r:" IF_FEATURE_TFTP_BLOCKSIZE("b:")
822                         IF_FEATURE_TFTP_HPA_COMPAT("m:")
823                         "\0"
824                         /* -p or -g is mandatory, and they are mutually exclusive */
825                         IF_FEATURE_TFTP_GET("g:") IF_FEATURE_TFTP_PUT("p:")
826                         IF_GETPUT("g--p:p--g:"),
827                         &local_file, &remote_file
828                         IF_FEATURE_TFTP_BLOCKSIZE(, &blksize_str)
829                         IF_FEATURE_TFTP_HPA_COMPAT(, NULL)
830         );
831         argv += optind;
832
833 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
834         /* Check if the blksize is valid:
835          * RFC2348 says between 8 and 65464 */
836         blksize = tftp_blksize_check(blksize_str, 65564);
837         if (blksize < 0) {
838                 //bb_error_msg("bad block size");
839                 return EXIT_FAILURE;
840         }
841 # endif
842
843         if (remote_file) {
844                 if (!local_file) {
845                         const char *slash = strrchr(remote_file, '/');
846                         local_file = slash ? slash + 1 : remote_file;
847                 }
848         } else {
849                 remote_file = local_file;
850         }
851
852         /* Error if filename or host is not known */
853         if (!remote_file || !argv[0])
854                 bb_show_usage();
855
856         port = bb_lookup_port(argv[1], "udp", 69);
857         peer_lsa = xhost2sockaddr(argv[0], port);
858
859 # if ENABLE_TFTP_DEBUG
860         fprintf(stderr, "using server '%s', remote_file '%s', local_file '%s'\n",
861                         xmalloc_sockaddr2dotted(&peer_lsa->u.sa),
862                         remote_file, local_file);
863 # endif
864
865 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
866         G.file = remote_file;
867 # endif
868         result = tftp_protocol(
869                 NULL /*our_lsa*/, peer_lsa,
870                 (LONE_DASH(local_file) ? NULL : local_file), remote_file
871                 IF_FEATURE_TFTP_BLOCKSIZE(, 1 /* want_transfer_size */)
872                 IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
873         );
874         tftp_progress_done();
875
876         return result;
877 }
878 #endif /* ENABLE_TFTP */
879
880 #if ENABLE_TFTPD
881 int tftpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
882 int tftpd_main(int argc UNUSED_PARAM, char **argv)
883 {
884         len_and_sockaddr *our_lsa;
885         len_and_sockaddr *peer_lsa;
886         char *mode, *user_opt;
887         char *local_file = local_file;
888         const char *error_msg;
889         int opt, result, opcode;
890         IF_FEATURE_TFTP_BLOCKSIZE(int blksize = TFTP_BLKSIZE_DEFAULT;)
891         IF_FEATURE_TFTP_BLOCKSIZE(int want_transfer_size = 0;)
892
893         INIT_G();
894
895         our_lsa = get_sock_lsa(STDIN_FILENO);
896         if (!our_lsa) {
897                 /* This is confusing:
898                  *bb_error_msg_and_die("stdin is not a socket");
899                  * Better: */
900                 bb_show_usage();
901                 /* Help text says that tftpd must be used as inetd service,
902                  * which is by far the most usual cause of get_sock_lsa
903                  * failure */
904         }
905         peer_lsa = xzalloc(LSA_LEN_SIZE + our_lsa->len);
906         peer_lsa->len = our_lsa->len;
907
908         /* Shifting to not collide with TFTP_OPTs */
909         opt = option_mask32 = TFTPD_OPT | (getopt32(argv, "rcu:l", &user_opt) << 8);
910         argv += optind;
911         if (opt & TFTPD_OPT_l) {
912                 openlog(applet_name, LOG_PID, LOG_DAEMON);
913                 logmode = LOGMODE_SYSLOG;
914         }
915         if (opt & TFTPD_OPT_u) {
916                 /* Must be before xchroot */
917                 G.pw = xgetpwnam(user_opt);
918         }
919         if (argv[0]) {
920                 xchroot(argv[0]);
921         }
922
923         result = recv_from_to(STDIN_FILENO,
924                         G.block_buf, sizeof(G.block_buf) + 1,
925                         /* ^^^ sizeof+1 to reliably detect oversized input */
926                         0 /* flags */,
927                         &peer_lsa->u.sa, &our_lsa->u.sa, our_lsa->len);
928
929         error_msg = "malformed packet";
930         opcode = ntohs(*(uint16_t*)G.block_buf);
931         if (result < 4 || result > sizeof(G.block_buf)
932         /*|| G.block_buf[result-1] != '\0' - bug compatibility, see below */
933          || (IF_FEATURE_TFTP_PUT(opcode != TFTP_RRQ) /* not download */
934              IF_GETPUT(&&)
935              IF_FEATURE_TFTP_GET(opcode != TFTP_WRQ) /* not upload */
936             )
937         ) {
938                 goto err;
939         }
940         /* Some HP PA-RISC firmware always sends fixed 516-byte requests,
941          * with trailing garbage.
942          * Support that by not requiring NUL to be the last byte (see above).
943          * To make strXYZ() ops safe, force NUL termination:
944          */
945         G.block_buf_tail[0] = '\0';
946
947         local_file = G.block_buf + 2;
948         if (local_file[0] == '.' || strstr(local_file, "/.")) {
949                 error_msg = "dot in file name";
950                 goto err;
951         }
952         mode = local_file + strlen(local_file) + 1;
953         /* RFC 1350 says mode string is case independent */
954         if (mode >= G.block_buf + result || strcasecmp(mode, "octet") != 0) {
955                 error_msg = "mode is not 'octet'";
956                 goto err;
957         }
958 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
959         {
960                 char *res;
961                 char *opt_str = mode + sizeof("octet");
962                 int opt_len = G.block_buf + result - opt_str;
963                 if (opt_len > 0) {
964                         res = tftp_get_option("blksize", opt_str, opt_len);
965                         if (res) {
966                                 blksize = tftp_blksize_check(res, 65564);
967                                 if (blksize < 0) {
968                                         G_error_pkt_reason = ERR_BAD_OPT;
969                                         /* will just send error pkt */
970                                         goto do_proto;
971                                 }
972                         }
973                         if (opcode != TFTP_WRQ /* download? */
974                         /* did client ask us about file size? */
975                          && tftp_get_option("tsize", opt_str, opt_len)
976                         ) {
977                                 want_transfer_size = 1;
978                         }
979                 }
980         }
981 # endif
982
983         if (!ENABLE_FEATURE_TFTP_PUT || opcode == TFTP_WRQ) {
984                 if (opt & TFTPD_OPT_r) {
985                         /* This would mean "disk full" - not true */
986                         /*G_error_pkt_reason = ERR_WRITE;*/
987                         error_msg = bb_msg_write_error;
988                         goto err;
989                 }
990                 IF_GETPUT(option_mask32 |= TFTP_OPT_GET;) /* will receive file's data */
991         } else {
992                 IF_GETPUT(option_mask32 |= TFTP_OPT_PUT;) /* will send file's data */
993         }
994
995         /* NB: if G_error_pkt_str or G_error_pkt_reason is set up,
996          * tftp_protocol() just sends one error pkt and returns */
997
998  do_proto:
999         close(STDIN_FILENO); /* close old, possibly wildcard socket */
1000         /* tftp_protocol() will create new one, bound to particular local IP */
1001         result = tftp_protocol(
1002                 our_lsa, peer_lsa,
1003                 local_file
1004                 IF_TFTP(, NULL /*remote_file*/)
1005                 IF_FEATURE_TFTP_BLOCKSIZE(, want_transfer_size)
1006                 IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
1007         );
1008
1009         return result;
1010  err:
1011         strcpy(G_error_pkt_str, error_msg);
1012         goto do_proto;
1013 }
1014 #endif /* ENABLE_TFTPD */
1015
1016 #endif /* ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT */