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