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
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_BLOCKSIZE_DEFAULT 512 /* according to RFC 1350, don't change */
29 #define TFTP_TIMEOUT_MS 50
30 #define TFTP_MAXTIMEOUT_MS 2000
31 #define TFTP_NUM_RETRIES 12 /* number of backed-off retries */
33 /* opcodes we support */
41 #if ENABLE_FEATURE_TFTP_GET && !ENABLE_FEATURE_TFTP_PUT
42 #define USE_GETPUT(...)
43 #define CMD_GET(cmd) 1
44 #define CMD_PUT(cmd) 0
45 #elif !ENABLE_FEATURE_TFTP_GET && ENABLE_FEATURE_TFTP_PUT
46 #define USE_GETPUT(...)
47 #define CMD_GET(cmd) 0
48 #define CMD_PUT(cmd) 1
50 #define USE_GETPUT(...) __VA_ARGS__
51 /* masks coming from getopt32 */
52 #define CMD_GET(cmd) ((cmd) & 1)
53 #define CMD_PUT(cmd) ((cmd) & 2)
55 /* NB: in the code below
56 * CMD_GET(cmd) and CMD_PUT(cmd) are mutually exclusive
60 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
62 static int tftp_blocksize_check(int blocksize, int bufsize)
64 /* Check if the blocksize is valid:
65 * RFC2348 says between 8 and 65464,
66 * but our implementation makes it impossible
67 * to use blocksizes smaller than 22 octets.
69 if ((bufsize && (blocksize > bufsize))
70 || (blocksize < 24) || (blocksize > 65564)
72 bb_error_msg("bad blocksize");
78 static char *tftp_option_get(char *buf, int len, const char *option)
85 * "opt_name<NUL>opt_val<NUL>opt_name2<NUL>opt_val2<NUL>..." */
88 /* Make sure options are terminated correctly */
89 for (k = 0; k < len; k++) {
96 if (opt_val == 0) { /* it's "name" part */
97 if (strcasecmp(buf, option) == 0) {
100 } else if (opt_found) {
115 static int tftp_protocol(
117 len_and_sockaddr *our_lsa,
118 len_and_sockaddr *peer_lsa,
119 USE_TFTP(const char *remote_file,)
124 #define remote_file NULL
126 struct pollfd pfd[1];
127 #define socket_fd (pfd[0].fd)
130 USE_FEATURE_TFTP_BLOCKSIZE(smallint want_option_ack = 0;)
131 smallint finished = 0;
135 int retries, waittime_ms;
136 int tftp_bufsize = blocksize + 4;
138 /* Can't use RESERVE_CONFIG_BUFFER here since the allocation
139 * size varies meaning BUFFERS_GO_ON_STACK would fail */
140 /* We must keep the transmit and receive buffers seperate */
141 /* In case we rcv a garbage pkt and we need to rexmit the last pkt */
142 char *xbuf = xmalloc(tftp_bufsize);
143 char *rbuf = xmalloc(tftp_bufsize);
145 socket_fd = xsocket(peer_lsa->u.sa.sa_family, SOCK_DGRAM, 0);
146 setsockopt_reuseaddr(socket_fd);
148 if (!ENABLE_TFTP || our_lsa) {
152 /* Create a socket which is:
153 * 1. bound to IP:port peer sent 1st datagram to,
154 * 2. connected to peer's IP:port
155 * This way we will answer from the IP:port peer
156 * expects, will not get any other packets on
157 * the socket, and also plain read/write will work. */
158 xbind(socket_fd, &our_lsa->u.sa, our_lsa->len);
159 xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
161 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
162 if (blocksize != TFTP_BLOCKSIZE_DEFAULT) {
163 /* Create and send OACK packet */
166 goto add_blksize_opt;
168 /* else: just fall into while (1) loop below */
174 /* We can't (and don't really need to) bind the socket:
175 * we don't know from which local IP datagrams will be sent,
176 * but kernel will pick the same IP every time (unless routing
177 * table is changed), thus peer will see dgrams consistently
178 * coming from the same IP.
179 * We would like to connect the socket, but since peer's
180 * UDP code can be less perfect than ours, _peer's_ IP:port
181 * in replies may differ from IP:port we used to send
182 * our first packet. We can connect() only when we get
191 /* add filename and mode */
192 /* fill in packet if the filename fits into xbuf */
193 len = strlen(remote_file) + 1;
194 if (2 + len + sizeof("octet") >= tftp_bufsize) {
195 bb_error_msg("remote filename is too long");
198 strcpy(cp, remote_file);
200 /* add "mode" part of the package */
202 cp += sizeof("octet");
204 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
205 if (blocksize != TFTP_BLOCKSIZE_DEFAULT) {
206 /* rfc2348 says that 65464 is a max allowed value */
207 if ((&xbuf[tftp_bufsize - 1] - cp) < sizeof("blksize NNNNN")) {
208 bb_error_msg("remote filename is too long");
213 /* add "blksize", <nul>, blocksize, <nul> */
214 strcpy(cp, "blksize");
215 cp += sizeof("blksize");
216 cp += snprintf(cp, 6, "%d", blocksize) + 1;
219 /* First packet is built, so skip packet generation */
223 /* Using mostly goto's - continue/break will be less clear
224 * in where we actually jump to */
226 /* Build ACK or DATA */
228 *((uint16_t*)cp) = htons(block_nr);
234 len = full_read(local_fd, cp, tftp_bufsize - 4);
236 bb_perror_msg(bb_msg_read_error);
239 if (len != (tftp_bufsize - 4)) {
246 *((uint16_t*)xbuf) = htons(opcode); /* fill in opcode part */
247 send_len = cp - xbuf;
248 /* NB: send_len value is preserved in code below
249 * for potential resend */
251 retries = TFTP_NUM_RETRIES; /* re-initialize */
252 waittime_ms = TFTP_TIMEOUT_MS;
255 #if ENABLE_DEBUG_TFTP
256 fprintf(stderr, "sending %u bytes\n", send_len);
257 for (cp = xbuf; cp < &xbuf[send_len]; cp++)
258 fprintf(stderr, "%02x ", (unsigned char) *cp);
259 fprintf(stderr, "\n");
261 xsendto(socket_fd, xbuf, send_len, &peer_lsa->u.sa, peer_lsa->len);
262 /* Was it final ACK? then exit */
263 if (finished && (opcode == TFTP_ACK))
268 /*pfd[0].fd = socket_fd;*/
269 pfd[0].events = POLLIN;
270 switch (safe_poll(pfd, 1, waittime_ms)) {
273 /* tftp (not tftpd!) receiving 1st packet */
274 our_lsa = ((void*)(ptrdiff_t)-1); /* not NULL */
275 len = recvfrom(socket_fd, rbuf, tftp_bufsize, 0,
276 &peer_lsa->u.sa, &peer_lsa->len);
277 /* Our first dgram went to port 69
278 * but reply may come from different one.
279 * Remember and use this new port (and IP) */
281 xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
283 /* tftpd, or not the very first packet:
284 * socket is connect()ed, can just read from it. */
285 len = safe_read(socket_fd, rbuf, tftp_bufsize);
288 bb_perror_msg("read");
295 bb_error_msg("timeout");
299 /* exponential backoff with limit */
300 waittime_ms += waittime_ms/2;
301 if (waittime_ms > TFTP_MAXTIMEOUT_MS) {
302 waittime_ms = TFTP_MAXTIMEOUT_MS;
305 goto send_again; /* resend last sent pkt */
307 /*bb_perror_msg("poll"); - done in safe_poll */
311 /* Process recv'ed packet */
312 opcode = ntohs( ((uint16_t*)rbuf)[0] );
313 recv_blk = ntohs( ((uint16_t*)rbuf)[1] );
315 #if ENABLE_DEBUG_TFTP
316 fprintf(stderr, "received %d bytes: %04x %04x\n", len, opcode, recv_blk);
319 if (opcode == TFTP_ERROR) {
320 static const char *const errcode_str[] = {
325 "illegal TFTP operation",
326 "unknown transfer id",
327 "file already exists",
332 const char *msg = "";
334 if (rbuf[4] != '\0') {
336 rbuf[tftp_bufsize - 1] = '\0';
337 } else if (recv_blk < ARRAY_SIZE(errcode_str)) {
338 msg = errcode_str[recv_blk];
340 bb_error_msg("server error: (%u) %s", recv_blk, msg);
344 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
345 if (want_option_ack) {
348 if (opcode == TFTP_OACK) {
349 /* server seems to support options */
352 res = tftp_option_get(&rbuf[2], len - 2, "blksize");
354 int blksize = xatoi_u(res);
355 if (!tftp_blocksize_check(blksize, tftp_bufsize - 4)) {
356 /* send ERROR 8 to server... */
357 /* htons can be impossible to use in const initializer: */
358 /*static const uint16_t error_8[2] = { htons(TFTP_ERROR), htons(8) };*/
359 /* thus we open-code big-endian layout */
360 static const uint8_t error_8[4] = { 0,TFTP_ERROR, 0,8 };
361 xsendto(socket_fd, error_8, 4, &peer_lsa->u.sa, peer_lsa->len);
362 bb_error_msg("server proposes bad blksize %d, exiting", blksize);
365 #if ENABLE_DEBUG_TFTP
366 fprintf(stderr, "using blksize %u\n",
369 tftp_bufsize = blksize + 4;
370 /* Send ACK for OACK ("block" no: 0) */
375 * "An option not acknowledged by the server
376 * must be ignored by the client and server
377 * as if it were never requested." */
380 bb_error_msg("blksize is not supported by server"
381 " - reverting to 512");
382 tftp_bufsize = TFTP_BLOCKSIZE_DEFAULT + 4;
385 /* block_nr is already advanced to next block# we expect
386 * to get / block# we are about to send next time */
388 if (CMD_GET(cmd) && (opcode == TFTP_DATA)) {
389 if (recv_blk == block_nr) {
390 len = full_write(local_fd, &rbuf[4], len - 4);
392 bb_perror_msg(bb_msg_write_error);
395 if (len != (tftp_bufsize - 4)) {
398 continue; /* send ACK */
400 if (recv_blk == (block_nr - 1)) {
401 /* Server lost our TFTP_ACK. Resend it */
407 if (CMD_PUT(cmd) && (opcode == TFTP_ACK)) {
408 /* did peer ACK our last DATA pkt? */
409 if (recv_blk == (uint16_t) (block_nr - 1)) {
412 continue; /* send next block */
415 /* Awww... recv'd packet is not recognized! */
417 /* why recv_again? - rfc1123 says:
418 * "The sender (i.e., the side originating the DATA packets)
419 * must never resend the current DATA packet on receipt
420 * of a duplicate ACK".
421 * DATA pkts are resent ONLY on timeout.
422 * Thus "goto send_again" will ba a bad mistake above.
424 * http://en.wikipedia.org/wiki/Sorcerer's_Apprentice_Syndrome
426 } /* end of "while (1)" */
428 if (ENABLE_FEATURE_CLEAN_UP) {
433 return finished == 0; /* returns 1 on failure */
438 int tftp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
439 int tftp_main(int argc ATTRIBUTE_UNUSED, char **argv)
441 len_and_sockaddr *peer_lsa;
442 const char *local_file = NULL;
443 const char *remote_file = NULL;
449 int blocksize = TFTP_BLOCKSIZE_DEFAULT;
451 /* -p or -g is mandatory, and they are mutually exclusive */
452 opt_complementary = "" USE_FEATURE_TFTP_GET("g:") USE_FEATURE_TFTP_PUT("p:")
453 USE_GETPUT("g--p:p--g:")
454 USE_FEATURE_TFTP_BLOCKSIZE("b+");
456 USE_GETPUT(cmd =) getopt32(argv,
457 USE_FEATURE_TFTP_GET("g") USE_FEATURE_TFTP_PUT("p")
458 "l:r:" USE_FEATURE_TFTP_BLOCKSIZE("b:"),
459 &local_file, &remote_file
460 USE_FEATURE_TFTP_BLOCKSIZE(, &blocksize));
465 flags = O_WRONLY | O_CREAT | O_TRUNC;
467 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
468 if (!tftp_blocksize_check(blocksize, 0))
473 local_file = remote_file;
475 remote_file = local_file;
476 /* Error if filename or host is not known */
477 if (!remote_file || !argv[0])
480 local_fd = CMD_GET(cmd) ? STDOUT_FILENO : STDIN_FILENO;
481 if (!LONE_DASH(local_file)) {
482 local_fd = xopen(local_file, flags);
485 port = bb_lookup_port(argv[1], "udp", 69);
486 peer_lsa = xhost2sockaddr(argv[0], port);
488 #if ENABLE_DEBUG_TFTP
489 fprintf(stderr, "using server '%s', remote_file '%s', local_file '%s'\n",
490 xmalloc_sockaddr2dotted(&peer_lsa->u.sa),
491 remote_file, local_file);
494 result = tftp_protocol(
498 remote_file, local_fd, blocksize);
500 if (ENABLE_FEATURE_CLEAN_UP)
502 if (result != EXIT_SUCCESS && !LONE_DASH(local_file) && CMD_GET(cmd)) {
508 #endif /* ENABLE_TFTP */
512 /* TODO: libbb candidate? */
513 static len_and_sockaddr *get_sock_lsa(int s)
515 len_and_sockaddr *lsa;
518 if (getsockname(s, NULL, &len) != 0)
520 lsa = xzalloc(LSA_LEN_SIZE + len);
522 getsockname(s, &lsa->u.sa, &lsa->len);
526 int tftpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
527 int tftpd_main(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
530 char block_buf[TFTP_BLOCKSIZE_DEFAULT];
531 len_and_sockaddr *our_lsa;
532 len_and_sockaddr *peer_lsa;
533 char *filename, *mode, *opt_str;
534 int result, opcode, cmd, req_modebits, open_mode, local_fd, blksize;
536 our_lsa = get_sock_lsa(STDIN_FILENO);
538 bb_perror_msg_and_die("stdin is not a socket");
539 peer_lsa = xzalloc(LSA_LEN_SIZE + our_lsa->len);
540 peer_lsa->len = our_lsa->len;
545 result = recv_from_to(STDIN_FILENO, block_buf, sizeof(block_buf),
547 &peer_lsa->u.sa, &our_lsa->u.sa, our_lsa->len);
549 opcode = ntohs(*(uint16_t*)block_buf);
550 if (result < 4 || result >= sizeof(block_buf)
551 || block_buf[result-1] != '\0'
552 || (opcode != TFTP_RRQ && opcode != TFTP_WRQ)
554 bb_error_msg_and_die("malformed packet");
556 filename = block_buf + 2;
557 if (filename[0] == '.' || strstr(filename, "/.")) {
558 bb_error_msg_and_die("dot in filename");
560 mode = filename + strlen(filename) + 1;
561 if (mode >= block_buf + sizeof(block_buf)
562 || strcmp(mode, "octet") != 0
564 bb_error_msg_and_die("malformed packet");
566 blksize = TFTP_BLOCKSIZE_DEFAULT;
567 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
569 if (opt_str < block_buf + sizeof(block_buf)) {
570 char *res = tftp_option_get(opt_str, block_buf + sizeof(block_buf) - opt_str, "blksize");
572 int sz = xatoi_u(res);
573 if (tftp_blocksize_check(sz, 0))
578 xstat(filename, &statbuf);
579 /* if opcode == TFTP_WRQ: */
580 cmd = 1; /* CMD_GET: we will receive file's data */
581 req_modebits = 0222; /* writable by anyone */
582 open_mode = O_WRONLY | O_TRUNC;
583 if (opcode == TFTP_RRQ) {
584 cmd = 2; /* CMD_PUT */
585 req_modebits = 0444; /* readable by anyone */
586 open_mode = O_RDONLY;
588 if (!S_ISREG(statbuf.st_mode)
589 || (statbuf.st_mode & req_modebits) != req_modebits
591 bb_error_msg_and_die("access to '%s' is denied", filename);
593 local_fd = xopen(filename, open_mode);
595 close(STDIN_FILENO); /* close old, possibly wildcard socket */
596 /* tftp_protocol() will create new one, bound to particular local IP */
597 result = tftp_protocol(
600 USE_TFTP(NULL /*remote_file*/,)
608 #endif /* ENABLE_TFTPD */
610 #endif /* ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT */