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 G_error_pkt_reason = ERR_NOFILE;
406 strcpy(G_error_pkt_str, "can't open file");
409 /* gcc 4.3.1 would NOT optimize it out as it should! */
410 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
411 if (blksize != TFTP_BLKSIZE_DEFAULT || want_transfer_size) {
412 /* Create and send OACK packet. */
413 /* For the download case, block_nr is still 1 -
414 * we expect 1st ACK from peer to be for (block_nr-1),
415 * that is, for "block 0" which is our OACK pkt */
417 goto add_blksize_opt;
420 if (CMD_GET(option_mask32)) {
421 /* It's upload and we don't send OACK.
422 * We must ACK 1st packet (with filename)
423 * as if it is "block 0" */
427 /* Open file (must be after changing user) */
428 local_fd = CMD_GET(option_mask32) ? STDOUT_FILENO : STDIN_FILENO;
429 if (NOT_LONE_DASH(local_file))
430 local_fd = xopen(local_file, open_mode);
431 /* Removing #if, or using if() statement instead of #if may lead to
432 * "warning: null argument where non-null required": */
436 /* We can't (and don't really need to) bind the socket:
437 * we don't know from which local IP datagrams will be sent,
438 * but kernel will pick the same IP every time (unless routing
439 * table is changed), thus peer will see dgrams consistently
440 * coming from the same IP.
441 * We would like to connect the socket, but since peer's
442 * UDP code can be less perfect than ours, _peer's_ IP:port
443 * in replies may differ from IP:port we used to send
444 * our first packet. We can connect() only when we get
449 if (CMD_GET(option_mask32)) {
452 /* add filename and mode */
453 /* fill in packet if the filename fits into xbuf */
454 len = strlen(remote_file) + 1;
455 if (2 + len + sizeof("octet") >= io_bufsize) {
456 bb_error_msg("remote filename is too long");
459 strcpy(cp, remote_file);
461 /* add "mode" part of the packet */
463 cp += sizeof("octet");
465 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
466 if (blksize == TFTP_BLKSIZE_DEFAULT && !want_transfer_size)
469 /* Need to add option to pkt */
470 if ((&xbuf[io_bufsize - 1] - cp) < sizeof("blksize NNNNN tsize ") + sizeof(off_t)*3) {
471 bb_error_msg("remote filename is too long");
476 #endif /* ENABLE_TFTP */
478 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
480 if (blksize != TFTP_BLKSIZE_DEFAULT) {
481 /* add "blksize", <nul>, blksize, <nul> */
482 strcpy(cp, "blksize");
483 cp += sizeof("blksize");
484 cp += snprintf(cp, 6, "%d", blksize) + 1;
486 if (want_transfer_size) {
487 /* add "tsize", <nul>, size, <nul> (see RFC2349) */
488 /* if tftp and downloading, we send "0" (since we opened local_fd with O_TRUNC)
489 * and this makes server to send "tsize" option with the size */
490 /* if tftp and uploading, we send file size (maybe dont, to not confuse old servers???) */
491 /* if tftpd and downloading, we are answering to client's request */
492 /* if tftpd and uploading: !want_transfer_size, this code is not executed */
495 cp += sizeof("tsize");
497 fstat(local_fd, &st);
498 cp += sprintf(cp, "%"OFF_FMT"u", (off_t)st.st_size) + 1;
499 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
500 /* Save for progress bar. If 0 (tftp downloading),
501 * we look at server's reply later */
503 if (remote_file && st.st_size)
504 tftp_progress_init();
508 /* First packet is built, so skip packet generation */
512 /* Using mostly goto's - continue/break will be less clear
513 * in where we actually jump to */
515 /* Build ACK or DATA */
517 *((uint16_t*)cp) = htons(block_nr);
521 if (CMD_PUT(option_mask32)) {
523 len = full_read(local_fd, cp, blksize);
525 goto send_read_err_pkt;
527 if (len != blksize) {
531 IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += len;)
535 *((uint16_t*)xbuf) = htons(opcode); /* fill in opcode part */
536 send_len = cp - xbuf;
537 /* NB: send_len value is preserved in code below
538 * for potential resend */
540 retries = TFTP_NUM_RETRIES; /* re-initialize */
541 waittime_ms = TFTP_TIMEOUT_MS;
544 #if ENABLE_TFTP_DEBUG
545 fprintf(stderr, "sending %u bytes\n", send_len);
546 for (cp = xbuf; cp < &xbuf[send_len]; cp++)
547 fprintf(stderr, "%02x ", (unsigned char) *cp);
548 fprintf(stderr, "\n");
550 xsendto(socket_fd, xbuf, send_len, &peer_lsa->u.sa, peer_lsa->len);
552 #if ENABLE_FEATURE_TFTP_PROGRESS_BAR
553 if (is_bb_progress_inited(&G.pmt))
554 tftp_progress_update();
556 /* Was it final ACK? then exit */
557 if (finished && (opcode == TFTP_ACK))
562 /*pfd[0].fd = socket_fd;*/
563 pfd[0].events = POLLIN;
564 switch (safe_poll(pfd, 1, waittime_ms)) {
566 /*bb_perror_msg("poll"); - done in safe_poll */
571 tftp_progress_done();
572 bb_error_msg("timeout");
573 goto ret; /* no err packet sent */
576 /* exponential backoff with limit */
577 waittime_ms += waittime_ms/2;
578 if (waittime_ms > TFTP_MAXTIMEOUT_MS) {
579 waittime_ms = TFTP_MAXTIMEOUT_MS;
582 goto send_again; /* resend last sent pkt */
585 /* tftp (not tftpd!) receiving 1st packet */
586 our_lsa = ((void*)(ptrdiff_t)-1); /* not NULL */
587 len = recvfrom(socket_fd, rbuf, io_bufsize, 0,
588 &peer_lsa->u.sa, &peer_lsa->len);
589 /* Our first dgram went to port 69
590 * but reply may come from different one.
591 * Remember and use this new port (and IP) */
593 xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
595 /* tftpd, or not the very first packet:
596 * socket is connect()ed, can just read from it. */
597 /* Don't full_read()!
598 * This is not TCP, one read == one pkt! */
599 len = safe_read(socket_fd, rbuf, io_bufsize);
602 goto send_read_err_pkt;
604 if (len < 4) { /* too small? */
609 /* Process recv'ed packet */
610 opcode = ntohs( ((uint16_t*)rbuf)[0] );
611 recv_blk = ntohs( ((uint16_t*)rbuf)[1] );
612 #if ENABLE_TFTP_DEBUG
613 fprintf(stderr, "received %d bytes: %04x %04x\n", len, opcode, recv_blk);
615 if (opcode == TFTP_ERROR) {
616 static const char errcode_str[] ALIGN1 =
622 "unknown transfer id\0"
623 "file already exists\0"
627 const char *msg = "";
629 if (len > 4 && rbuf[4] != '\0') {
631 rbuf[io_bufsize - 1] = '\0'; /* paranoia */
632 } else if (recv_blk <= 8) {
633 msg = nth_string(errcode_str, recv_blk);
635 bb_error_msg("server error: (%u) %s", recv_blk, msg);
639 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
642 if (opcode == TFTP_OACK) {
643 /* server seems to support options */
646 res = tftp_get_option("blksize", &rbuf[2], len - 2);
648 blksize = tftp_blksize_check(res, blksize);
650 G_error_pkt_reason = ERR_BAD_OPT;
653 io_bufsize = blksize + 4;
655 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
656 if (remote_file && G.size == 0) { /* if we don't know it yet */
657 res = tftp_get_option("tsize", &rbuf[2], len - 2);
659 G.size = bb_strtoull(res, NULL, 10);
661 tftp_progress_init();
665 if (CMD_GET(option_mask32)) {
666 /* We'll send ACK for OACK,
667 * such ACK has "block no" of 0 */
673 * "An option not acknowledged by the server
674 * must be ignored by the client and server
675 * as if it were never requested." */
676 if (blksize != TFTP_BLKSIZE_DEFAULT)
677 bb_error_msg("falling back to blocksize "TFTP_BLKSIZE_DEFAULT_STR);
678 blksize = TFTP_BLKSIZE_DEFAULT;
679 io_bufsize = TFTP_BLKSIZE_DEFAULT + 4;
682 /* block_nr is already advanced to next block# we expect
683 * to get / block# we are about to send next time */
685 if (CMD_GET(option_mask32) && (opcode == TFTP_DATA)) {
686 if (recv_blk == block_nr) {
687 int sz = full_write(local_fd, &rbuf[4], len - 4);
689 strcpy(G_error_pkt_str, bb_msg_write_error);
690 G_error_pkt_reason = ERR_WRITE;
696 IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += sz;)
697 continue; /* send ACK */
699 /* Disabled to cope with servers with Sorcerer's Apprentice Syndrome */
701 if (recv_blk == (block_nr - 1)) {
702 /* Server lost our TFTP_ACK. Resend it */
709 if (CMD_PUT(option_mask32) && (opcode == TFTP_ACK)) {
710 /* did peer ACK our last DATA pkt? */
711 if (recv_blk == (uint16_t) (block_nr - 1)) {
714 continue; /* send next block */
717 /* Awww... recv'd packet is not recognized! */
719 /* why recv_again? - rfc1123 says:
720 * "The sender (i.e., the side originating the DATA packets)
721 * must never resend the current DATA packet on receipt
722 * of a duplicate ACK".
723 * DATA pkts are resent ONLY on timeout.
724 * Thus "goto send_again" will ba a bad mistake above.
726 * http://en.wikipedia.org/wiki/Sorcerer's_Apprentice_Syndrome
728 } /* end of "while (1)" */
730 if (ENABLE_FEATURE_CLEAN_UP) {
736 return finished == 0; /* returns 1 on failure */
739 strcpy(G_error_pkt_str, bb_msg_read_error);
741 if (G_error_pkt_str[0])
742 bb_error_msg("%s", G_error_pkt_str);
743 G.error_pkt[1] = TFTP_ERROR;
744 xsendto(socket_fd, G.error_pkt, 4 + 1 + strlen(G_error_pkt_str),
745 &peer_lsa->u.sa, peer_lsa->len);
752 int tftp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
753 int tftp_main(int argc UNUSED_PARAM, char **argv)
755 len_and_sockaddr *peer_lsa;
756 const char *local_file = NULL;
757 const char *remote_file = NULL;
758 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
759 const char *blksize_str = TFTP_BLKSIZE_DEFAULT_STR;
768 if (ENABLE_FEATURE_TFTP_HPA_COMPAT) {
769 /* As of 2019, common tftp client in Linux distros
770 * is one maintained by H. Peter Anvin:
771 * I've seen "tftp-hpa 5.2" version.
772 * Make the following command work:
773 * "tftp HOST [PORT] -m binary -c get/put FILE"
774 * by mangling it into "....... -g/-p -r FILE"
775 * and accepting and ignoring -m STR option.
779 if (strcmp(argv[i], "-c") == 0) {
782 if (strcmp(argv[i], "get") == 0) {
783 argv[i-1] = (char*)"-g";
784 argv[i] = (char*)"-r";
787 if (strcmp(argv[i], "put") == 0) {
788 argv[i-1] = (char*)"-p";
789 argv[i] = (char*)"-r";
797 IF_GETPUT(opt =) getopt32(argv, "^"
798 IF_FEATURE_TFTP_GET("g") IF_FEATURE_TFTP_PUT("p")
799 "l:r:" IF_FEATURE_TFTP_BLOCKSIZE("b:")
800 IF_FEATURE_TFTP_HPA_COMPAT("m:")
802 /* -p or -g is mandatory, and they are mutually exclusive */
803 IF_FEATURE_TFTP_GET("g:") IF_FEATURE_TFTP_PUT("p:")
804 IF_GETPUT("g--p:p--g:"),
805 &local_file, &remote_file
806 IF_FEATURE_TFTP_BLOCKSIZE(, &blksize_str)
807 IF_FEATURE_TFTP_HPA_COMPAT(, NULL)
811 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
812 /* Check if the blksize is valid:
813 * RFC2348 says between 8 and 65464 */
814 blksize = tftp_blksize_check(blksize_str, 65564);
816 //bb_error_msg("bad block size");
823 const char *slash = strrchr(remote_file, '/');
824 local_file = slash ? slash + 1 : remote_file;
827 remote_file = local_file;
830 /* Error if filename or host is not known */
831 if (!remote_file || !argv[0])
834 port = bb_lookup_port(argv[1], "udp", 69);
835 peer_lsa = xhost2sockaddr(argv[0], port);
837 # if ENABLE_TFTP_DEBUG
838 fprintf(stderr, "using server '%s', remote_file '%s', local_file '%s'\n",
839 xmalloc_sockaddr2dotted(&peer_lsa->u.sa),
840 remote_file, local_file);
843 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
844 G.file = remote_file;
846 result = tftp_protocol(
847 NULL /*our_lsa*/, peer_lsa,
848 local_file, remote_file
849 IF_FEATURE_TFTP_BLOCKSIZE(, 1 /* want_transfer_size */)
850 IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
852 tftp_progress_done();
854 if (result != EXIT_SUCCESS && NOT_LONE_DASH(local_file) && CMD_GET(opt)) {
860 #endif /* ENABLE_TFTP */
863 int tftpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
864 int tftpd_main(int argc UNUSED_PARAM, char **argv)
866 len_and_sockaddr *our_lsa;
867 len_and_sockaddr *peer_lsa;
868 char *mode, *user_opt;
869 char *local_file = local_file;
870 const char *error_msg;
871 int opt, result, opcode;
872 IF_FEATURE_TFTP_BLOCKSIZE(int blksize = TFTP_BLKSIZE_DEFAULT;)
873 IF_FEATURE_TFTP_BLOCKSIZE(int want_transfer_size = 0;)
877 our_lsa = get_sock_lsa(STDIN_FILENO);
879 /* This is confusing:
880 *bb_error_msg_and_die("stdin is not a socket");
883 /* Help text says that tftpd must be used as inetd service,
884 * which is by far the most usual cause of get_sock_lsa
887 peer_lsa = xzalloc(LSA_LEN_SIZE + our_lsa->len);
888 peer_lsa->len = our_lsa->len;
890 /* Shifting to not collide with TFTP_OPTs */
891 opt = option_mask32 = TFTPD_OPT | (getopt32(argv, "rcu:l", &user_opt) << 8);
893 if (opt & TFTPD_OPT_l) {
894 openlog(applet_name, LOG_PID, LOG_DAEMON);
895 logmode = LOGMODE_SYSLOG;
897 if (opt & TFTPD_OPT_u) {
898 /* Must be before xchroot */
899 G.pw = xgetpwnam(user_opt);
905 result = recv_from_to(STDIN_FILENO,
906 G.block_buf, sizeof(G.block_buf) + 1,
907 /* ^^^ sizeof+1 to reliably detect oversized input */
909 &peer_lsa->u.sa, &our_lsa->u.sa, our_lsa->len);
911 error_msg = "malformed packet";
912 opcode = ntohs(*(uint16_t*)G.block_buf);
913 if (result < 4 || result > sizeof(G.block_buf)
914 /*|| G.block_buf[result-1] != '\0' - bug compatibility, see below */
915 || (IF_FEATURE_TFTP_PUT(opcode != TFTP_RRQ) /* not download */
917 IF_FEATURE_TFTP_GET(opcode != TFTP_WRQ) /* not upload */
922 /* Some HP PA-RISC firmware always sends fixed 516-byte requests,
923 * with trailing garbage.
924 * Support that by not requiring NUL to be the last byte (see above).
925 * To make strXYZ() ops safe, force NUL termination:
927 G.block_buf_tail[0] = '\0';
929 local_file = G.block_buf + 2;
930 if (local_file[0] == '.' || strstr(local_file, "/.")) {
931 error_msg = "dot in file name";
934 mode = local_file + strlen(local_file) + 1;
935 /* RFC 1350 says mode string is case independent */
936 if (mode >= G.block_buf + result || strcasecmp(mode, "octet") != 0) {
937 error_msg = "mode is not 'octet'";
940 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
943 char *opt_str = mode + sizeof("octet");
944 int opt_len = G.block_buf + result - opt_str;
946 res = tftp_get_option("blksize", opt_str, opt_len);
948 blksize = tftp_blksize_check(res, 65564);
950 G_error_pkt_reason = ERR_BAD_OPT;
951 /* will just send error pkt */
955 if (opcode != TFTP_WRQ /* download? */
956 /* did client ask us about file size? */
957 && tftp_get_option("tsize", opt_str, opt_len)
959 want_transfer_size = 1;
965 if (!ENABLE_FEATURE_TFTP_PUT || opcode == TFTP_WRQ) {
966 if (opt & TFTPD_OPT_r) {
967 /* This would mean "disk full" - not true */
968 /*G_error_pkt_reason = ERR_WRITE;*/
969 error_msg = bb_msg_write_error;
972 IF_GETPUT(option_mask32 |= TFTP_OPT_GET;) /* will receive file's data */
974 IF_GETPUT(option_mask32 |= TFTP_OPT_PUT;) /* will send file's data */
977 /* NB: if G_error_pkt_str or G_error_pkt_reason is set up,
978 * tftp_protocol() just sends one error pkt and returns */
981 close(STDIN_FILENO); /* close old, possibly wildcard socket */
982 /* tftp_protocol() will create new one, bound to particular local IP */
983 result = tftp_protocol(
986 IF_TFTP(, NULL /*remote_file*/)
987 IF_FEATURE_TFTP_BLOCKSIZE(, want_transfer_size)
988 IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
993 strcpy(G_error_pkt_str, error_msg);
997 #endif /* ENABLE_TFTPD */
999 #endif /* ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT */