1 /* vi: set sw=4 ts=4: */
3 * A simple tftp client/server for busybox.
4 * Tries to follow RFC1350.
5 * Only "octet" mode supported.
6 * Optional blocksize negotiation (RFC2347 + RFC2348)
8 * Copyright (C) 2001 Magnus Damm <damm@opensource.se>
10 * Parts of the code based on:
12 * atftp: Copyright (C) 2000 Jean-Pierre Lefebvre <helix@step.polymtl.ca>
13 * and Remi Lefebvre <remi@debian.org>
15 * utftp: Copyright (C) 1999 Uwe Ohse <uwe@ohse.de>
17 * tftpd added by Denys Vlasenko & Vladimir Dronnikov
19 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
22 //config: bool "tftp (11 kb)"
25 //config: Trivial File Transfer Protocol client. TFTP is usually used
26 //config: for simple, small transfers such as a root image
27 //config: for a network-enabled bootloader.
29 //config:config FEATURE_TFTP_PROGRESS_BAR
30 //config: bool "Enable progress bar"
32 //config: depends on TFTP
34 //config:config FEATURE_TFTP_HPA_COMPAT
35 //config: bool "tftp-hpa compat (support -c get/put FILE)"
37 //config: depends on TFTP
40 //config: bool "tftpd (10 kb)"
43 //config: Trivial File Transfer Protocol server.
44 //config: It expects that stdin is a datagram socket and a packet
45 //config: is already pending on it. It will exit after one transfer.
46 //config: In other words: it should be run from inetd in nowait mode,
47 //config: or from udpsvd. Example: "udpsvd -E 0 69 tftpd DIR"
49 //config:config FEATURE_TFTP_GET
50 //config: bool "Enable 'tftp get' and/or tftpd upload code"
52 //config: depends on TFTP || TFTPD
54 //config: Add support for the GET command within the TFTP client. This allows
55 //config: a client to retrieve a file from a TFTP server.
56 //config: Also enable upload support in tftpd, if tftpd is selected.
58 //config: Note: this option does _not_ make tftpd capable of download
59 //config: (the usual operation people need from it)!
61 //config:config FEATURE_TFTP_PUT
62 //config: bool "Enable 'tftp put' and/or tftpd download code"
64 //config: depends on TFTP || TFTPD
66 //config: Add support for the PUT command within the TFTP client. This allows
67 //config: a client to transfer a file to a TFTP server.
68 //config: Also enable download support in tftpd, if tftpd is selected.
70 //config:config FEATURE_TFTP_BLOCKSIZE
71 //config: bool "Enable 'blksize' and 'tsize' protocol options"
73 //config: depends on TFTP || TFTPD
75 //config: Allow tftp to specify block size, and tftpd to understand
76 //config: "blksize" and "tsize" options.
78 //config:config TFTP_DEBUG
79 //config: bool "Enable debug"
81 //config: depends on TFTP || TFTPD
83 //config: Make tftp[d] print debugging messages on stderr.
84 //config: This is useful if you are diagnosing a bug in tftp[d].
86 //applet:#if ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT
87 //applet:IF_TFTP(APPLET(tftp, BB_DIR_USR_BIN, BB_SUID_DROP))
88 //applet:IF_TFTPD(APPLET(tftpd, BB_DIR_USR_SBIN, BB_SUID_DROP))
91 //kbuild:lib-$(CONFIG_TFTP) += tftp.o
92 //kbuild:lib-$(CONFIG_TFTPD) += tftp.o
94 //usage:#define tftp_trivial_usage
95 //usage: "[OPTIONS] HOST [PORT]"
96 //usage:#define tftp_full_usage "\n\n"
97 //usage: "Transfer a file from/to tftp server\n"
98 //usage: "\n -l FILE Local FILE"
99 //usage: "\n -r FILE Remote FILE"
100 //usage: IF_FEATURE_TFTP_GET(
101 //usage: "\n -g Get file"
103 //usage: IF_FEATURE_TFTP_PUT(
104 //usage: "\n -p Put file"
106 //usage: IF_FEATURE_TFTP_BLOCKSIZE(
107 //usage: "\n -b SIZE Transfer blocks of SIZE octets"
109 ///////: "\n -m STR Accepted and ignored ('-m binary' compat with tftp-hpa 5.2)"
111 //usage:#define tftpd_trivial_usage
112 //usage: "[-crl] [-u USER] [DIR]"
113 //usage:#define tftpd_full_usage "\n\n"
114 //usage: "Transfer a file on tftp client's request\n"
116 //usage: "tftpd should be used as an inetd service.\n"
117 //usage: "tftpd's line for inetd.conf:\n"
118 //usage: " 69 dgram udp nowait root tftpd tftpd -l /files/to/serve\n"
119 //usage: "It also can be ran from udpsvd:\n"
120 //usage: " udpsvd -vE 0.0.0.0 69 tftpd /files/to/serve\n"
121 //usage: "\n -r Prohibit upload"
122 //usage: "\n -c Allow file creation via upload"
123 //usage: "\n -u Access files as USER"
124 //usage: "\n -l Log to syslog (inetd mode requires this)"
127 #include "common_bufsiz.h"
130 #if ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT
132 #define TFTP_BLKSIZE_DEFAULT 512 /* according to RFC 1350, don't change */
133 #define TFTP_BLKSIZE_DEFAULT_STR "512"
134 /* Was 50 ms but users asked to bump it up a bit */
135 #define TFTP_TIMEOUT_MS 100
136 #define TFTP_MAXTIMEOUT_MS 2000
137 #define TFTP_NUM_RETRIES 12 /* number of backed-off retries */
139 /* opcodes we support */
147 /* error codes sent over network (we use only 0, 1, 3 and 8) */
148 /* generic (error message is included in the packet) */
152 /* disk full or allocation exceeded */
157 #define ERR_BAD_USER 7
158 #define ERR_BAD_OPT 8
160 /* masks coming from getopt32 */
162 TFTP_OPT_GET = (1 << 0),
163 TFTP_OPT_PUT = (1 << 1),
164 /* pseudo option: if set, it's tftpd */
165 TFTPD_OPT = (1 << 7) * ENABLE_TFTPD,
166 TFTPD_OPT_r = (1 << 8) * ENABLE_TFTPD,
167 TFTPD_OPT_c = (1 << 9) * ENABLE_TFTPD,
168 TFTPD_OPT_u = (1 << 10) * ENABLE_TFTPD,
169 TFTPD_OPT_l = (1 << 11) * ENABLE_TFTPD,
172 #if ENABLE_FEATURE_TFTP_GET && !ENABLE_FEATURE_TFTP_PUT
173 #define IF_GETPUT(...)
174 #define CMD_GET(cmd) 1
175 #define CMD_PUT(cmd) 0
176 #elif !ENABLE_FEATURE_TFTP_GET && ENABLE_FEATURE_TFTP_PUT
177 #define IF_GETPUT(...)
178 #define CMD_GET(cmd) 0
179 #define CMD_PUT(cmd) 1
181 #define IF_GETPUT(...) __VA_ARGS__
182 #define CMD_GET(cmd) ((cmd) & TFTP_OPT_GET)
183 #define CMD_PUT(cmd) ((cmd) & TFTP_OPT_PUT)
185 /* NB: in the code below
186 * CMD_GET(cmd) and CMD_PUT(cmd) are mutually exclusive
191 /* u16 TFTP_ERROR; u16 reason; both network-endian, then error text: */
192 uint8_t error_pkt[4 + 32];
194 /* Used in tftpd_main() for initial packet */
195 /* Some HP PA-RISC firmware always sends fixed 516-byte requests */
197 char block_buf_tail[1];
198 #if ENABLE_FEATURE_TFTP_PROGRESS_BAR
205 #define G (*(struct globals*)bb_common_bufsiz1)
206 #define INIT_G() do { \
207 setup_common_bufsiz(); \
208 BUILD_BUG_ON(sizeof(G) > COMMON_BUFSIZE); \
211 #define G_error_pkt_reason (G.error_pkt[3])
212 #define G_error_pkt_str ((char*)(G.error_pkt + 4))
214 #if ENABLE_FEATURE_TFTP_PROGRESS_BAR && ENABLE_FEATURE_TFTP_BLOCKSIZE
215 static void tftp_progress_update(void)
217 bb_progress_update(&G.pmt, 0, G.pos, G.size);
219 static void tftp_progress_init(void)
221 bb_progress_init(&G.pmt, G.file);
222 tftp_progress_update();
224 static void tftp_progress_done(void)
226 if (is_bb_progress_inited(&G.pmt)) {
227 tftp_progress_update();
228 bb_putchar_stderr('\n');
229 bb_progress_free(&G.pmt);
233 # define tftp_progress_update() ((void)0)
234 # define tftp_progress_init() ((void)0)
235 # define tftp_progress_done() ((void)0)
238 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
240 static int tftp_blksize_check(const char *blksize_str, int maxsize)
242 /* Check if the blksize is valid:
243 * RFC2348 says between 8 and 65464,
244 * but our implementation makes it impossible
245 * to use blksizes smaller than 22 octets. */
246 unsigned blksize = bb_strtou(blksize_str, NULL, 10);
248 || (blksize < 24) || (blksize > maxsize)
250 bb_error_msg("bad blocksize '%s'", blksize_str);
253 # if ENABLE_TFTP_DEBUG
254 bb_info_msg("using blksize %u", blksize);
259 static char *tftp_get_option(const char *option, char *buf, int len)
266 * "opt_name<NUL>opt_val<NUL>opt_name2<NUL>opt_val2<NUL>..." */
269 /* Make sure options are terminated correctly */
270 for (k = 0; k < len; k++) {
271 if (buf[k] == '\0') {
277 if (opt_val == 0) { /* it's "name" part */
278 if (strcasecmp(buf, option) == 0) {
281 } else if (opt_found) {
296 static int tftp_protocol(
297 /* NULL if tftp, !NULL if tftpd: */
298 len_and_sockaddr *our_lsa,
299 len_and_sockaddr *peer_lsa,
300 const char *local_file
301 IF_TFTP(, const char *remote_file)
303 # define remote_file NULL
305 /* 1 for tftp; 1/0 for tftpd depending whether client asked about it: */
306 IF_FEATURE_TFTP_BLOCKSIZE(, int want_transfer_size)
307 IF_FEATURE_TFTP_BLOCKSIZE(, int blksize))
309 #if !ENABLE_FEATURE_TFTP_BLOCKSIZE
310 enum { blksize = TFTP_BLKSIZE_DEFAULT };
313 struct pollfd pfd[1];
314 #define socket_fd (pfd[0].fd)
317 IF_FEATURE_TFTP_BLOCKSIZE(smallint expect_OACK = 0;)
318 smallint finished = 0;
322 int open_mode, local_fd;
323 int retries, waittime_ms;
324 int io_bufsize = blksize + 4;
326 /* Can't use RESERVE_CONFIG_BUFFER here since the allocation
327 * size varies meaning BUFFERS_GO_ON_STACK would fail.
329 * We must keep the transmit and receive buffers separate
330 * in case we rcv a garbage pkt - we need to rexmit the last pkt.
332 char *xbuf = xmalloc(io_bufsize);
333 char *rbuf = xmalloc(io_bufsize);
335 socket_fd = xsocket(peer_lsa->u.sa.sa_family, SOCK_DGRAM, 0);
336 setsockopt_reuseaddr(socket_fd);
338 if (!ENABLE_TFTP || our_lsa) { /* tftpd */
339 /* Create a socket which is:
340 * 1. bound to IP:port peer sent 1st datagram to,
341 * 2. connected to peer's IP:port
342 * This way we will answer from the IP:port peer
343 * expects, will not get any other packets on
344 * the socket, and also plain read/write will work. */
345 xbind(socket_fd, &our_lsa->u.sa, our_lsa->len);
346 xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
348 /* Is there an error already? Send pkt and bail out */
349 if (G_error_pkt_reason || G_error_pkt_str[0])
353 change_identity(G.pw); /* initgroups, setgid, setuid */
357 /* Prepare open mode */
358 if (CMD_PUT(option_mask32)) {
359 open_mode = O_RDONLY;
361 open_mode = O_WRONLY | O_TRUNC | O_CREAT;
363 if ((option_mask32 & (TFTPD_OPT+TFTPD_OPT_c)) == TFTPD_OPT) {
364 /* tftpd without -c */
365 open_mode = O_WRONLY | O_TRUNC;
370 /* Examples of network traffic.
371 * Note two cases when ACKs with block# of 0 are sent.
373 * Download without options:
374 * tftp -> "\0\1FILENAME\0octet\0"
375 * "\0\3\0\1FILEDATA..." <- tftpd
378 * Download with option of blksize 16384:
379 * tftp -> "\0\1FILENAME\0octet\0blksize\00016384\0"
380 * "\0\6blksize\00016384\0" <- tftpd
382 * "\0\3\0\1FILEDATA..." <- tftpd
385 * Upload without options:
386 * tftp -> "\0\2FILENAME\0octet\0"
387 * "\0\4\0\0" <- tftpd
388 * tftp -> "\0\3\0\1FILEDATA..."
389 * "\0\4\0\1" <- tftpd
391 * Upload with option of blksize 16384:
392 * tftp -> "\0\2FILENAME\0octet\0blksize\00016384\0"
393 * "\0\6blksize\00016384\0" <- tftpd
394 * tftp -> "\0\3\0\1FILEDATA..."
395 * "\0\4\0\1" <- tftpd
401 if (!ENABLE_TFTP || our_lsa) { /* tftpd */
402 /* Open file (must be after changing user) */
403 local_fd = open(local_file, open_mode, 0666);
405 /* sanitize name, it came from untrusted remote side */
406 unsigned char *p = (void *) local_file;
412 bb_perror_msg("can't open '%s'", local_file);
413 G_error_pkt_reason = ERR_NOFILE;
414 strcpy(G_error_pkt_str, "can't open file");
415 goto send_err_pkt_nomsg;
417 /* gcc 4.3.1 would NOT optimize it out as it should! */
418 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
419 if (blksize != TFTP_BLKSIZE_DEFAULT || want_transfer_size) {
420 /* Create and send OACK packet. */
421 /* For the download case, block_nr is still 1 -
422 * we expect 1st ACK from peer to be for (block_nr-1),
423 * that is, for "block 0" which is our OACK pkt */
425 goto add_blksize_opt;
428 if (CMD_GET(option_mask32)) {
429 /* It's upload and we don't send OACK.
430 * We must ACK 1st packet (with filename)
431 * as if it is "block 0" */
435 /* Open file (must be after changing user) */
436 local_fd = CMD_GET(option_mask32) ? STDOUT_FILENO : STDIN_FILENO;
437 if (NOT_LONE_DASH(local_file))
438 local_fd = xopen(local_file, open_mode);
439 /* Removing #if, or using if() statement instead of #if may lead to
440 * "warning: null argument where non-null required": */
444 /* We can't (and don't really need to) bind the socket:
445 * we don't know from which local IP datagrams will be sent,
446 * but kernel will pick the same IP every time (unless routing
447 * table is changed), thus peer will see dgrams consistently
448 * coming from the same IP.
449 * We would like to connect the socket, but since peer's
450 * UDP code can be less perfect than ours, _peer's_ IP:port
451 * in replies may differ from IP:port we used to send
452 * our first packet. We can connect() only when we get
457 if (CMD_GET(option_mask32)) {
460 /* add filename and mode */
461 /* fill in packet if the filename fits into xbuf */
462 len = strlen(remote_file);
463 if (len + 3 + sizeof("octet") >= io_bufsize) {
464 bb_simple_error_msg("remote filename is too long");
467 cp = stpcpy(cp, remote_file) + 1;
468 /* add "mode" part of the packet */
469 cp = stpcpy(cp, "octet") + 1;
471 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
472 if (blksize == TFTP_BLKSIZE_DEFAULT && !want_transfer_size)
475 /* Need to add option to pkt */
476 if ((&xbuf[io_bufsize - 1] - cp) < sizeof("blksize NNNNN tsize ") + sizeof(off_t)*3) {
477 bb_simple_error_msg("remote filename is too long");
482 #endif /* ENABLE_TFTP */
484 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
486 if (blksize != TFTP_BLKSIZE_DEFAULT) {
487 /* add "blksize", <nul>, blksize, <nul> */
488 strcpy(cp, "blksize");
489 cp += sizeof("blksize");
490 cp += snprintf(cp, 6, "%d", blksize) + 1;
492 if (want_transfer_size) {
493 /* add "tsize", <nul>, size, <nul> (see RFC2349) */
494 /* if tftp and downloading, we send "0" (since we opened local_fd with O_TRUNC)
495 * and this makes server to send "tsize" option with the size */
496 /* if tftp and uploading, we send file size (maybe dont, to not confuse old servers???) */
497 /* if tftpd and downloading, we are answering to client's request */
498 /* if tftpd and uploading: !want_transfer_size, this code is not executed */
501 cp += sizeof("tsize");
503 fstat(local_fd, &st);
504 cp += sprintf(cp, "%"OFF_FMT"u", (off_t)st.st_size) + 1;
505 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
506 /* Save for progress bar. If 0 (tftp downloading),
507 * we look at server's reply later */
509 if (remote_file && st.st_size)
510 tftp_progress_init();
514 /* First packet is built, so skip packet generation */
518 /* Using mostly goto's - continue/break will be less clear
519 * in where we actually jump to */
521 /* Build ACK or DATA */
523 *((uint16_t*)cp) = htons(block_nr);
527 if (CMD_PUT(option_mask32)) {
529 len = full_read(local_fd, cp, blksize);
531 goto send_read_err_pkt;
533 if (len != blksize) {
537 IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += len;)
541 *((uint16_t*)xbuf) = htons(opcode); /* fill in opcode part */
542 send_len = cp - xbuf;
543 /* NB: send_len value is preserved in code below
544 * for potential resend */
546 retries = TFTP_NUM_RETRIES; /* re-initialize */
547 waittime_ms = TFTP_TIMEOUT_MS;
550 #if ENABLE_TFTP_DEBUG
551 fprintf(stderr, "sending %u bytes\n", send_len);
552 for (cp = xbuf; cp < &xbuf[send_len]; cp++)
553 fprintf(stderr, "%02x ", (unsigned char) *cp);
554 fprintf(stderr, "\n");
556 xsendto(socket_fd, xbuf, send_len, &peer_lsa->u.sa, peer_lsa->len);
558 #if ENABLE_FEATURE_TFTP_PROGRESS_BAR
559 if (is_bb_progress_inited(&G.pmt))
560 tftp_progress_update();
562 /* Was it final ACK? then exit */
563 if (finished && (opcode == TFTP_ACK))
568 /*pfd[0].fd = socket_fd;*/
569 pfd[0].events = POLLIN;
570 switch (safe_poll(pfd, 1, waittime_ms)) {
572 /*bb_perror_msg("poll"); - done in safe_poll */
577 tftp_progress_done();
578 bb_simple_error_msg("timeout");
579 goto ret; /* no err packet sent */
582 /* exponential backoff with limit */
583 waittime_ms += waittime_ms/2;
584 if (waittime_ms > TFTP_MAXTIMEOUT_MS) {
585 waittime_ms = TFTP_MAXTIMEOUT_MS;
588 goto send_again; /* resend last sent pkt */
591 /* tftp (not tftpd!) receiving 1st packet */
592 our_lsa = ((void*)(ptrdiff_t)-1); /* not NULL */
593 len = recvfrom(socket_fd, rbuf, io_bufsize, 0,
594 &peer_lsa->u.sa, &peer_lsa->len);
595 /* Our first dgram went to port 69
596 * but reply may come from different one.
597 * Remember and use this new port (and IP) */
599 xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
601 /* tftpd, or not the very first packet:
602 * socket is connect()ed, can just read from it. */
603 /* Don't full_read()!
604 * This is not TCP, one read == one pkt! */
605 len = safe_read(socket_fd, rbuf, io_bufsize);
608 goto send_read_err_pkt;
610 if (len < 4) { /* too small? */
615 /* Process recv'ed packet */
616 opcode = ntohs( ((uint16_t*)rbuf)[0] );
617 recv_blk = ntohs( ((uint16_t*)rbuf)[1] );
618 #if ENABLE_TFTP_DEBUG
619 fprintf(stderr, "received %d bytes: %04x %04x\n", len, opcode, recv_blk);
621 if (opcode == TFTP_ERROR) {
622 static const char errcode_str[] ALIGN1 =
628 "unknown transfer id\0"
629 "file already exists\0"
633 const char *msg = "";
635 if (len > 4 && rbuf[4] != '\0') {
637 rbuf[io_bufsize - 1] = '\0'; /* paranoia */
638 } else if (recv_blk <= 8) {
639 msg = nth_string(errcode_str, recv_blk);
641 bb_error_msg("server error: (%u) %s", recv_blk, msg);
645 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
648 if (opcode == TFTP_OACK) {
649 /* server seems to support options */
652 res = tftp_get_option("blksize", &rbuf[2], len - 2);
654 blksize = tftp_blksize_check(res, blksize);
656 G_error_pkt_reason = ERR_BAD_OPT;
659 io_bufsize = blksize + 4;
661 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
662 if (remote_file && G.size == 0) { /* if we don't know it yet */
663 res = tftp_get_option("tsize", &rbuf[2], len - 2);
665 G.size = bb_strtoull(res, NULL, 10);
667 tftp_progress_init();
671 if (CMD_GET(option_mask32)) {
672 /* We'll send ACK for OACK,
673 * such ACK has "block no" of 0 */
679 * "An option not acknowledged by the server
680 * must be ignored by the client and server
681 * as if it were never requested." */
682 if (blksize != TFTP_BLKSIZE_DEFAULT)
683 bb_simple_error_msg("falling back to blocksize "TFTP_BLKSIZE_DEFAULT_STR);
684 blksize = TFTP_BLKSIZE_DEFAULT;
685 io_bufsize = TFTP_BLKSIZE_DEFAULT + 4;
688 /* block_nr is already advanced to next block# we expect
689 * to get / block# we are about to send next time */
691 if (CMD_GET(option_mask32) && (opcode == TFTP_DATA)) {
692 if (recv_blk == block_nr) {
693 int sz = full_write(local_fd, &rbuf[4], len - 4);
695 strcpy(G_error_pkt_str, bb_msg_write_error);
696 G_error_pkt_reason = ERR_WRITE;
702 IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += sz;)
703 continue; /* send ACK */
705 /* Disabled to cope with servers with Sorcerer's Apprentice Syndrome */
707 if (recv_blk == (block_nr - 1)) {
708 /* Server lost our TFTP_ACK. Resend it */
715 if (CMD_PUT(option_mask32) && (opcode == TFTP_ACK)) {
716 /* did peer ACK our last DATA pkt? */
717 if (recv_blk == (uint16_t) (block_nr - 1)) {
720 continue; /* send next block */
723 /* Awww... recv'd packet is not recognized! */
725 /* why recv_again? - rfc1123 says:
726 * "The sender (i.e., the side originating the DATA packets)
727 * must never resend the current DATA packet on receipt
728 * of a duplicate ACK".
729 * DATA pkts are resent ONLY on timeout.
730 * Thus "goto send_again" will be a bad mistake above.
732 * http://en.wikipedia.org/wiki/Sorcerer's_Apprentice_Syndrome
734 } /* end of "while (1)" */
736 if (ENABLE_FEATURE_CLEAN_UP) {
742 return finished == 0; /* returns 1 on failure */
745 strcpy(G_error_pkt_str, bb_msg_read_error);
747 if (G_error_pkt_str[0])
748 bb_simple_error_msg(G_error_pkt_str);
750 G.error_pkt[1] = TFTP_ERROR;
751 xsendto(socket_fd, G.error_pkt, 4 + 1 + strlen(G_error_pkt_str),
752 &peer_lsa->u.sa, peer_lsa->len);
758 int tftp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
759 int tftp_main(int argc UNUSED_PARAM, char **argv)
761 len_and_sockaddr *peer_lsa;
762 const char *local_file = NULL;
763 const char *remote_file = NULL;
764 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
765 const char *blksize_str = TFTP_BLKSIZE_DEFAULT_STR;
774 if (ENABLE_FEATURE_TFTP_HPA_COMPAT) {
775 /* As of 2019, common tftp client in Linux distros
776 * is one maintained by H. Peter Anvin:
777 * I've seen "tftp-hpa 5.2" version.
778 * Make the following command work:
779 * "tftp HOST [PORT] -m binary -c get/put FILE"
780 * by mangling it into "....... -g/-p -r FILE"
781 * and accepting and ignoring -m STR option.
785 /* Accept not only -c, but also
786 * -lc, -cl, -llcclcllcc etc:
787 * "-l Literal mode (do not recognize HOST:FILE)"
788 * since we do not recognize that syntax anyway,
789 * might as well allow the option.
791 if (argv[i][0] == '-' && strchr(argv[i], 'c')
792 /*&& argv[i][1+strspn(argv[i]+1, "lc")] == '\0'*/
796 if (strcmp(argv[i], "get") == 0) {
797 argv[i-1] = (char*)"-g";
798 argv[i] = (char*)"-r";
801 if (strcmp(argv[i], "put") == 0) {
802 argv[i-1] = (char*)"-p";
803 argv[i] = (char*)"-r";
811 IF_GETPUT(opt =) getopt32(argv, "^"
812 IF_FEATURE_TFTP_GET("g") IF_FEATURE_TFTP_PUT("p")
813 "l:r:" IF_FEATURE_TFTP_BLOCKSIZE("b:")
814 IF_FEATURE_TFTP_HPA_COMPAT("m:")
816 /* -p or -g is mandatory, and they are mutually exclusive */
817 IF_FEATURE_TFTP_GET("g:") IF_FEATURE_TFTP_PUT("p:")
818 IF_GETPUT("g--p:p--g:"),
819 &local_file, &remote_file
820 IF_FEATURE_TFTP_BLOCKSIZE(, &blksize_str)
821 IF_FEATURE_TFTP_HPA_COMPAT(, NULL)
825 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
826 /* Check if the blksize is valid:
827 * RFC2348 says between 8 and 65464 */
828 blksize = tftp_blksize_check(blksize_str, 65564);
830 //bb_error_msg("bad block size");
837 const char *slash = strrchr(remote_file, '/');
838 local_file = slash ? slash + 1 : remote_file;
841 remote_file = local_file;
844 /* Error if filename or host is not known */
845 if (!remote_file || !argv[0])
848 port = bb_lookup_port(argv[1], "udp", 69);
849 peer_lsa = xhost2sockaddr(argv[0], port);
851 # if ENABLE_TFTP_DEBUG
852 fprintf(stderr, "using server '%s', remote_file '%s', local_file '%s'\n",
853 xmalloc_sockaddr2dotted(&peer_lsa->u.sa),
854 remote_file, local_file);
857 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
858 G.file = remote_file;
860 result = tftp_protocol(
861 NULL /*our_lsa*/, peer_lsa,
862 local_file, remote_file
863 IF_FEATURE_TFTP_BLOCKSIZE(, 1 /* want_transfer_size */)
864 IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
866 tftp_progress_done();
868 if (result != EXIT_SUCCESS && NOT_LONE_DASH(local_file) && CMD_GET(opt)) {
873 #endif /* ENABLE_TFTP */
876 int tftpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
877 int tftpd_main(int argc UNUSED_PARAM, char **argv)
879 len_and_sockaddr *our_lsa;
880 len_and_sockaddr *peer_lsa;
881 char *mode, *user_opt;
882 char *local_file = local_file;
883 const char *error_msg;
884 int opt, result, opcode;
885 IF_FEATURE_TFTP_BLOCKSIZE(int blksize = TFTP_BLKSIZE_DEFAULT;)
886 IF_FEATURE_TFTP_BLOCKSIZE(int want_transfer_size = 0;)
890 our_lsa = get_sock_lsa(STDIN_FILENO);
892 /* This is confusing:
893 *bb_error_msg_and_die("stdin is not a socket");
896 /* Help text says that tftpd must be used as inetd service,
897 * which is by far the most usual cause of get_sock_lsa
900 peer_lsa = xzalloc(LSA_LEN_SIZE + our_lsa->len);
901 peer_lsa->len = our_lsa->len;
903 /* Shifting to not collide with TFTP_OPTs */
904 opt = option_mask32 = TFTPD_OPT | (getopt32(argv, "rcu:l", &user_opt) << 8);
906 if (opt & TFTPD_OPT_l) {
907 openlog(applet_name, LOG_PID, LOG_DAEMON);
908 logmode = LOGMODE_SYSLOG;
910 if (opt & TFTPD_OPT_u) {
911 /* Must be before xchroot */
912 G.pw = xgetpwnam(user_opt);
918 result = recv_from_to(STDIN_FILENO,
919 G.block_buf, sizeof(G.block_buf) + 1,
920 /* ^^^ sizeof+1 to reliably detect oversized input */
922 &peer_lsa->u.sa, &our_lsa->u.sa, our_lsa->len);
924 error_msg = "malformed packet";
925 opcode = ntohs(*(uint16_t*)G.block_buf);
926 if (result < 4 || result > sizeof(G.block_buf)
927 /*|| G.block_buf[result-1] != '\0' - bug compatibility, see below */
928 || (IF_FEATURE_TFTP_PUT(opcode != TFTP_RRQ) /* not download */
930 IF_FEATURE_TFTP_GET(opcode != TFTP_WRQ) /* not upload */
935 /* Some HP PA-RISC firmware always sends fixed 516-byte requests,
936 * with trailing garbage.
937 * Support that by not requiring NUL to be the last byte (see above).
938 * To make strXYZ() ops safe, force NUL termination:
940 G.block_buf_tail[0] = '\0';
942 local_file = G.block_buf + 2;
943 if (local_file[0] == '.' || strstr(local_file, "/.")) {
944 error_msg = "dot in file name";
947 mode = local_file + strlen(local_file) + 1;
948 /* RFC 1350 says mode string is case independent */
949 if (mode >= G.block_buf + result || strcasecmp(mode, "octet") != 0) {
950 error_msg = "mode is not 'octet'";
953 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
956 char *opt_str = mode + sizeof("octet");
957 int opt_len = G.block_buf + result - opt_str;
959 res = tftp_get_option("blksize", opt_str, opt_len);
961 blksize = tftp_blksize_check(res, 65564);
963 G_error_pkt_reason = ERR_BAD_OPT;
964 /* will just send error pkt */
968 if (opcode != TFTP_WRQ /* download? */
969 /* did client ask us about file size? */
970 && tftp_get_option("tsize", opt_str, opt_len)
972 want_transfer_size = 1;
978 if (!ENABLE_FEATURE_TFTP_PUT || opcode == TFTP_WRQ) {
979 if (opt & TFTPD_OPT_r) {
980 /* This would mean "disk full" - not true */
981 /*G_error_pkt_reason = ERR_WRITE;*/
982 error_msg = bb_msg_write_error;
985 IF_GETPUT(option_mask32 |= TFTP_OPT_GET;) /* will receive file's data */
987 IF_GETPUT(option_mask32 |= TFTP_OPT_PUT;) /* will send file's data */
990 /* NB: if G_error_pkt_str or G_error_pkt_reason is set up,
991 * tftp_protocol() just sends one error pkt and returns */
994 close(STDIN_FILENO); /* close old, possibly wildcard socket */
995 /* tftp_protocol() will create new one, bound to particular local IP */
996 result = tftp_protocol(
999 IF_TFTP(, NULL /*remote_file*/)
1000 IF_FEATURE_TFTP_BLOCKSIZE(, want_transfer_size)
1001 IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
1006 strcpy(G_error_pkt_str, error_msg);
1009 #endif /* ENABLE_TFTPD */
1011 #endif /* ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT */