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
35 //config: bool "tftpd (10 kb)"
38 //config: Trivial File Transfer Protocol server.
39 //config: It expects that stdin is a datagram socket and a packet
40 //config: is already pending on it. It will exit after one transfer.
41 //config: In other words: it should be run from inetd in nowait mode,
42 //config: or from udpsvd. Example: "udpsvd -E 0 69 tftpd DIR"
44 //config:config FEATURE_TFTP_GET
45 //config: bool "Enable 'tftp get' and/or tftpd upload code"
47 //config: depends on TFTP || TFTPD
49 //config: Add support for the GET command within the TFTP client. This allows
50 //config: a client to retrieve a file from a TFTP server.
51 //config: Also enable upload support in tftpd, if tftpd is selected.
53 //config: Note: this option does _not_ make tftpd capable of download
54 //config: (the usual operation people need from it)!
56 //config:config FEATURE_TFTP_PUT
57 //config: bool "Enable 'tftp put' and/or tftpd download code"
59 //config: depends on TFTP || TFTPD
61 //config: Add support for the PUT command within the TFTP client. This allows
62 //config: a client to transfer a file to a TFTP server.
63 //config: Also enable download support in tftpd, if tftpd is selected.
65 //config:config FEATURE_TFTP_BLOCKSIZE
66 //config: bool "Enable 'blksize' and 'tsize' protocol options"
68 //config: depends on TFTP || TFTPD
70 //config: Allow tftp to specify block size, and tftpd to understand
71 //config: "blksize" and "tsize" options.
73 //config:config TFTP_DEBUG
74 //config: bool "Enable debug"
76 //config: depends on TFTP || TFTPD
78 //config: Make tftp[d] print debugging messages on stderr.
79 //config: This is useful if you are diagnosing a bug in tftp[d].
81 //applet:#if ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT
82 //applet:IF_TFTP(APPLET(tftp, BB_DIR_USR_BIN, BB_SUID_DROP))
83 //applet:IF_TFTPD(APPLET(tftpd, BB_DIR_USR_SBIN, BB_SUID_DROP))
86 //kbuild:lib-$(CONFIG_TFTP) += tftp.o
87 //kbuild:lib-$(CONFIG_TFTPD) += tftp.o
89 //usage:#define tftp_trivial_usage
90 //usage: "[OPTIONS] HOST [PORT]"
91 //usage:#define tftp_full_usage "\n\n"
92 //usage: "Transfer a file from/to tftp server\n"
93 //usage: "\n -l FILE Local FILE"
94 //usage: "\n -r FILE Remote FILE"
95 //usage: IF_FEATURE_TFTP_GET(
96 //usage: "\n -g Get file"
98 //usage: IF_FEATURE_TFTP_PUT(
99 //usage: "\n -p Put file"
101 //usage: IF_FEATURE_TFTP_BLOCKSIZE(
102 //usage: "\n -b SIZE Transfer blocks of SIZE octets"
105 //usage:#define tftpd_trivial_usage
106 //usage: "[-cr] [-u USER] [DIR]"
107 //usage:#define tftpd_full_usage "\n\n"
108 //usage: "Transfer a file on tftp client's request\n"
110 //usage: "tftpd should be used as an inetd service.\n"
111 //usage: "tftpd's line for inetd.conf:\n"
112 //usage: " 69 dgram udp nowait root tftpd tftpd -l /files/to/serve\n"
113 //usage: "It also can be ran from udpsvd:\n"
114 //usage: " udpsvd -vE 0.0.0.0 69 tftpd /files/to/serve\n"
115 //usage: "\n -r Prohibit upload"
116 //usage: "\n -c Allow file creation via upload"
117 //usage: "\n -u Access files as USER"
118 //usage: "\n -l Log to syslog (inetd mode requires this)"
121 #include "common_bufsiz.h"
124 #if ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT
126 #define TFTP_BLKSIZE_DEFAULT 512 /* according to RFC 1350, don't change */
127 #define TFTP_BLKSIZE_DEFAULT_STR "512"
128 /* Was 50 ms but users asked to bump it up a bit */
129 #define TFTP_TIMEOUT_MS 100
130 #define TFTP_MAXTIMEOUT_MS 2000
131 #define TFTP_NUM_RETRIES 12 /* number of backed-off retries */
133 /* opcodes we support */
141 /* error codes sent over network (we use only 0, 1, 3 and 8) */
142 /* generic (error message is included in the packet) */
146 /* disk full or allocation exceeded */
151 #define ERR_BAD_USER 7
152 #define ERR_BAD_OPT 8
154 /* masks coming from getopt32 */
156 TFTP_OPT_GET = (1 << 0),
157 TFTP_OPT_PUT = (1 << 1),
158 /* pseudo option: if set, it's tftpd */
159 TFTPD_OPT = (1 << 7) * ENABLE_TFTPD,
160 TFTPD_OPT_r = (1 << 8) * ENABLE_TFTPD,
161 TFTPD_OPT_c = (1 << 9) * ENABLE_TFTPD,
162 TFTPD_OPT_u = (1 << 10) * ENABLE_TFTPD,
163 TFTPD_OPT_l = (1 << 11) * ENABLE_TFTPD,
166 #if ENABLE_FEATURE_TFTP_GET && !ENABLE_FEATURE_TFTP_PUT
167 #define IF_GETPUT(...)
168 #define CMD_GET(cmd) 1
169 #define CMD_PUT(cmd) 0
170 #elif !ENABLE_FEATURE_TFTP_GET && ENABLE_FEATURE_TFTP_PUT
171 #define IF_GETPUT(...)
172 #define CMD_GET(cmd) 0
173 #define CMD_PUT(cmd) 1
175 #define IF_GETPUT(...) __VA_ARGS__
176 #define CMD_GET(cmd) ((cmd) & TFTP_OPT_GET)
177 #define CMD_PUT(cmd) ((cmd) & TFTP_OPT_PUT)
179 /* NB: in the code below
180 * CMD_GET(cmd) and CMD_PUT(cmd) are mutually exclusive
185 /* u16 TFTP_ERROR; u16 reason; both network-endian, then error text: */
186 uint8_t error_pkt[4 + 32];
188 /* Used in tftpd_main() for initial packet */
189 /* Some HP PA-RISC firmware always sends fixed 516-byte requests */
191 char block_buf_tail[1];
192 #if ENABLE_FEATURE_TFTP_PROGRESS_BAR
199 #define G (*(struct globals*)bb_common_bufsiz1)
200 #define INIT_G() do { \
201 setup_common_bufsiz(); \
202 BUILD_BUG_ON(sizeof(G) > COMMON_BUFSIZE); \
205 #define G_error_pkt_reason (G.error_pkt[3])
206 #define G_error_pkt_str ((char*)(G.error_pkt + 4))
208 #if ENABLE_FEATURE_TFTP_PROGRESS_BAR && ENABLE_FEATURE_TFTP_BLOCKSIZE
209 static void tftp_progress_update(void)
211 bb_progress_update(&G.pmt, 0, G.pos, G.size);
213 static void tftp_progress_init(void)
215 bb_progress_init(&G.pmt, G.file);
216 tftp_progress_update();
218 static void tftp_progress_done(void)
220 if (is_bb_progress_inited(&G.pmt)) {
221 tftp_progress_update();
222 bb_putchar_stderr('\n');
223 bb_progress_free(&G.pmt);
227 # define tftp_progress_update() ((void)0)
228 # define tftp_progress_init() ((void)0)
229 # define tftp_progress_done() ((void)0)
232 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
234 static int tftp_blksize_check(const char *blksize_str, int maxsize)
236 /* Check if the blksize is valid:
237 * RFC2348 says between 8 and 65464,
238 * but our implementation makes it impossible
239 * to use blksizes smaller than 22 octets. */
240 unsigned blksize = bb_strtou(blksize_str, NULL, 10);
242 || (blksize < 24) || (blksize > maxsize)
244 bb_error_msg("bad blocksize '%s'", blksize_str);
247 # if ENABLE_TFTP_DEBUG
248 bb_error_msg("using blksize %u", blksize);
253 static char *tftp_get_option(const char *option, char *buf, int len)
260 * "opt_name<NUL>opt_val<NUL>opt_name2<NUL>opt_val2<NUL>..." */
263 /* Make sure options are terminated correctly */
264 for (k = 0; k < len; k++) {
265 if (buf[k] == '\0') {
271 if (opt_val == 0) { /* it's "name" part */
272 if (strcasecmp(buf, option) == 0) {
275 } else if (opt_found) {
290 static int tftp_protocol(
291 /* NULL if tftp, !NULL if tftpd: */
292 len_and_sockaddr *our_lsa,
293 len_and_sockaddr *peer_lsa,
294 const char *local_file
295 IF_TFTP(, const char *remote_file)
297 # define remote_file NULL
299 /* 1 for tftp; 1/0 for tftpd depending whether client asked about it: */
300 IF_FEATURE_TFTP_BLOCKSIZE(, int want_transfer_size)
301 IF_FEATURE_TFTP_BLOCKSIZE(, int blksize))
303 #if !ENABLE_FEATURE_TFTP_BLOCKSIZE
304 enum { blksize = TFTP_BLKSIZE_DEFAULT };
307 struct pollfd pfd[1];
308 #define socket_fd (pfd[0].fd)
311 IF_FEATURE_TFTP_BLOCKSIZE(smallint expect_OACK = 0;)
312 smallint finished = 0;
316 int open_mode, local_fd;
317 int retries, waittime_ms;
318 int io_bufsize = blksize + 4;
320 /* Can't use RESERVE_CONFIG_BUFFER here since the allocation
321 * size varies meaning BUFFERS_GO_ON_STACK would fail.
323 * We must keep the transmit and receive buffers separate
324 * in case we rcv a garbage pkt - we need to rexmit the last pkt.
326 char *xbuf = xmalloc(io_bufsize);
327 char *rbuf = xmalloc(io_bufsize);
329 socket_fd = xsocket(peer_lsa->u.sa.sa_family, SOCK_DGRAM, 0);
330 setsockopt_reuseaddr(socket_fd);
332 if (!ENABLE_TFTP || our_lsa) { /* tftpd */
333 /* Create a socket which is:
334 * 1. bound to IP:port peer sent 1st datagram to,
335 * 2. connected to peer's IP:port
336 * This way we will answer from the IP:port peer
337 * expects, will not get any other packets on
338 * the socket, and also plain read/write will work. */
339 xbind(socket_fd, &our_lsa->u.sa, our_lsa->len);
340 xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
342 /* Is there an error already? Send pkt and bail out */
343 if (G_error_pkt_reason || G_error_pkt_str[0])
347 change_identity(G.pw); /* initgroups, setgid, setuid */
351 /* Prepare open mode */
352 if (CMD_PUT(option_mask32)) {
353 open_mode = O_RDONLY;
355 open_mode = O_WRONLY | O_TRUNC | O_CREAT;
357 if ((option_mask32 & (TFTPD_OPT+TFTPD_OPT_c)) == TFTPD_OPT) {
358 /* tftpd without -c */
359 open_mode = O_WRONLY | O_TRUNC;
364 /* Examples of network traffic.
365 * Note two cases when ACKs with block# of 0 are sent.
367 * Download without options:
368 * tftp -> "\0\1FILENAME\0octet\0"
369 * "\0\3\0\1FILEDATA..." <- tftpd
372 * Download with option of blksize 16384:
373 * tftp -> "\0\1FILENAME\0octet\0blksize\00016384\0"
374 * "\0\6blksize\00016384\0" <- tftpd
376 * "\0\3\0\1FILEDATA..." <- tftpd
379 * Upload without options:
380 * tftp -> "\0\2FILENAME\0octet\0"
381 * "\0\4\0\0" <- tftpd
382 * tftp -> "\0\3\0\1FILEDATA..."
383 * "\0\4\0\1" <- tftpd
385 * Upload with option of blksize 16384:
386 * tftp -> "\0\2FILENAME\0octet\0blksize\00016384\0"
387 * "\0\6blksize\00016384\0" <- tftpd
388 * tftp -> "\0\3\0\1FILEDATA..."
389 * "\0\4\0\1" <- tftpd
395 if (!ENABLE_TFTP || our_lsa) { /* tftpd */
396 /* Open file (must be after changing user) */
397 local_fd = open(local_file, open_mode, 0666);
399 G_error_pkt_reason = ERR_NOFILE;
400 strcpy(G_error_pkt_str, "can't open file");
403 /* gcc 4.3.1 would NOT optimize it out as it should! */
404 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
405 if (blksize != TFTP_BLKSIZE_DEFAULT || want_transfer_size) {
406 /* Create and send OACK packet. */
407 /* For the download case, block_nr is still 1 -
408 * we expect 1st ACK from peer to be for (block_nr-1),
409 * that is, for "block 0" which is our OACK pkt */
411 goto add_blksize_opt;
414 if (CMD_GET(option_mask32)) {
415 /* It's upload and we don't send OACK.
416 * We must ACK 1st packet (with filename)
417 * as if it is "block 0" */
421 /* Open file (must be after changing user) */
422 local_fd = CMD_GET(option_mask32) ? STDOUT_FILENO : STDIN_FILENO;
423 if (NOT_LONE_DASH(local_file))
424 local_fd = xopen(local_file, open_mode);
425 /* Removing #if, or using if() statement instead of #if may lead to
426 * "warning: null argument where non-null required": */
430 /* We can't (and don't really need to) bind the socket:
431 * we don't know from which local IP datagrams will be sent,
432 * but kernel will pick the same IP every time (unless routing
433 * table is changed), thus peer will see dgrams consistently
434 * coming from the same IP.
435 * We would like to connect the socket, but since peer's
436 * UDP code can be less perfect than ours, _peer's_ IP:port
437 * in replies may differ from IP:port we used to send
438 * our first packet. We can connect() only when we get
443 if (CMD_GET(option_mask32)) {
446 /* add filename and mode */
447 /* fill in packet if the filename fits into xbuf */
448 len = strlen(remote_file) + 1;
449 if (2 + len + sizeof("octet") >= io_bufsize) {
450 bb_error_msg("remote filename is too long");
453 strcpy(cp, remote_file);
455 /* add "mode" part of the packet */
457 cp += sizeof("octet");
459 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
460 if (blksize == TFTP_BLKSIZE_DEFAULT && !want_transfer_size)
463 /* Need to add option to pkt */
464 if ((&xbuf[io_bufsize - 1] - cp) < sizeof("blksize NNNNN tsize ") + sizeof(off_t)*3) {
465 bb_error_msg("remote filename is too long");
470 #endif /* ENABLE_TFTP */
472 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
474 if (blksize != TFTP_BLKSIZE_DEFAULT) {
475 /* add "blksize", <nul>, blksize, <nul> */
476 strcpy(cp, "blksize");
477 cp += sizeof("blksize");
478 cp += snprintf(cp, 6, "%d", blksize) + 1;
480 if (want_transfer_size) {
481 /* add "tsize", <nul>, size, <nul> (see RFC2349) */
482 /* if tftp and downloading, we send "0" (since we opened local_fd with O_TRUNC)
483 * and this makes server to send "tsize" option with the size */
484 /* if tftp and uploading, we send file size (maybe dont, to not confuse old servers???) */
485 /* if tftpd and downloading, we are answering to client's request */
486 /* if tftpd and uploading: !want_transfer_size, this code is not executed */
489 cp += sizeof("tsize");
491 fstat(local_fd, &st);
492 cp += sprintf(cp, "%"OFF_FMT"u", (off_t)st.st_size) + 1;
493 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
494 /* Save for progress bar. If 0 (tftp downloading),
495 * we look at server's reply later */
497 if (remote_file && st.st_size)
498 tftp_progress_init();
502 /* First packet is built, so skip packet generation */
506 /* Using mostly goto's - continue/break will be less clear
507 * in where we actually jump to */
509 /* Build ACK or DATA */
511 *((uint16_t*)cp) = htons(block_nr);
515 if (CMD_PUT(option_mask32)) {
517 len = full_read(local_fd, cp, blksize);
519 goto send_read_err_pkt;
521 if (len != blksize) {
525 IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += len;)
529 *((uint16_t*)xbuf) = htons(opcode); /* fill in opcode part */
530 send_len = cp - xbuf;
531 /* NB: send_len value is preserved in code below
532 * for potential resend */
534 retries = TFTP_NUM_RETRIES; /* re-initialize */
535 waittime_ms = TFTP_TIMEOUT_MS;
538 #if ENABLE_TFTP_DEBUG
539 fprintf(stderr, "sending %u bytes\n", send_len);
540 for (cp = xbuf; cp < &xbuf[send_len]; cp++)
541 fprintf(stderr, "%02x ", (unsigned char) *cp);
542 fprintf(stderr, "\n");
544 xsendto(socket_fd, xbuf, send_len, &peer_lsa->u.sa, peer_lsa->len);
546 #if ENABLE_FEATURE_TFTP_PROGRESS_BAR
547 if (is_bb_progress_inited(&G.pmt))
548 tftp_progress_update();
550 /* Was it final ACK? then exit */
551 if (finished && (opcode == TFTP_ACK))
556 /*pfd[0].fd = socket_fd;*/
557 pfd[0].events = POLLIN;
558 switch (safe_poll(pfd, 1, waittime_ms)) {
560 /*bb_perror_msg("poll"); - done in safe_poll */
565 tftp_progress_done();
566 bb_error_msg("timeout");
567 goto ret; /* no err packet sent */
570 /* exponential backoff with limit */
571 waittime_ms += waittime_ms/2;
572 if (waittime_ms > TFTP_MAXTIMEOUT_MS) {
573 waittime_ms = TFTP_MAXTIMEOUT_MS;
576 goto send_again; /* resend last sent pkt */
579 /* tftp (not tftpd!) receiving 1st packet */
580 our_lsa = ((void*)(ptrdiff_t)-1); /* not NULL */
581 len = recvfrom(socket_fd, rbuf, io_bufsize, 0,
582 &peer_lsa->u.sa, &peer_lsa->len);
583 /* Our first dgram went to port 69
584 * but reply may come from different one.
585 * Remember and use this new port (and IP) */
587 xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
589 /* tftpd, or not the very first packet:
590 * socket is connect()ed, can just read from it. */
591 /* Don't full_read()!
592 * This is not TCP, one read == one pkt! */
593 len = safe_read(socket_fd, rbuf, io_bufsize);
596 goto send_read_err_pkt;
598 if (len < 4) { /* too small? */
603 /* Process recv'ed packet */
604 opcode = ntohs( ((uint16_t*)rbuf)[0] );
605 recv_blk = ntohs( ((uint16_t*)rbuf)[1] );
606 #if ENABLE_TFTP_DEBUG
607 fprintf(stderr, "received %d bytes: %04x %04x\n", len, opcode, recv_blk);
609 if (opcode == TFTP_ERROR) {
610 static const char errcode_str[] ALIGN1 =
616 "unknown transfer id\0"
617 "file already exists\0"
621 const char *msg = "";
623 if (len > 4 && rbuf[4] != '\0') {
625 rbuf[io_bufsize - 1] = '\0'; /* paranoia */
626 } else if (recv_blk <= 8) {
627 msg = nth_string(errcode_str, recv_blk);
629 bb_error_msg("server error: (%u) %s", recv_blk, msg);
633 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
636 if (opcode == TFTP_OACK) {
637 /* server seems to support options */
640 res = tftp_get_option("blksize", &rbuf[2], len - 2);
642 blksize = tftp_blksize_check(res, blksize);
644 G_error_pkt_reason = ERR_BAD_OPT;
647 io_bufsize = blksize + 4;
649 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
650 if (remote_file && G.size == 0) { /* if we don't know it yet */
651 res = tftp_get_option("tsize", &rbuf[2], len - 2);
653 G.size = bb_strtoull(res, NULL, 10);
655 tftp_progress_init();
659 if (CMD_GET(option_mask32)) {
660 /* We'll send ACK for OACK,
661 * such ACK has "block no" of 0 */
667 * "An option not acknowledged by the server
668 * must be ignored by the client and server
669 * as if it were never requested." */
670 if (blksize != TFTP_BLKSIZE_DEFAULT)
671 bb_error_msg("falling back to blocksize "TFTP_BLKSIZE_DEFAULT_STR);
672 blksize = TFTP_BLKSIZE_DEFAULT;
673 io_bufsize = TFTP_BLKSIZE_DEFAULT + 4;
676 /* block_nr is already advanced to next block# we expect
677 * to get / block# we are about to send next time */
679 if (CMD_GET(option_mask32) && (opcode == TFTP_DATA)) {
680 if (recv_blk == block_nr) {
681 int sz = full_write(local_fd, &rbuf[4], len - 4);
683 strcpy(G_error_pkt_str, bb_msg_write_error);
684 G_error_pkt_reason = ERR_WRITE;
690 IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += sz;)
691 continue; /* send ACK */
693 /* Disabled to cope with servers with Sorcerer's Apprentice Syndrome */
695 if (recv_blk == (block_nr - 1)) {
696 /* Server lost our TFTP_ACK. Resend it */
703 if (CMD_PUT(option_mask32) && (opcode == TFTP_ACK)) {
704 /* did peer ACK our last DATA pkt? */
705 if (recv_blk == (uint16_t) (block_nr - 1)) {
708 continue; /* send next block */
711 /* Awww... recv'd packet is not recognized! */
713 /* why recv_again? - rfc1123 says:
714 * "The sender (i.e., the side originating the DATA packets)
715 * must never resend the current DATA packet on receipt
716 * of a duplicate ACK".
717 * DATA pkts are resent ONLY on timeout.
718 * Thus "goto send_again" will ba a bad mistake above.
720 * http://en.wikipedia.org/wiki/Sorcerer's_Apprentice_Syndrome
722 } /* end of "while (1)" */
724 if (ENABLE_FEATURE_CLEAN_UP) {
730 return finished == 0; /* returns 1 on failure */
733 strcpy(G_error_pkt_str, bb_msg_read_error);
735 if (G_error_pkt_str[0])
736 bb_error_msg("%s", G_error_pkt_str);
737 G.error_pkt[1] = TFTP_ERROR;
738 xsendto(socket_fd, G.error_pkt, 4 + 1 + strlen(G_error_pkt_str),
739 &peer_lsa->u.sa, peer_lsa->len);
746 int tftp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
747 int tftp_main(int argc UNUSED_PARAM, char **argv)
749 len_and_sockaddr *peer_lsa;
750 const char *local_file = NULL;
751 const char *remote_file = NULL;
752 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
753 const char *blksize_str = TFTP_BLKSIZE_DEFAULT_STR;
762 IF_GETPUT(opt =) getopt32(argv, "^"
763 IF_FEATURE_TFTP_GET("g") IF_FEATURE_TFTP_PUT("p")
764 "l:r:" IF_FEATURE_TFTP_BLOCKSIZE("b:")
766 /* -p or -g is mandatory, and they are mutually exclusive */
767 IF_FEATURE_TFTP_GET("g:") IF_FEATURE_TFTP_PUT("p:")
768 IF_GETPUT("g--p:p--g:"),
769 &local_file, &remote_file
770 IF_FEATURE_TFTP_BLOCKSIZE(, &blksize_str)
774 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
775 /* Check if the blksize is valid:
776 * RFC2348 says between 8 and 65464 */
777 blksize = tftp_blksize_check(blksize_str, 65564);
779 //bb_error_msg("bad block size");
786 const char *slash = strrchr(remote_file, '/');
787 local_file = slash ? slash + 1 : remote_file;
790 remote_file = local_file;
793 /* Error if filename or host is not known */
794 if (!remote_file || !argv[0])
797 port = bb_lookup_port(argv[1], "udp", 69);
798 peer_lsa = xhost2sockaddr(argv[0], port);
800 # if ENABLE_TFTP_DEBUG
801 fprintf(stderr, "using server '%s', remote_file '%s', local_file '%s'\n",
802 xmalloc_sockaddr2dotted(&peer_lsa->u.sa),
803 remote_file, local_file);
806 # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
807 G.file = remote_file;
809 result = tftp_protocol(
810 NULL /*our_lsa*/, peer_lsa,
811 local_file, remote_file
812 IF_FEATURE_TFTP_BLOCKSIZE(, 1 /* want_transfer_size */)
813 IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
815 tftp_progress_done();
817 if (result != EXIT_SUCCESS && NOT_LONE_DASH(local_file) && CMD_GET(opt)) {
823 #endif /* ENABLE_TFTP */
826 int tftpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
827 int tftpd_main(int argc UNUSED_PARAM, char **argv)
829 len_and_sockaddr *our_lsa;
830 len_and_sockaddr *peer_lsa;
831 char *mode, *user_opt;
832 char *local_file = local_file;
833 const char *error_msg;
834 int opt, result, opcode;
835 IF_FEATURE_TFTP_BLOCKSIZE(int blksize = TFTP_BLKSIZE_DEFAULT;)
836 IF_FEATURE_TFTP_BLOCKSIZE(int want_transfer_size = 0;)
840 our_lsa = get_sock_lsa(STDIN_FILENO);
842 /* This is confusing:
843 *bb_error_msg_and_die("stdin is not a socket");
846 /* Help text says that tftpd must be used as inetd service,
847 * which is by far the most usual cause of get_sock_lsa
850 peer_lsa = xzalloc(LSA_LEN_SIZE + our_lsa->len);
851 peer_lsa->len = our_lsa->len;
853 /* Shifting to not collide with TFTP_OPTs */
854 opt = option_mask32 = TFTPD_OPT | (getopt32(argv, "rcu:l", &user_opt) << 8);
856 if (opt & TFTPD_OPT_l) {
857 openlog(applet_name, LOG_PID, LOG_DAEMON);
858 logmode = LOGMODE_SYSLOG;
860 if (opt & TFTPD_OPT_u) {
861 /* Must be before xchroot */
862 G.pw = xgetpwnam(user_opt);
868 result = recv_from_to(STDIN_FILENO,
869 G.block_buf, sizeof(G.block_buf) + 1,
870 /* ^^^ sizeof+1 to reliably detect oversized input */
872 &peer_lsa->u.sa, &our_lsa->u.sa, our_lsa->len);
874 error_msg = "malformed packet";
875 opcode = ntohs(*(uint16_t*)G.block_buf);
876 if (result < 4 || result > sizeof(G.block_buf)
877 /*|| G.block_buf[result-1] != '\0' - bug compatibility, see below */
878 || (IF_FEATURE_TFTP_PUT(opcode != TFTP_RRQ) /* not download */
880 IF_FEATURE_TFTP_GET(opcode != TFTP_WRQ) /* not upload */
885 /* Some HP PA-RISC firmware always sends fixed 516-byte requests,
886 * with trailing garbage.
887 * Support that by not requiring NUL to be the last byte (see above).
888 * To make strXYZ() ops safe, force NUL termination:
890 G.block_buf_tail[0] = '\0';
892 local_file = G.block_buf + 2;
893 if (local_file[0] == '.' || strstr(local_file, "/.")) {
894 error_msg = "dot in file name";
897 mode = local_file + strlen(local_file) + 1;
898 /* RFC 1350 says mode string is case independent */
899 if (mode >= G.block_buf + result || strcasecmp(mode, "octet") != 0) {
902 # if ENABLE_FEATURE_TFTP_BLOCKSIZE
905 char *opt_str = mode + sizeof("octet");
906 int opt_len = G.block_buf + result - opt_str;
908 res = tftp_get_option("blksize", opt_str, opt_len);
910 blksize = tftp_blksize_check(res, 65564);
912 G_error_pkt_reason = ERR_BAD_OPT;
913 /* will just send error pkt */
917 if (opcode != TFTP_WRQ /* download? */
918 /* did client ask us about file size? */
919 && tftp_get_option("tsize", opt_str, opt_len)
921 want_transfer_size = 1;
927 if (!ENABLE_FEATURE_TFTP_PUT || opcode == TFTP_WRQ) {
928 if (opt & TFTPD_OPT_r) {
929 /* This would mean "disk full" - not true */
930 /*G_error_pkt_reason = ERR_WRITE;*/
931 error_msg = bb_msg_write_error;
934 IF_GETPUT(option_mask32 |= TFTP_OPT_GET;) /* will receive file's data */
936 IF_GETPUT(option_mask32 |= TFTP_OPT_PUT;) /* will send file's data */
939 /* NB: if G_error_pkt_str or G_error_pkt_reason is set up,
940 * tftp_protocol() just sends one error pkt and returns */
943 close(STDIN_FILENO); /* close old, possibly wildcard socket */
944 /* tftp_protocol() will create new one, bound to particular local IP */
945 result = tftp_protocol(
947 local_file IF_TFTP(, NULL /*remote_file*/)
948 IF_FEATURE_TFTP_BLOCKSIZE(, want_transfer_size)
949 IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
954 strcpy(G_error_pkt_str, error_msg);
958 #endif /* ENABLE_TFTPD */
960 #endif /* ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT */