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