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