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;
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 /* Examples of network traffic.
358 * Note two cases when ACKs with block# of 0 are sent.
360 * Download without options:
361 * tftp -> "\0\1FILENAME\0octet\0"
362 * "\0\3\0\1FILEDATA..." <- tftpd
365 * Download with option of blksize 16384:
366 * tftp -> "\0\1FILENAME\0octet\0blksize\00016384\0"
367 * "\0\6blksize\00016384\0" <- tftpd
369 * "\0\3\0\1FILEDATA..." <- tftpd
372 * Upload without options:
373 * tftp -> "\0\2FILENAME\0octet\0"
374 * "\0\4\0\0" <- tftpd
375 * tftp -> "\0\3\0\1FILEDATA..."
376 * "\0\4\0\1" <- tftpd
378 * Upload with option of blksize 16384:
379 * tftp -> "\0\2FILENAME\0octet\0blksize\00016384\0"
380 * "\0\6blksize\00016384\0" <- tftpd
381 * tftp -> "\0\3\0\1FILEDATA..."
382 * "\0\4\0\1" <- tftpd
388 if (!ENABLE_TFTP || our_lsa) { /* tftpd */
389 /* Open file (must be after changing user) */
390 int open_mode = O_RDONLY;
391 if (CMD_GET(option_mask32)) {
392 open_mode = O_WRONLY | O_TRUNC | O_CREAT;
393 if ((option_mask32 & (TFTPD_OPT+TFTPD_OPT_c)) == TFTPD_OPT) {
394 /* tftpd without -c */
395 open_mode = O_WRONLY | O_TRUNC;
398 local_fd = open(local_file, open_mode, 0666);
400 /* sanitize name, it came from untrusted remote side */
401 unsigned char *p = (void *) local_file;
407 bb_perror_msg("can't open '%s'", local_file);
408 G_error_pkt_reason = ERR_NOFILE;
409 strcpy(G_error_pkt_str, "can't open file");
410 goto send_err_pkt_nomsg;
413 /* gcc 4.3.1 would NOT optimize it out as it should! */
414 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
415 if (blksize != TFTP_BLKSIZE_DEFAULT || want_transfer_size) {
416 /* Create and send OACK packet. */
417 /* For the download case, block_nr is still 1 -
418 * we expect 1st ACK from peer to be for (block_nr-1),
419 * that is, for "block 0" which is our OACK pkt */
421 goto add_blksize_opt;
424 if (CMD_GET(option_mask32)) {
425 /* It's upload and we don't send OACK.
426 * We must ACK 1st packet (with filename)
427 * as if it is "block 0" */
431 if (CMD_PUT(option_mask32)) {
432 local_fd = STDIN_FILENO;
434 local_fd = xopen(local_file, O_RDONLY);
436 /* Removing #if, or using if() statement instead of #if may lead to
437 * "warning: null argument where non-null required": */
441 /* We can't (and don't really need to) bind the socket:
442 * we don't know from which local IP datagrams will be sent,
443 * but kernel will pick the same IP every time (unless routing
444 * table is changed), thus peer will see dgrams consistently
445 * coming from the same IP.
446 * We would like to connect the socket, but since peer's
447 * UDP code can be less perfect than ours, _peer's_ IP:port
448 * in replies may differ from IP:port we used to send
449 * our first packet. We can connect() only when we get
454 if (CMD_GET(option_mask32)) {
457 /* add filename and mode */
458 /* fill in packet if the filename fits into xbuf */
459 len = strlen(remote_file);
460 if (len + 3 + sizeof("octet") >= io_bufsize) {
461 bb_simple_error_msg("remote filename is too long");
464 cp = stpcpy(cp, remote_file) + 1;
465 /* add "mode" part of the packet */
466 cp = stpcpy(cp, "octet") + 1;
468 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
469 if (blksize == TFTP_BLKSIZE_DEFAULT && !want_transfer_size)
472 /* Need to add option to pkt */
473 if ((&xbuf[io_bufsize - 1] - cp) < sizeof("blksize NNNNN tsize ") + sizeof(off_t)*3) {
474 bb_simple_error_msg("remote filename is too long");
479 #endif /* ENABLE_TFTP */
481 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
483 if (blksize != TFTP_BLKSIZE_DEFAULT) {
484 /* add "blksize", <nul>, blksize, <nul> */
485 strcpy(cp, "blksize");
486 cp += sizeof("blksize");
487 cp += snprintf(cp, 6, "%d", blksize) + 1;
489 if (want_transfer_size) {
490 /* add "tsize", <nul>, size, <nul> (see RFC2349) */
491 /* if tftp and downloading, we send "0" (local_fd is not open yet)
492 * and this makes server to send "tsize" option with the size */
493 /* if tftp and uploading, we send file size (maybe dont, to not confuse old servers???) */
494 /* if tftpd and downloading, we are answering to client's request */
495 /* if tftpd and uploading: !want_transfer_size, this code is not executed */
498 cp += sizeof("tsize");
501 fstat(local_fd, &st);
502 cp += sprintf(cp, "%"OFF_FMT"u", (off_t)st.st_size) + 1;
503 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
504 /* Save for progress bar. If 0 (tftp downloading),
505 * we look at server's reply later */
507 if (remote_file && st.st_size)
508 tftp_progress_init();
512 /* First packet is built, so skip packet generation */
516 /* Using mostly goto's - continue/break will be less clear
517 * in where we actually jump to */
519 /* Build ACK or DATA */
521 *((uint16_t*)cp) = htons(block_nr);
525 if (CMD_PUT(option_mask32)) {
527 len = full_read(local_fd, cp, blksize);
529 goto send_read_err_pkt;
531 if (len != blksize) {
535 IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += len;)
539 *((uint16_t*)xbuf) = htons(opcode); /* fill in opcode part */
540 send_len = cp - xbuf;
541 /* NB: send_len value is preserved in code below
542 * for potential resend */
544 retries = TFTP_NUM_RETRIES; /* re-initialize */
545 waittime_ms = TFTP_TIMEOUT_MS;
548 #if ENABLE_TFTP_DEBUG
549 fprintf(stderr, "sending %u bytes\n", send_len);
550 for (cp = xbuf; cp < &xbuf[send_len]; cp++)
551 fprintf(stderr, "%02x ", (unsigned char) *cp);
552 fprintf(stderr, "\n");
554 xsendto(socket_fd, xbuf, send_len, &peer_lsa->u.sa, peer_lsa->len);
556 #if ENABLE_FEATURE_TFTP_PROGRESS_BAR
557 if (is_bb_progress_inited(&G.pmt))
558 tftp_progress_update();
560 /* Was it final ACK? then exit */
561 if (finished && (opcode == TFTP_ACK))
566 /*pfd[0].fd = socket_fd;*/
567 pfd[0].events = POLLIN;
568 switch (safe_poll(pfd, 1, waittime_ms)) {
570 /*bb_perror_msg("poll"); - done in safe_poll */
575 tftp_progress_done();
576 bb_simple_error_msg("timeout");
577 goto ret; /* no err packet sent */
580 /* exponential backoff with limit */
581 waittime_ms += waittime_ms/2;
582 if (waittime_ms > TFTP_MAXTIMEOUT_MS) {
583 waittime_ms = TFTP_MAXTIMEOUT_MS;
586 goto send_again; /* resend last sent pkt */
589 /* tftp (not tftpd!) receiving 1st packet */
590 our_lsa = ((void*)(ptrdiff_t)-1); /* not NULL */
591 len = recvfrom(socket_fd, rbuf, io_bufsize, 0,
592 &peer_lsa->u.sa, &peer_lsa->len);
593 /* Our first dgram went to port 69
594 * but reply may come from different one.
595 * Remember and use this new port (and IP) */
597 xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
599 /* tftpd, or not the very first packet:
600 * socket is connect()ed, can just read from it. */
601 /* Don't full_read()!
602 * This is not TCP, one read == one pkt! */
603 len = safe_read(socket_fd, rbuf, io_bufsize);
606 goto send_read_err_pkt;
608 if (len < 4) { /* too small? */
613 /* Process recv'ed packet */
614 opcode = ntohs( ((uint16_t*)rbuf)[0] );
615 recv_blk = ntohs( ((uint16_t*)rbuf)[1] );
616 #if ENABLE_TFTP_DEBUG
617 fprintf(stderr, "received %d bytes: %04x %04x\n", len, opcode, recv_blk);
619 if (opcode == TFTP_ERROR) {
620 static const char errcode_str[] ALIGN1 =
626 "unknown transfer id\0"
627 "file already exists\0"
631 const char *msg = "";
633 if (len > 4 && rbuf[4] != '\0') {
635 rbuf[io_bufsize - 1] = '\0'; /* paranoia */
636 } else if (recv_blk <= 8) {
637 msg = nth_string(errcode_str, recv_blk);
639 bb_error_msg("server error: (%u) %s", recv_blk, msg);
643 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
646 if (opcode == TFTP_OACK) {
647 /* server seems to support options */
650 res = tftp_get_option("blksize", &rbuf[2], len - 2);
652 blksize = tftp_blksize_check(res, blksize);
654 G_error_pkt_reason = ERR_BAD_OPT;
657 io_bufsize = blksize + 4;
659 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
660 if (remote_file && G.size == 0) { /* if we don't know it yet */
661 res = tftp_get_option("tsize", &rbuf[2], len - 2);
663 G.size = bb_strtoull(res, NULL, 10);
665 tftp_progress_init();
669 if (CMD_GET(option_mask32)) {
670 /* We'll send ACK for OACK,
671 * such ACK has "block no" of 0 */
677 * "An option not acknowledged by the server
678 * must be ignored by the client and server
679 * as if it were never requested." */
680 if (blksize != TFTP_BLKSIZE_DEFAULT)
681 bb_simple_error_msg("falling back to blocksize "TFTP_BLKSIZE_DEFAULT_STR);
682 blksize = TFTP_BLKSIZE_DEFAULT;
683 io_bufsize = TFTP_BLKSIZE_DEFAULT + 4;
686 /* block_nr is already advanced to next block# we expect
687 * to get / block# we are about to send next time */
689 if (CMD_GET(option_mask32) && (opcode == TFTP_DATA)) {
690 if (recv_blk == block_nr) {
692 if (local_fd == -1) {
693 local_fd = STDOUT_FILENO;
695 local_fd = xopen(local_file, O_WRONLY | O_TRUNC | O_CREAT);
697 sz = full_write(local_fd, &rbuf[4], len - 4);
699 strcpy(G_error_pkt_str, bb_msg_write_error);
700 G_error_pkt_reason = ERR_WRITE;
706 IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += sz;)
707 continue; /* send ACK */
709 /* Disabled to cope with servers with Sorcerer's Apprentice Syndrome */
711 if (recv_blk == (block_nr - 1)) {
712 /* Server lost our TFTP_ACK. Resend it */
719 if (CMD_PUT(option_mask32) && (opcode == TFTP_ACK)) {
720 /* did peer ACK our last DATA pkt? */
721 if (recv_blk == (uint16_t) (block_nr - 1)) {
724 continue; /* send next block */
727 /* Awww... recv'd packet is not recognized! */
729 /* why recv_again? - rfc1123 says:
730 * "The sender (i.e., the side originating the DATA packets)
731 * must never resend the current DATA packet on receipt
732 * of a duplicate ACK".
733 * DATA pkts are resent ONLY on timeout.
734 * Thus "goto send_again" will be a bad mistake above.
736 * http://en.wikipedia.org/wiki/Sorcerer's_Apprentice_Syndrome
738 } /* end of "while (1)" */
740 if (ENABLE_FEATURE_CLEAN_UP) {
751 strcpy(G_error_pkt_str, bb_msg_read_error);
753 if (G_error_pkt_str[0])
754 bb_simple_error_msg(G_error_pkt_str);
756 G.error_pkt[1] = TFTP_ERROR;
757 xsendto(socket_fd, G.error_pkt, 4 + 1 + strlen(G_error_pkt_str),
758 &peer_lsa->u.sa, peer_lsa->len);
760 if (local_fd >= 0 && CMD_GET(option_mask32) && local_file)
767 int tftp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
768 int tftp_main(int argc UNUSED_PARAM, char **argv)
770 len_and_sockaddr *peer_lsa;
771 const char *local_file = NULL;
772 const char *remote_file = NULL;
773 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
774 const char *blksize_str = TFTP_BLKSIZE_DEFAULT_STR;
782 if (ENABLE_FEATURE_TFTP_HPA_COMPAT) {
783 /* As of 2019, common tftp client in Linux distros
784 * is one maintained by H. Peter Anvin:
785 * I've seen "tftp-hpa 5.2" version.
786 * Make the following command work:
787 * "tftp HOST [PORT] -m binary -c get/put FILE"
788 * by mangling it into "....... -g/-p -r FILE"
789 * and accepting and ignoring -m STR option.
793 /* Accept not only -c, but also
794 * -lc, -cl, -llcclcllcc etc:
795 * "-l Literal mode (do not recognize HOST:FILE)"
796 * since we do not recognize that syntax anyway,
797 * might as well allow the option.
799 if (argv[i][0] == '-' && strchr(argv[i], 'c')
800 /*&& argv[i][1+strspn(argv[i]+1, "lc")] == '\0'*/
804 if (strcmp(argv[i], "get") == 0) {
805 argv[i-1] = (char*)"-g";
806 argv[i] = (char*)"-r";
809 if (strcmp(argv[i], "put") == 0) {
810 argv[i-1] = (char*)"-p";
811 argv[i] = (char*)"-r";
820 IF_FEATURE_TFTP_GET("g") IF_FEATURE_TFTP_PUT("p")
821 "l:r:" IF_FEATURE_TFTP_BLOCKSIZE("b:")
822 IF_FEATURE_TFTP_HPA_COMPAT("m:")
824 /* -p or -g is mandatory, and they are mutually exclusive */
825 IF_FEATURE_TFTP_GET("g:") IF_FEATURE_TFTP_PUT("p:")
826 IF_GETPUT("g--p:p--g:"),
827 &local_file, &remote_file
828 IF_FEATURE_TFTP_BLOCKSIZE(, &blksize_str)
829 IF_FEATURE_TFTP_HPA_COMPAT(, NULL)
833 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
834 /* Check if the blksize is valid:
835 * RFC2348 says between 8 and 65464 */
836 blksize = tftp_blksize_check(blksize_str, 65564);
838 //bb_error_msg("bad block size");
845 const char *slash = strrchr(remote_file, '/');
846 local_file = slash ? slash + 1 : remote_file;
849 remote_file = local_file;
852 /* Error if filename or host is not known */
853 if (!remote_file || !argv[0])
856 port = bb_lookup_port(argv[1], "udp", 69);
857 peer_lsa = xhost2sockaddr(argv[0], port);
859 # if ENABLE_TFTP_DEBUG
860 fprintf(stderr, "using server '%s', remote_file '%s', local_file '%s'\n",
861 xmalloc_sockaddr2dotted(&peer_lsa->u.sa),
862 remote_file, local_file);
865 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
866 G.file = remote_file;
868 result = tftp_protocol(
869 NULL /*our_lsa*/, peer_lsa,
870 (LONE_DASH(local_file) ? NULL : local_file), remote_file
871 IF_FEATURE_TFTP_BLOCKSIZE(, 1 /* want_transfer_size */)
872 IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
874 tftp_progress_done();
878 #endif /* ENABLE_TFTP */
881 int tftpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
882 int tftpd_main(int argc UNUSED_PARAM, char **argv)
884 len_and_sockaddr *our_lsa;
885 len_and_sockaddr *peer_lsa;
886 char *mode, *user_opt;
887 char *local_file = local_file;
888 const char *error_msg;
889 int opt, result, opcode;
890 IF_FEATURE_TFTP_BLOCKSIZE(int blksize = TFTP_BLKSIZE_DEFAULT;)
891 IF_FEATURE_TFTP_BLOCKSIZE(int want_transfer_size = 0;)
895 our_lsa = get_sock_lsa(STDIN_FILENO);
897 /* This is confusing:
898 *bb_error_msg_and_die("stdin is not a socket");
901 /* Help text says that tftpd must be used as inetd service,
902 * which is by far the most usual cause of get_sock_lsa
905 peer_lsa = xzalloc(LSA_LEN_SIZE + our_lsa->len);
906 peer_lsa->len = our_lsa->len;
908 /* Shifting to not collide with TFTP_OPTs */
909 opt = option_mask32 = TFTPD_OPT | (getopt32(argv, "rcu:l", &user_opt) << 8);
911 if (opt & TFTPD_OPT_l) {
912 openlog(applet_name, LOG_PID, LOG_DAEMON);
913 logmode = LOGMODE_SYSLOG;
915 if (opt & TFTPD_OPT_u) {
916 /* Must be before xchroot */
917 G.pw = xgetpwnam(user_opt);
923 result = recv_from_to(STDIN_FILENO,
924 G.block_buf, sizeof(G.block_buf) + 1,
925 /* ^^^ sizeof+1 to reliably detect oversized input */
927 &peer_lsa->u.sa, &our_lsa->u.sa, our_lsa->len);
929 error_msg = "malformed packet";
930 opcode = ntohs(*(uint16_t*)G.block_buf);
931 if (result < 4 || result > sizeof(G.block_buf)
932 /*|| G.block_buf[result-1] != '\0' - bug compatibility, see below */
933 || (IF_FEATURE_TFTP_PUT(opcode != TFTP_RRQ) /* not download */
935 IF_FEATURE_TFTP_GET(opcode != TFTP_WRQ) /* not upload */
940 /* Some HP PA-RISC firmware always sends fixed 516-byte requests,
941 * with trailing garbage.
942 * Support that by not requiring NUL to be the last byte (see above).
943 * To make strXYZ() ops safe, force NUL termination:
945 G.block_buf_tail[0] = '\0';
947 local_file = G.block_buf + 2;
948 if (local_file[0] == '.' || strstr(local_file, "/.")) {
949 error_msg = "dot in file name";
952 mode = local_file + strlen(local_file) + 1;
953 /* RFC 1350 says mode string is case independent */
954 if (mode >= G.block_buf + result || strcasecmp(mode, "octet") != 0) {
955 error_msg = "mode is not 'octet'";
958 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
961 char *opt_str = mode + sizeof("octet");
962 int opt_len = G.block_buf + result - opt_str;
964 res = tftp_get_option("blksize", opt_str, opt_len);
966 blksize = tftp_blksize_check(res, 65564);
968 G_error_pkt_reason = ERR_BAD_OPT;
969 /* will just send error pkt */
973 if (opcode != TFTP_WRQ /* download? */
974 /* did client ask us about file size? */
975 && tftp_get_option("tsize", opt_str, opt_len)
977 want_transfer_size = 1;
983 if (!ENABLE_FEATURE_TFTP_PUT || opcode == TFTP_WRQ) {
984 if (opt & TFTPD_OPT_r) {
985 /* This would mean "disk full" - not true */
986 /*G_error_pkt_reason = ERR_WRITE;*/
987 error_msg = bb_msg_write_error;
990 IF_GETPUT(option_mask32 |= TFTP_OPT_GET;) /* will receive file's data */
992 IF_GETPUT(option_mask32 |= TFTP_OPT_PUT;) /* will send file's data */
995 /* NB: if G_error_pkt_str or G_error_pkt_reason is set up,
996 * tftp_protocol() just sends one error pkt and returns */
999 close(STDIN_FILENO); /* close old, possibly wildcard socket */
1000 /* tftp_protocol() will create new one, bound to particular local IP */
1001 result = tftp_protocol(
1004 IF_TFTP(, NULL /*remote_file*/)
1005 IF_FEATURE_TFTP_BLOCKSIZE(, want_transfer_size)
1006 IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
1011 strcpy(G_error_pkt_str, error_msg);
1014 #endif /* ENABLE_TFTPD */
1016 #endif /* ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT */