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