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 tarball for details.
23 #if ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT
25 #define TFTP_BLKSIZE_DEFAULT 512 /* according to RFC 1350, don't change */
26 #define TFTP_BLKSIZE_DEFAULT_STR "512"
27 #define TFTP_TIMEOUT_MS 50
28 #define TFTP_MAXTIMEOUT_MS 2000
29 #define TFTP_NUM_RETRIES 12 /* number of backed-off retries */
31 /* opcodes we support */
39 /* error codes sent over network (we use only 0, 1, 3 and 8) */
40 /* generic (error message is included in the packet) */
44 /* disk full or allocation exceeded */
49 #define ERR_BAD_USER 7
52 /* masks coming from getopt32 */
54 TFTP_OPT_GET = (1 << 0),
55 TFTP_OPT_PUT = (1 << 1),
56 /* pseudo option: if set, it's tftpd */
57 TFTPD_OPT = (1 << 7) * ENABLE_TFTPD,
58 TFTPD_OPT_r = (1 << 8) * ENABLE_TFTPD,
59 TFTPD_OPT_c = (1 << 9) * ENABLE_TFTPD,
60 TFTPD_OPT_u = (1 << 10) * ENABLE_TFTPD,
63 #if ENABLE_FEATURE_TFTP_GET && !ENABLE_FEATURE_TFTP_PUT
64 #define IF_GETPUT(...)
65 #define CMD_GET(cmd) 1
66 #define CMD_PUT(cmd) 0
67 #elif !ENABLE_FEATURE_TFTP_GET && ENABLE_FEATURE_TFTP_PUT
68 #define IF_GETPUT(...)
69 #define CMD_GET(cmd) 0
70 #define CMD_PUT(cmd) 1
72 #define IF_GETPUT(...) __VA_ARGS__
73 #define CMD_GET(cmd) ((cmd) & TFTP_OPT_GET)
74 #define CMD_PUT(cmd) ((cmd) & TFTP_OPT_PUT)
76 /* NB: in the code below
77 * CMD_GET(cmd) and CMD_PUT(cmd) are mutually exclusive
82 /* u16 TFTP_ERROR; u16 reason; both network-endian, then error text: */
83 uint8_t error_pkt[4 + 32];
85 /* used in tftpd_main(), a bit big for stack: */
86 char block_buf[TFTP_BLKSIZE_DEFAULT];
88 #define G (*(struct globals*)&bb_common_bufsiz1)
89 #define block_buf (G.block_buf )
90 #define user_opt (G.user_opt )
91 #define error_pkt (G.error_pkt )
92 #define INIT_G() do { } while (0)
94 #define error_pkt_reason (error_pkt[3])
95 #define error_pkt_str (error_pkt + 4)
98 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
100 static int tftp_blksize_check(const char *blksize_str, int maxsize)
102 /* Check if the blksize is valid:
103 * RFC2348 says between 8 and 65464,
104 * but our implementation makes it impossible
105 * to use blksizes smaller than 22 octets. */
106 unsigned blksize = bb_strtou(blksize_str, NULL, 10);
108 || (blksize < 24) || (blksize > maxsize)
110 bb_error_msg("bad blocksize '%s'", blksize_str);
113 #if ENABLE_TFTP_DEBUG
114 bb_error_msg("using blksize %u", blksize);
119 static char *tftp_get_option(const char *option, char *buf, int len)
126 * "opt_name<NUL>opt_val<NUL>opt_name2<NUL>opt_val2<NUL>..." */
129 /* Make sure options are terminated correctly */
130 for (k = 0; k < len; k++) {
131 if (buf[k] == '\0') {
137 if (opt_val == 0) { /* it's "name" part */
138 if (strcasecmp(buf, option) == 0) {
141 } else if (opt_found) {
156 static int tftp_protocol(
157 len_and_sockaddr *our_lsa, /* NULL if tftp, !NULL if tftpd */
158 len_and_sockaddr *peer_lsa,
159 const char *local_file
160 IF_TFTP(, const char *remote_file)
161 IF_FEATURE_TFTP_BLOCKSIZE(IF_TFTPD(, void *tsize))
162 IF_FEATURE_TFTP_BLOCKSIZE(, int blksize))
165 # define remote_file NULL
167 #if !(ENABLE_FEATURE_TFTP_BLOCKSIZE && ENABLE_TFTPD)
170 #if !ENABLE_FEATURE_TFTP_BLOCKSIZE
171 enum { blksize = TFTP_BLKSIZE_DEFAULT };
174 struct pollfd pfd[1];
175 #define socket_fd (pfd[0].fd)
178 IF_FEATURE_TFTP_BLOCKSIZE(smallint expect_OACK = 0;)
179 smallint finished = 0;
183 int open_mode, local_fd;
184 int retries, waittime_ms;
185 int io_bufsize = blksize + 4;
187 /* Can't use RESERVE_CONFIG_BUFFER here since the allocation
188 * size varies meaning BUFFERS_GO_ON_STACK would fail.
190 * We must keep the transmit and receive buffers separate
191 * in case we rcv a garbage pkt - we need to rexmit the last pkt.
193 char *xbuf = xmalloc(io_bufsize);
194 char *rbuf = xmalloc(io_bufsize);
196 socket_fd = xsocket(peer_lsa->u.sa.sa_family, SOCK_DGRAM, 0);
197 setsockopt_reuseaddr(socket_fd);
199 if (!ENABLE_TFTP || our_lsa) { /* tftpd */
200 /* Create a socket which is:
201 * 1. bound to IP:port peer sent 1st datagram to,
202 * 2. connected to peer's IP:port
203 * This way we will answer from the IP:port peer
204 * expects, will not get any other packets on
205 * the socket, and also plain read/write will work. */
206 xbind(socket_fd, &our_lsa->u.sa, our_lsa->len);
207 xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
209 /* Is there an error already? Send pkt and bail out */
210 if (error_pkt_reason || error_pkt_str[0])
214 struct passwd *pw = xgetpwnam(user_opt);
215 change_identity(pw); /* initgroups, setgid, setuid */
219 /* Prepare open mode */
220 if (CMD_PUT(option_mask32)) {
221 open_mode = O_RDONLY;
223 open_mode = O_WRONLY | O_TRUNC | O_CREAT;
225 if ((option_mask32 & (TFTPD_OPT+TFTPD_OPT_c)) == TFTPD_OPT) {
226 /* tftpd without -c */
227 open_mode = O_WRONLY | O_TRUNC;
232 /* Examples of network traffic.
233 * Note two cases when ACKs with block# of 0 are sent.
235 * Download without options:
236 * tftp -> "\0\1FILENAME\0octet\0"
237 * "\0\3\0\1FILEDATA..." <- tftpd
240 * Download with option of blksize 16384:
241 * tftp -> "\0\1FILENAME\0octet\0blksize\00016384\0"
242 * "\0\6blksize\00016384\0" <- tftpd
244 * "\0\3\0\1FILEDATA..." <- tftpd
247 * Upload without options:
248 * tftp -> "\0\2FILENAME\0octet\0"
249 * "\0\4\0\0" <- tftpd
250 * tftp -> "\0\3\0\1FILEDATA..."
251 * "\0\4\0\1" <- tftpd
253 * Upload with option of blksize 16384:
254 * tftp -> "\0\2FILENAME\0octet\0blksize\00016384\0"
255 * "\0\6blksize\00016384\0" <- tftpd
256 * tftp -> "\0\3\0\1FILEDATA..."
257 * "\0\4\0\1" <- tftpd
263 if (!ENABLE_TFTP || our_lsa) { /* tftpd */
264 /* Open file (must be after changing user) */
265 local_fd = open(local_file, open_mode);
267 error_pkt_reason = ERR_NOFILE;
268 strcpy((char*)error_pkt_str, "can't open file");
271 /* gcc 4.3.1 would NOT optimize it out as it should! */
272 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
273 if (blksize != TFTP_BLKSIZE_DEFAULT || tsize) {
274 /* Create and send OACK packet. */
275 /* For the download case, block_nr is still 1 -
276 * we expect 1st ACK from peer to be for (block_nr-1),
277 * that is, for "block 0" which is our OACK pkt */
279 goto add_blksize_opt;
282 if (CMD_GET(option_mask32)) {
283 /* It's upload and we don't send OACK.
284 * We must ACK 1st packet (with filename)
285 * as if it is "block 0" */
290 /* Open file (must be after changing user) */
291 local_fd = CMD_GET(option_mask32) ? STDOUT_FILENO : STDIN_FILENO;
292 if (NOT_LONE_DASH(local_file))
293 local_fd = xopen(local_file, open_mode);
294 /* Removing #if, or using if() statement instead of #if may lead to
295 * "warning: null argument where non-null required": */
299 /* We can't (and don't really need to) bind the socket:
300 * we don't know from which local IP datagrams will be sent,
301 * but kernel will pick the same IP every time (unless routing
302 * table is changed), thus peer will see dgrams consistently
303 * coming from the same IP.
304 * We would like to connect the socket, but since peer's
305 * UDP code can be less perfect than ours, _peer's_ IP:port
306 * in replies may differ from IP:port we used to send
307 * our first packet. We can connect() only when we get
312 if (CMD_GET(option_mask32)) {
315 /* add filename and mode */
316 /* fill in packet if the filename fits into xbuf */
317 len = strlen(remote_file) + 1;
318 if (2 + len + sizeof("octet") >= io_bufsize) {
319 bb_error_msg("remote filename is too long");
322 strcpy(cp, remote_file);
324 /* add "mode" part of the package */
326 cp += sizeof("octet");
328 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
329 if (blksize == TFTP_BLKSIZE_DEFAULT)
332 /* Non-standard blocksize: add option to pkt */
333 if ((&xbuf[io_bufsize - 1] - cp) < sizeof("blksize NNNNN")) {
334 bb_error_msg("remote filename is too long");
339 #endif /* ENABLE_TFTP */
341 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
346 /* add "tsize", <nul>, size, <nul> */
348 cp += sizeof("tsize");
349 fstat(local_fd, &st);
350 cp += snprintf(cp, 10, "%u", (int) st.st_size) + 1;
353 if (blksize != TFTP_BLKSIZE_DEFAULT) {
354 /* add "blksize", <nul>, blksize, <nul> */
355 strcpy(cp, "blksize");
356 cp += sizeof("blksize");
357 cp += snprintf(cp, 6, "%d", blksize) + 1;
360 /* First packet is built, so skip packet generation */
364 /* Using mostly goto's - continue/break will be less clear
365 * in where we actually jump to */
367 /* Build ACK or DATA */
369 *((uint16_t*)cp) = htons(block_nr);
373 if (CMD_PUT(option_mask32)) {
375 len = full_read(local_fd, cp, blksize);
377 goto send_read_err_pkt;
379 if (len != blksize) {
386 *((uint16_t*)xbuf) = htons(opcode); /* fill in opcode part */
387 send_len = cp - xbuf;
388 /* NB: send_len value is preserved in code below
389 * for potential resend */
391 retries = TFTP_NUM_RETRIES; /* re-initialize */
392 waittime_ms = TFTP_TIMEOUT_MS;
395 #if ENABLE_TFTP_DEBUG
396 fprintf(stderr, "sending %u bytes\n", send_len);
397 for (cp = xbuf; cp < &xbuf[send_len]; cp++)
398 fprintf(stderr, "%02x ", (unsigned char) *cp);
399 fprintf(stderr, "\n");
401 xsendto(socket_fd, xbuf, send_len, &peer_lsa->u.sa, peer_lsa->len);
402 /* Was it final ACK? then exit */
403 if (finished && (opcode == TFTP_ACK))
408 /*pfd[0].fd = socket_fd;*/
409 pfd[0].events = POLLIN;
410 switch (safe_poll(pfd, 1, waittime_ms)) {
412 /*bb_perror_msg("poll"); - done in safe_poll */
417 bb_error_msg("timeout");
418 goto ret; /* no err packet sent */
421 /* exponential backoff with limit */
422 waittime_ms += waittime_ms/2;
423 if (waittime_ms > TFTP_MAXTIMEOUT_MS) {
424 waittime_ms = TFTP_MAXTIMEOUT_MS;
427 goto send_again; /* resend last sent pkt */
430 /* tftp (not tftpd!) receiving 1st packet */
431 our_lsa = ((void*)(ptrdiff_t)-1); /* not NULL */
432 len = recvfrom(socket_fd, rbuf, io_bufsize, 0,
433 &peer_lsa->u.sa, &peer_lsa->len);
434 /* Our first dgram went to port 69
435 * but reply may come from different one.
436 * Remember and use this new port (and IP) */
438 xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
440 /* tftpd, or not the very first packet:
441 * socket is connect()ed, can just read from it. */
442 /* Don't full_read()!
443 * This is not TCP, one read == one pkt! */
444 len = safe_read(socket_fd, rbuf, io_bufsize);
447 goto send_read_err_pkt;
449 if (len < 4) { /* too small? */
454 /* Process recv'ed packet */
455 opcode = ntohs( ((uint16_t*)rbuf)[0] );
456 recv_blk = ntohs( ((uint16_t*)rbuf)[1] );
457 #if ENABLE_TFTP_DEBUG
458 fprintf(stderr, "received %d bytes: %04x %04x\n", len, opcode, recv_blk);
460 if (opcode == TFTP_ERROR) {
461 static const char errcode_str[] ALIGN1 =
467 "unknown transfer id\0"
468 "file already exists\0"
472 const char *msg = "";
474 if (len > 4 && rbuf[4] != '\0') {
476 rbuf[io_bufsize - 1] = '\0'; /* paranoia */
477 } else if (recv_blk <= 8) {
478 msg = nth_string(errcode_str, recv_blk);
480 bb_error_msg("server error: (%u) %s", recv_blk, msg);
484 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
487 if (opcode == TFTP_OACK) {
488 /* server seems to support options */
491 res = tftp_get_option("blksize", &rbuf[2], len - 2);
493 blksize = tftp_blksize_check(res, blksize);
495 error_pkt_reason = ERR_BAD_OPT;
498 io_bufsize = blksize + 4;
500 if (CMD_GET(option_mask32)) {
501 /* We'll send ACK for OACK,
502 * such ACK has "block no" of 0 */
508 * "An option not acknowledged by the server
509 * must be ignored by the client and server
510 * as if it were never requested." */
511 bb_error_msg("server only supports blocksize of 512");
512 blksize = TFTP_BLKSIZE_DEFAULT;
513 io_bufsize = TFTP_BLKSIZE_DEFAULT + 4;
516 /* block_nr is already advanced to next block# we expect
517 * to get / block# we are about to send next time */
519 if (CMD_GET(option_mask32) && (opcode == TFTP_DATA)) {
520 if (recv_blk == block_nr) {
521 int sz = full_write(local_fd, &rbuf[4], len - 4);
523 strcpy((char*)error_pkt_str, bb_msg_write_error);
524 error_pkt_reason = ERR_WRITE;
530 continue; /* send ACK */
532 /* Disabled to cope with servers with Sorcerer's Apprentice Syndrome */
534 if (recv_blk == (block_nr - 1)) {
535 /* Server lost our TFTP_ACK. Resend it */
542 if (CMD_PUT(option_mask32) && (opcode == TFTP_ACK)) {
543 /* did peer ACK our last DATA pkt? */
544 if (recv_blk == (uint16_t) (block_nr - 1)) {
547 continue; /* send next block */
550 /* Awww... recv'd packet is not recognized! */
552 /* why recv_again? - rfc1123 says:
553 * "The sender (i.e., the side originating the DATA packets)
554 * must never resend the current DATA packet on receipt
555 * of a duplicate ACK".
556 * DATA pkts are resent ONLY on timeout.
557 * Thus "goto send_again" will ba a bad mistake above.
559 * http://en.wikipedia.org/wiki/Sorcerer's_Apprentice_Syndrome
561 } /* end of "while (1)" */
563 if (ENABLE_FEATURE_CLEAN_UP) {
569 return finished == 0; /* returns 1 on failure */
572 strcpy((char*)error_pkt_str, bb_msg_read_error);
574 if (error_pkt_str[0])
575 bb_error_msg((char*)error_pkt_str);
576 error_pkt[1] = TFTP_ERROR;
577 xsendto(socket_fd, error_pkt, 4 + 1 + strlen((char*)error_pkt_str),
578 &peer_lsa->u.sa, peer_lsa->len);
586 int tftp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
587 int tftp_main(int argc UNUSED_PARAM, char **argv)
589 len_and_sockaddr *peer_lsa;
590 const char *local_file = NULL;
591 const char *remote_file = NULL;
592 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
593 const char *blksize_str = TFTP_BLKSIZE_DEFAULT_STR;
602 /* -p or -g is mandatory, and they are mutually exclusive */
603 opt_complementary = "" IF_FEATURE_TFTP_GET("g:") IF_FEATURE_TFTP_PUT("p:")
604 IF_GETPUT("g--p:p--g:");
606 IF_GETPUT(opt =) getopt32(argv,
607 IF_FEATURE_TFTP_GET("g") IF_FEATURE_TFTP_PUT("p")
608 "l:r:" IF_FEATURE_TFTP_BLOCKSIZE("b:"),
609 &local_file, &remote_file
610 IF_FEATURE_TFTP_BLOCKSIZE(, &blksize_str));
613 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
614 /* Check if the blksize is valid:
615 * RFC2348 says between 8 and 65464 */
616 blksize = tftp_blksize_check(blksize_str, 65564);
618 //bb_error_msg("bad block size");
625 const char *slash = strrchr(remote_file, '/');
626 local_file = slash ? slash + 1 : remote_file;
629 remote_file = local_file;
632 /* Error if filename or host is not known */
633 if (!remote_file || !argv[0])
636 port = bb_lookup_port(argv[1], "udp", 69);
637 peer_lsa = xhost2sockaddr(argv[0], port);
639 #if ENABLE_TFTP_DEBUG
640 fprintf(stderr, "using server '%s', remote_file '%s', local_file '%s'\n",
641 xmalloc_sockaddr2dotted(&peer_lsa->u.sa),
642 remote_file, local_file);
645 result = tftp_protocol(
646 NULL /*our_lsa*/, peer_lsa,
647 local_file, remote_file
648 IF_FEATURE_TFTP_BLOCKSIZE(IF_TFTPD(, NULL /*tsize*/))
649 IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
652 if (result != EXIT_SUCCESS && NOT_LONE_DASH(local_file) && CMD_GET(opt)) {
658 #endif /* ENABLE_TFTP */
661 int tftpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
662 int tftpd_main(int argc UNUSED_PARAM, char **argv)
664 len_and_sockaddr *our_lsa;
665 len_and_sockaddr *peer_lsa;
666 char *local_file, *mode;
667 const char *error_msg;
668 int opt, result, opcode;
669 IF_FEATURE_TFTP_BLOCKSIZE(int blksize = TFTP_BLKSIZE_DEFAULT;)
670 IF_FEATURE_TFTP_BLOCKSIZE(char *tsize = NULL;)
674 our_lsa = get_sock_lsa(STDIN_FILENO);
676 /* This is confusing:
677 *bb_error_msg_and_die("stdin is not a socket");
680 /* Help text says that tftpd must be used as inetd service,
681 * which is by far the most usual cause of get_sock_lsa
684 peer_lsa = xzalloc(LSA_LEN_SIZE + our_lsa->len);
685 peer_lsa->len = our_lsa->len;
687 /* Shifting to not collide with TFTP_OPTs */
688 opt = option_mask32 = TFTPD_OPT | (getopt32(argv, "rcu:", &user_opt) << 8);
693 result = recv_from_to(STDIN_FILENO, block_buf, sizeof(block_buf),
695 &peer_lsa->u.sa, &our_lsa->u.sa, our_lsa->len);
697 error_msg = "malformed packet";
698 opcode = ntohs(*(uint16_t*)block_buf);
699 if (result < 4 || result >= sizeof(block_buf)
700 || block_buf[result-1] != '\0'
701 || (IF_FEATURE_TFTP_PUT(opcode != TFTP_RRQ) /* not download */
703 IF_FEATURE_TFTP_GET(opcode != TFTP_WRQ) /* not upload */
708 local_file = block_buf + 2;
709 if (local_file[0] == '.' || strstr(local_file, "/.")) {
710 error_msg = "dot in file name";
713 mode = local_file + strlen(local_file) + 1;
714 if (mode >= block_buf + result || strcmp(mode, "octet") != 0) {
717 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
720 char *opt_str = mode + sizeof("octet");
721 int opt_len = block_buf + result - opt_str;
723 res = tftp_get_option("blksize", opt_str, opt_len);
725 blksize = tftp_blksize_check(res, 65564);
727 error_pkt_reason = ERR_BAD_OPT;
728 /* will just send error pkt */
732 /* did client ask us about file size? */
733 tsize = tftp_get_option("tsize", opt_str, opt_len);
738 if (!ENABLE_FEATURE_TFTP_PUT || opcode == TFTP_WRQ) {
739 if (opt & TFTPD_OPT_r) {
740 /* This would mean "disk full" - not true */
741 /*error_pkt_reason = ERR_WRITE;*/
742 error_msg = bb_msg_write_error;
745 IF_GETPUT(option_mask32 |= TFTP_OPT_GET;) /* will receive file's data */
747 IF_GETPUT(option_mask32 |= TFTP_OPT_PUT;) /* will send file's data */
750 /* NB: if error_pkt_str or error_pkt_reason is set up,
751 * tftp_protocol() just sends one error pkt and returns */
754 close(STDIN_FILENO); /* close old, possibly wildcard socket */
755 /* tftp_protocol() will create new one, bound to particular local IP */
756 result = tftp_protocol(
758 local_file IF_TFTP(, NULL /*remote_file*/)
759 IF_FEATURE_TFTP_BLOCKSIZE(, tsize)
760 IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
765 strcpy((char*)error_pkt_str, error_msg);
769 #endif /* ENABLE_TFTPD */
771 #endif /* ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT */