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