1 /* vi: set sw=4 ts=4: */
2 /* -------------------------------------------------------------------------
5 * A simple tftp client/server for busybox.
6 * Tries to follow RFC1350.
7 * Only "octet" mode supported.
8 * Optional blocksize negotiation (RFC2347 + RFC2348)
10 * Copyright (C) 2001 Magnus Damm <damm@opensource.se>
12 * Parts of the code based on:
14 * atftp: Copyright (C) 2000 Jean-Pierre Lefebvre <helix@step.polymtl.ca>
15 * and Remi Lefebvre <remi@debian.org>
17 * utftp: Copyright (C) 1999 Uwe Ohse <uwe@ohse.de>
19 * tftpd added by Denys Vlasenko & Vladimir Dronnikov
21 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
22 * ------------------------------------------------------------------------- */
26 #if ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT
28 #define TFTP_BLKSIZE_DEFAULT 512 /* according to RFC 1350, don't change */
29 #define TFTP_BLKSIZE_DEFAULT_STR "512"
30 #define TFTP_TIMEOUT_MS 50
31 #define TFTP_MAXTIMEOUT_MS 2000
32 #define TFTP_NUM_RETRIES 12 /* number of backed-off retries */
34 /* opcodes we support */
42 /* error codes sent over network (we use only 0, 3 and 8) */
43 /* generic (error message is included in the packet) */
47 /* disk full or allocation exceeded */
52 #define ERR_BAD_USER 7
55 /* masks coming from getopt32 */
57 TFTP_OPT_GET = (1 << 0),
58 TFTP_OPT_PUT = (1 << 1),
59 /* pseudo option: if set, it's tftpd */
60 TFTPD_OPT = (1 << 7) * ENABLE_TFTPD,
61 TFTPD_OPT_r = (1 << 8) * ENABLE_TFTPD,
62 TFTPD_OPT_c = (1 << 9) * ENABLE_TFTPD,
63 TFTPD_OPT_u = (1 << 10) * ENABLE_TFTPD,
66 #if ENABLE_FEATURE_TFTP_GET && !ENABLE_FEATURE_TFTP_PUT
67 #define USE_GETPUT(...)
68 #define CMD_GET(cmd) 1
69 #define CMD_PUT(cmd) 0
70 #elif !ENABLE_FEATURE_TFTP_GET && ENABLE_FEATURE_TFTP_PUT
71 #define USE_GETPUT(...)
72 #define CMD_GET(cmd) 0
73 #define CMD_PUT(cmd) 1
75 #define USE_GETPUT(...) __VA_ARGS__
76 #define CMD_GET(cmd) ((cmd) & TFTP_OPT_GET)
77 #define CMD_PUT(cmd) ((cmd) & TFTP_OPT_PUT)
79 /* NB: in the code below
80 * CMD_GET(cmd) and CMD_PUT(cmd) are mutually exclusive
85 /* u16 TFTP_ERROR; u16 reason; both network-endian, then error text: */
86 uint8_t error_pkt[4 + 32];
88 /* used in tftpd_main(), a bit big for stack: */
89 char block_buf[TFTP_BLKSIZE_DEFAULT];
91 #define G (*(struct globals*)&bb_common_bufsiz1)
92 #define block_buf (G.block_buf )
93 #define user_opt (G.user_opt )
94 #define error_pkt (G.error_pkt )
99 #define error_pkt_reason (error_pkt[3])
100 #define error_pkt_str (error_pkt + 4)
103 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
105 static int tftp_blksize_check(const char *blksize_str, int maxsize)
107 /* Check if the blksize is valid:
108 * RFC2348 says between 8 and 65464,
109 * but our implementation makes it impossible
110 * to use blksizes smaller than 22 octets. */
111 unsigned blksize = bb_strtou(blksize_str, NULL, 10);
113 || (blksize < 24) || (blksize > maxsize)
115 bb_error_msg("bad blocksize '%s'", blksize_str);
118 #if ENABLE_DEBUG_TFTP
119 bb_error_msg("using blksize %u", blksize);
124 static char *tftp_get_blksize(char *buf, int len)
126 #define option "blksize"
132 * "opt_name<NUL>opt_val<NUL>opt_name2<NUL>opt_val2<NUL>..." */
135 /* Make sure options are terminated correctly */
136 for (k = 0; k < len; k++) {
137 if (buf[k] == '\0') {
143 if (opt_val == 0) { /* it's "name" part */
144 if (strcasecmp(buf, option) == 0) {
147 } else if (opt_found) {
163 static int tftp_protocol(
164 len_and_sockaddr *our_lsa,
165 len_and_sockaddr *peer_lsa,
166 const char *local_file,
167 USE_TFTP(const char *remote_file,)
171 #define remote_file NULL
173 struct pollfd pfd[1];
174 #define socket_fd (pfd[0].fd)
177 USE_FEATURE_TFTP_BLOCKSIZE(smallint want_option_ack = 0;)
178 smallint finished = 0;
182 int open_mode, local_fd;
183 int retries, waittime_ms;
184 int io_bufsize = blksize + 4;
186 /* Can't use RESERVE_CONFIG_BUFFER here since the allocation
187 * size varies meaning BUFFERS_GO_ON_STACK would fail */
188 /* We must keep the transmit and receive buffers seperate */
189 /* In case we rcv a garbage pkt and we need to rexmit the last pkt */
190 char *xbuf = xmalloc(io_bufsize);
191 char *rbuf = xmalloc(io_bufsize);
193 socket_fd = xsocket(peer_lsa->u.sa.sa_family, SOCK_DGRAM, 0);
194 setsockopt_reuseaddr(socket_fd);
199 if (!ENABLE_TFTP || our_lsa) {
202 /* Create a socket which is:
203 * 1. bound to IP:port peer sent 1st datagram to,
204 * 2. connected to peer's IP:port
205 * This way we will answer from the IP:port peer
206 * expects, will not get any other packets on
207 * the socket, and also plain read/write will work. */
208 xbind(socket_fd, &our_lsa->u.sa, our_lsa->len);
209 xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
211 /* Is there an error already? Send pkt and bail out */
212 if (error_pkt_reason || error_pkt_str[0])
215 if (CMD_GET(option_mask32)) {
216 /* it's upload - we must ACK 1st packet (with filename)
217 * as if it's "block 0" */
222 struct passwd *pw = getpwnam(user_opt);
224 bb_error_msg_and_die("unknown user '%s'", user_opt);
225 change_identity(pw); /* initgroups, setgid, setuid */
229 /* Open local file (must be after changing user) */
230 if (CMD_PUT(option_mask32)) {
231 open_mode = O_RDONLY;
233 open_mode = O_WRONLY | O_TRUNC | O_CREAT;
235 if ((option_mask32 & (TFTPD_OPT+TFTPD_OPT_c)) == TFTPD_OPT) {
236 /* tftpd without -c */
237 open_mode = O_WRONLY | O_TRUNC;
241 if (!(option_mask32 & TFTPD_OPT)) {
242 local_fd = CMD_GET(option_mask32) ? STDOUT_FILENO : STDIN_FILENO;
243 if (NOT_LONE_DASH(local_file))
244 local_fd = xopen(local_file, open_mode);
246 local_fd = open_or_warn(local_file, open_mode);
248 /*error_pkt_reason = ERR_NOFILE/ERR_ACCESS?*/
249 strcpy(error_pkt_str, "can't open file");
254 if (!ENABLE_TFTP || our_lsa) {
255 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
256 if (blksize != TFTP_BLKSIZE_DEFAULT) {
257 /* Create and send OACK packet. */
258 /* For the download case, block_nr is still 1 -
259 * we expect 1st ACK from peer to be for (block_nr-1),
260 * that is, for "block 0" which is our OACK pkt */
262 goto add_blksize_opt;
267 /* Removing it, or using if() statement instead may lead to
268 * "warning: null argument where non-null required": */
272 /* We can't (and don't really need to) bind the socket:
273 * we don't know from which local IP datagrams will be sent,
274 * but kernel will pick the same IP every time (unless routing
275 * table is changed), thus peer will see dgrams consistently
276 * coming from the same IP.
277 * We would like to connect the socket, but since peer's
278 * UDP code can be less perfect than ours, _peer's_ IP:port
279 * in replies may differ from IP:port we used to send
280 * our first packet. We can connect() only when we get
285 if (CMD_GET(option_mask32)) {
288 /* add filename and mode */
289 /* fill in packet if the filename fits into xbuf */
290 len = strlen(remote_file) + 1;
291 if (2 + len + sizeof("octet") >= io_bufsize) {
292 bb_error_msg("remote filename is too long");
295 strcpy(cp, remote_file);
297 /* add "mode" part of the package */
299 cp += sizeof("octet");
301 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
302 if (blksize == TFTP_BLKSIZE_DEFAULT)
305 /* Non-standard blocksize: add option to pkt */
306 if ((&xbuf[io_bufsize - 1] - cp) < sizeof("blksize NNNNN")) {
307 bb_error_msg("remote filename is too long");
312 #endif /* ENABLE_TFTP */
314 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
316 /* add "blksize", <nul>, blksize, <nul> */
317 strcpy(cp, "blksize");
318 cp += sizeof("blksize");
319 cp += snprintf(cp, 6, "%d", blksize) + 1;
321 /* First packet is built, so skip packet generation */
325 /* Using mostly goto's - continue/break will be less clear
326 * in where we actually jump to */
328 /* Build ACK or DATA */
330 *((uint16_t*)cp) = htons(block_nr);
334 if (CMD_PUT(option_mask32)) {
336 len = full_read(local_fd, cp, blksize);
338 goto send_read_err_pkt;
340 if (len != blksize) {
347 *((uint16_t*)xbuf) = htons(opcode); /* fill in opcode part */
348 send_len = cp - xbuf;
349 /* NB: send_len value is preserved in code below
350 * for potential resend */
352 retries = TFTP_NUM_RETRIES; /* re-initialize */
353 waittime_ms = TFTP_TIMEOUT_MS;
356 #if ENABLE_DEBUG_TFTP
357 fprintf(stderr, "sending %u bytes\n", send_len);
358 for (cp = xbuf; cp < &xbuf[send_len]; cp++)
359 fprintf(stderr, "%02x ", (unsigned char) *cp);
360 fprintf(stderr, "\n");
362 xsendto(socket_fd, xbuf, send_len, &peer_lsa->u.sa, peer_lsa->len);
363 /* Was it final ACK? then exit */
364 if (finished && (opcode == TFTP_ACK))
369 /*pfd[0].fd = socket_fd;*/
370 pfd[0].events = POLLIN;
371 switch (safe_poll(pfd, 1, waittime_ms)) {
373 /*bb_perror_msg("poll"); - done in safe_poll */
378 bb_error_msg("timeout");
379 goto ret; /* no err packet sent */
382 /* exponential backoff with limit */
383 waittime_ms += waittime_ms/2;
384 if (waittime_ms > TFTP_MAXTIMEOUT_MS) {
385 waittime_ms = TFTP_MAXTIMEOUT_MS;
388 goto send_again; /* resend last sent pkt */
391 /* tftp (not tftpd!) receiving 1st packet */
392 our_lsa = ((void*)(ptrdiff_t)-1); /* not NULL */
393 len = recvfrom(socket_fd, rbuf, io_bufsize, 0,
394 &peer_lsa->u.sa, &peer_lsa->len);
395 /* Our first dgram went to port 69
396 * but reply may come from different one.
397 * Remember and use this new port (and IP) */
399 xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
401 /* tftpd, or not the very first packet:
402 * socket is connect()ed, can just read from it. */
403 /* Don't full_read()!
404 * This is not TCP, one read == one pkt! */
405 len = safe_read(socket_fd, rbuf, io_bufsize);
408 goto send_read_err_pkt;
410 if (len < 4) { /* too small? */
415 /* Process recv'ed packet */
416 opcode = ntohs( ((uint16_t*)rbuf)[0] );
417 recv_blk = ntohs( ((uint16_t*)rbuf)[1] );
418 #if ENABLE_DEBUG_TFTP
419 fprintf(stderr, "received %d bytes: %04x %04x\n", len, opcode, recv_blk);
422 if (opcode == TFTP_ERROR) {
423 static const char errcode_str[] =
429 "unknown transfer id\0"
430 "file already exists\0"
434 const char *msg = "";
436 if (len > 4 && rbuf[4] != '\0') {
438 rbuf[io_bufsize - 1] = '\0'; /* paranoia */
439 } else if (recv_blk <= 8) {
440 msg = nth_string(errcode_str, recv_blk);
442 bb_error_msg("server error: (%u) %s", recv_blk, msg);
446 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
447 if (want_option_ack) {
449 if (opcode == TFTP_OACK) {
450 /* server seems to support options */
453 res = tftp_get_blksize(&rbuf[2], len - 2);
455 blksize = tftp_blksize_check(res, blksize);
457 error_pkt_reason = ERR_BAD_OPT;
460 io_bufsize = blksize + 4;
461 /* Send ACK for OACK ("block" no: 0) */
466 * "An option not acknowledged by the server
467 * must be ignored by the client and server
468 * as if it were never requested." */
470 bb_error_msg("server only supports blocksize of 512");
471 blksize = TFTP_BLKSIZE_DEFAULT;
472 io_bufsize = TFTP_BLKSIZE_DEFAULT + 4;
475 /* block_nr is already advanced to next block# we expect
476 * to get / block# we are about to send next time */
478 if (CMD_GET(option_mask32) && (opcode == TFTP_DATA)) {
479 if (recv_blk == block_nr) {
480 int sz = full_write(local_fd, &rbuf[4], len - 4);
482 strcpy(error_pkt_str, bb_msg_write_error);
483 error_pkt_reason = ERR_WRITE;
489 continue; /* send ACK */
491 if (recv_blk == (block_nr - 1)) {
492 /* Server lost our TFTP_ACK. Resend it */
498 if (CMD_PUT(option_mask32) && (opcode == TFTP_ACK)) {
499 /* did peer ACK our last DATA pkt? */
500 if (recv_blk == (uint16_t) (block_nr - 1)) {
503 continue; /* send next block */
506 /* Awww... recv'd packet is not recognized! */
508 /* why recv_again? - rfc1123 says:
509 * "The sender (i.e., the side originating the DATA packets)
510 * must never resend the current DATA packet on receipt
511 * of a duplicate ACK".
512 * DATA pkts are resent ONLY on timeout.
513 * Thus "goto send_again" will ba a bad mistake above.
515 * http://en.wikipedia.org/wiki/Sorcerer's_Apprentice_Syndrome
517 } /* end of "while (1)" */
519 if (ENABLE_FEATURE_CLEAN_UP) {
525 return finished == 0; /* returns 1 on failure */
528 strcpy(error_pkt_str, bb_msg_read_error);
530 if (error_pkt_str[0])
531 bb_error_msg(error_pkt_str);
532 error_pkt[1] = TFTP_ERROR;
533 xsendto(socket_fd, error_pkt, 4 + 1 + strlen(error_pkt_str),
534 &peer_lsa->u.sa, peer_lsa->len);
540 int tftp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
541 int tftp_main(int argc ATTRIBUTE_UNUSED, char **argv)
543 len_and_sockaddr *peer_lsa;
544 const char *local_file = NULL;
545 const char *remote_file = NULL;
546 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
547 const char *blksize_str = TFTP_BLKSIZE_DEFAULT_STR;
556 /* -p or -g is mandatory, and they are mutually exclusive */
557 opt_complementary = "" USE_FEATURE_TFTP_GET("g:") USE_FEATURE_TFTP_PUT("p:")
558 USE_GETPUT("g--p:p--g:");
560 USE_GETPUT(opt =) getopt32(argv,
561 USE_FEATURE_TFTP_GET("g") USE_FEATURE_TFTP_PUT("p")
562 "l:r:" USE_FEATURE_TFTP_BLOCKSIZE("b:"),
563 &local_file, &remote_file
564 USE_FEATURE_TFTP_BLOCKSIZE(, &blksize_str));
567 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
568 /* Check if the blksize is valid:
569 * RFC2348 says between 8 and 65464 */
570 blksize = tftp_blksize_check(blksize_str, 65564);
572 //bb_error_msg("bad block size");
576 blksize = TFTP_BLKSIZE_DEFAULT;
580 local_file = remote_file;
582 remote_file = local_file;
583 /* Error if filename or host is not known */
584 if (!remote_file || !argv[0])
587 port = bb_lookup_port(argv[1], "udp", 69);
588 peer_lsa = xhost2sockaddr(argv[0], port);
590 #if ENABLE_DEBUG_TFTP
591 fprintf(stderr, "using server '%s', remote_file '%s', local_file '%s'\n",
592 xmalloc_sockaddr2dotted(&peer_lsa->u.sa),
593 remote_file, local_file);
596 result = tftp_protocol(
597 NULL /* our_lsa*/, peer_lsa,
598 local_file, remote_file,
601 if (result != EXIT_SUCCESS && NOT_LONE_DASH(local_file) && CMD_GET(opt)) {
607 #endif /* ENABLE_TFTP */
611 /* TODO: libbb candidate? */
612 static len_and_sockaddr *get_sock_lsa(int s)
614 len_and_sockaddr *lsa;
617 if (getsockname(s, NULL, &len) != 0)
619 lsa = xzalloc(LSA_LEN_SIZE + len);
621 getsockname(s, &lsa->u.sa, &lsa->len);
625 int tftpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
626 int tftpd_main(int argc ATTRIBUTE_UNUSED, char **argv)
628 len_and_sockaddr *our_lsa;
629 len_and_sockaddr *peer_lsa;
630 char *local_file, *mode;
631 const char *error_msg;
632 int opt, result, opcode;
633 int blksize = TFTP_BLKSIZE_DEFAULT;
637 our_lsa = get_sock_lsa(STDIN_FILENO);
639 bb_perror_msg_and_die("stdin is not a socket");
640 peer_lsa = xzalloc(LSA_LEN_SIZE + our_lsa->len);
641 peer_lsa->len = our_lsa->len;
643 /* Shifting to not collide with TFTP_OPTs */
644 opt = option_mask32 = TFTPD_OPT | (getopt32(argv, "rcu:", &user_opt) << 8);
649 result = recv_from_to(STDIN_FILENO, block_buf, sizeof(block_buf),
651 &peer_lsa->u.sa, &our_lsa->u.sa, our_lsa->len);
653 error_msg = "malformed packet";
654 opcode = ntohs(*(uint16_t*)block_buf);
655 if (result < 4 || result >= sizeof(block_buf)
656 || block_buf[result-1] != '\0'
657 || (USE_FEATURE_TFTP_PUT(opcode != TFTP_RRQ) /* not download */
659 USE_FEATURE_TFTP_GET(opcode != TFTP_WRQ) /* not upload */
664 local_file = block_buf + 2;
665 if (local_file[0] == '.' || strstr(local_file, "/.")) {
666 error_msg = "dot in file name";
669 mode = local_file + strlen(local_file) + 1;
670 if (mode >= block_buf + result || strcmp(mode, "octet") != 0) {
673 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
676 char *opt_str = mode + sizeof("octet");
677 int opt_len = block_buf + result - opt_str;
679 res = tftp_get_blksize(opt_str, opt_len);
681 blksize = tftp_blksize_check(res, 65564);
683 error_pkt_reason = ERR_BAD_OPT;
684 /* will just send error pkt */
692 if (!ENABLE_FEATURE_TFTP_PUT || opcode == TFTP_WRQ) {
693 if (opt & TFTPD_OPT_r) {
694 /* This would mean "disk full" - not true */
695 /*error_pkt_reason = ERR_WRITE;*/
696 error_msg = bb_msg_write_error;
699 USE_GETPUT(option_mask32 |= TFTP_OPT_GET;) /* will receive file's data */
701 USE_GETPUT(option_mask32 |= TFTP_OPT_PUT;) /* will send file's data */
704 close(STDIN_FILENO); /* close old, possibly wildcard socket */
705 /* tftp_protocol() will create new one, bound to particular local IP */
707 /* NB: if error_pkt_str or error_pkt_reason is set up,
708 * tftp_protocol() just sends one error pkt and returns */
710 result = tftp_protocol(
712 local_file, USE_TFTP(NULL /*remote_file*/,)
718 strcpy(error_pkt_str, error_msg);
722 #endif /* ENABLE_TFTPD */
724 #endif /* ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT */