*: move get_sock_lsa and xwrite_str to libbb, use where appropriate
[oweals/busybox.git] / networking / tftp.c
index 5fac48769a37e183aa0b8e09437e0d5445024378..fa0851615b6a7658ec2056c58534f6ca6d563207 100644 (file)
 
 #if ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT
 
-#define TFTP_BLKSIZE_DEFAULT   512      /* according to RFC 1350, don't change */
-#define TFTP_TIMEOUT_MS         50
-#define TFTP_MAXTIMEOUT_MS    2000
-#define TFTP_NUM_RETRIES        12      /* number of backed-off retries */
+#define TFTP_BLKSIZE_DEFAULT       512  /* according to RFC 1350, don't change */
+#define TFTP_BLKSIZE_DEFAULT_STR "512"
+#define TFTP_TIMEOUT_MS             50
+#define TFTP_MAXTIMEOUT_MS        2000
+#define TFTP_NUM_RETRIES            12  /* number of backed-off retries */
 
 /* opcodes we support */
 #define TFTP_RRQ   1
@@ -38,7 +39,7 @@
 #define TFTP_ERROR 5
 #define TFTP_OACK  6
 
-/* error codes sent over network (we use only 0, 3 and 8) */
+/* error codes sent over network (we use only 0, 1, 3 and 8) */
 /* generic (error message is included in the packet) */
 #define ERR_UNSPEC   0
 #define ERR_NOFILE   1
@@ -83,9 +84,7 @@ enum {
 struct globals {
        /* u16 TFTP_ERROR; u16 reason; both network-endian, then error text: */
        uint8_t error_pkt[4 + 32];
-#if ENABLE_TFTPD
        char *user_opt;
-#endif
        /* used in tftpd_main(), a bit big for stack: */
        char block_buf[TFTP_BLKSIZE_DEFAULT];
 };
@@ -93,9 +92,7 @@ struct globals {
 #define block_buf        (G.block_buf   )
 #define user_opt         (G.user_opt    )
 #define error_pkt        (G.error_pkt   )
-#define INIT_G() \
-       do { \
-       } while (0)
+#define INIT_G() do { } while (0)
 
 #define error_pkt_reason (error_pkt[3])
 #define error_pkt_str    (error_pkt + 4)
@@ -116,15 +113,14 @@ static int tftp_blksize_check(const char *blksize_str, int maxsize)
                bb_error_msg("bad blocksize '%s'", blksize_str);
                return -1;
        }
-#if ENABLE_DEBUG_TFTP
+#if ENABLE_TFTP_DEBUG
        bb_error_msg("using blksize %u", blksize);
 #endif
        return blksize;
 }
 
-static char *tftp_get_blksize(char *buf, int len)
+static char *tftp_get_option(const char *option, char *buf, int len)
 {
-#define option "blksize"
        int opt_val = 0;
        int opt_found = 0;
        int k;
@@ -156,7 +152,6 @@ static char *tftp_get_blksize(char *buf, int len)
        }
 
        return NULL;
-#undef option
 }
 
 #endif
@@ -164,13 +159,21 @@ static char *tftp_get_blksize(char *buf, int len)
 static int tftp_protocol(
                len_and_sockaddr *our_lsa,
                len_and_sockaddr *peer_lsa,
-               const char *local_file,
-               USE_TFTP(const char *remote_file,)
-               int blksize)
+               const char *local_file
+               USE_TFTP(, const char *remote_file)
+               USE_FEATURE_TFTP_BLOCKSIZE(USE_TFTPD(, void *tsize))
+               USE_FEATURE_TFTP_BLOCKSIZE(, int blksize))
 {
 #if !ENABLE_TFTP
 #define remote_file NULL
 #endif
+#if !(ENABLE_FEATURE_TFTP_BLOCKSIZE && ENABLE_TFTPD)
+#define tsize NULL
+#endif
+#if !ENABLE_FEATURE_TFTP_BLOCKSIZE
+       enum { blksize = TFTP_BLKSIZE_DEFAULT };
+#endif
+
        struct pollfd pfd[1];
 #define socket_fd (pfd[0].fd)
        int len;
@@ -194,15 +197,38 @@ static int tftp_protocol(
        socket_fd = xsocket(peer_lsa->u.sa.sa_family, SOCK_DGRAM, 0);
        setsockopt_reuseaddr(socket_fd);
 
-#if ENABLE_TFTPD
-       if (user_opt) {
-               struct passwd *pw = getpwnam(user_opt); /* initgroups, setgid, setuid */
-               if (!pw)
-                       bb_error_msg_and_die("unknown user '%s'", user_opt);
-               change_identity(pw);
+       block_nr = 1;
+       cp = xbuf + 2;
+
+       if (!ENABLE_TFTP || our_lsa) {
+               /* tftpd */
+
+               /* Create a socket which is:
+                * 1. bound to IP:port peer sent 1st datagram to,
+                * 2. connected to peer's IP:port
+                * This way we will answer from the IP:port peer
+                * expects, will not get any other packets on
+                * the socket, and also plain read/write will work. */
+               xbind(socket_fd, &our_lsa->u.sa, our_lsa->len);
+               xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
+
+               /* Is there an error already? Send pkt and bail out */
+               if (error_pkt_reason || error_pkt_str[0])
+                       goto send_err_pkt;
+
+               if (CMD_GET(option_mask32)) {
+                       /* it's upload - we must ACK 1st packet (with filename)
+                        * as if it's "block 0" */
+                       block_nr = 0;
+               }
+
+               if (user_opt) {
+                       struct passwd *pw = xgetpwnam(user_opt);
+                       change_identity(pw); /* initgroups, setgid, setuid */
+               }
        }
-#endif
 
+       /* Open local file (must be after changing user) */
        if (CMD_PUT(option_mask32)) {
                open_mode = O_RDONLY;
        } else {
@@ -219,50 +245,30 @@ static int tftp_protocol(
                if (NOT_LONE_DASH(local_file))
                        local_fd = xopen(local_file, open_mode);
        } else {
-               local_fd = open_or_warn(local_file, open_mode);
+               local_fd = open(local_file, open_mode);
                if (local_fd < 0) {
-                       /*error_pkt_reason = ERR_NOFILE/ERR_ACCESS?*/
-                       strcpy(error_pkt_str, "can't open file");
+                       error_pkt_reason = ERR_NOFILE;
+                       strcpy((char*)error_pkt_str, "can't open file");
                        goto send_err_pkt;
                }
        }
 
-       block_nr = 1;
        if (!ENABLE_TFTP || our_lsa) {
-               /* tftpd */
-
-               /* Create a socket which is:
-                * 1. bound to IP:port peer sent 1st datagram to,
-                * 2. connected to peer's IP:port
-                * This way we will answer from the IP:port peer
-                * expects, will not get any other packets on
-                * the socket, and also plain read/write will work. */
-               xbind(socket_fd, &our_lsa->u.sa, our_lsa->len);
-               xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
-
-               /* Is there an error already? Send pkt and bail out */
-               if (error_pkt_reason || error_pkt_str[0])
-                       goto send_err_pkt;
-
-               if (CMD_GET(option_mask32)) {
-                       /* it's upload - we must ACK 1st packet (with filename)
-                        * as if it's "block 0" */
-                       block_nr = 0;
-               }
-
+/* gcc 4.3.1 would NOT optimize it out as it should! */
 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
-               if (blksize != TFTP_BLKSIZE_DEFAULT) {
-                       /* Create and send OACK packet */
+               if (blksize != TFTP_BLKSIZE_DEFAULT || tsize) {
+                       /* Create and send OACK packet. */
                        /* For the download case, block_nr is still 1 -
                         * we expect 1st ACK from peer to be for (block_nr-1),
                         * that is, for "block 0" which is our OACK pkt */
                        opcode = TFTP_OACK;
-                       cp = xbuf + 2;
                        goto add_blksize_opt;
                }
-               /* else: just fall into while (1) loop below */
 #endif
        } else {
+/* Removing it, or using if() statement instead of #if may lead to
+ * "warning: null argument where non-null required": */
+#if ENABLE_TFTP
                /* tftp */
 
                /* We can't (and don't really need to) bind the socket:
@@ -281,7 +287,6 @@ static int tftp_protocol(
                if (CMD_GET(option_mask32)) {
                        opcode = TFTP_RRQ;
                }
-               cp = xbuf + 2;
                /* add filename and mode */
                /* fill in packet if the filename fits into xbuf */
                len = strlen(remote_file) + 1;
@@ -296,14 +301,31 @@ static int tftp_protocol(
                cp += sizeof("octet");
 
 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
-               if (blksize != TFTP_BLKSIZE_DEFAULT) {
-                       /* rfc2348 says that 65464 is a max allowed value */
-                       if ((&xbuf[io_bufsize - 1] - cp) < sizeof("blksize NNNNN")) {
-                               bb_error_msg("remote filename is too long");
-                               goto ret;
-                       }
-                       want_option_ack = 1;
+               if (blksize == TFTP_BLKSIZE_DEFAULT)
+                       goto send_pkt;
+
+               /* Non-standard blocksize: add option to pkt */
+               if ((&xbuf[io_bufsize - 1] - cp) < sizeof("blksize NNNNN")) {
+                       bb_error_msg("remote filename is too long");
+                       goto ret;
+               }
+               want_option_ack = 1;
+#endif
+#endif /* ENABLE_TFTP */
+
+#if ENABLE_FEATURE_TFTP_BLOCKSIZE
  add_blksize_opt:
+#if ENABLE_TFTPD
+               if (tsize) {
+                       struct stat st;
+                       /* add "tsize", <nul>, size, <nul> */
+                       strcpy(cp, "tsize");
+                       cp += sizeof("tsize");
+                       fstat(local_fd, &st);
+                       cp += snprintf(cp, 10, "%u", (int) st.st_size) + 1;
+               }
+#endif
+               if (blksize != TFTP_BLKSIZE_DEFAULT) {
                        /* add "blksize", <nul>, blksize, <nul> */
                        strcpy(cp, "blksize");
                        cp += sizeof("blksize");
@@ -345,7 +367,7 @@ static int tftp_protocol(
                waittime_ms = TFTP_TIMEOUT_MS;
 
  send_again:
-#if ENABLE_DEBUG_TFTP
+#if ENABLE_TFTP_DEBUG
                fprintf(stderr, "sending %u bytes\n", send_len);
                for (cp = xbuf; cp < &xbuf[send_len]; cp++)
                        fprintf(stderr, "%02x ", (unsigned char) *cp);
@@ -407,12 +429,11 @@ static int tftp_protocol(
                /* Process recv'ed packet */
                opcode = ntohs( ((uint16_t*)rbuf)[0] );
                recv_blk = ntohs( ((uint16_t*)rbuf)[1] );
-#if ENABLE_DEBUG_TFTP
+#if ENABLE_TFTP_DEBUG
                fprintf(stderr, "received %d bytes: %04x %04x\n", len, opcode, recv_blk);
 #endif
-
                if (opcode == TFTP_ERROR) {
-                       static const char errcode_str[] =
+                       static const char errcode_str[] ALIGN1 =
                                "\0"
                                "file not found\0"
                                "access violation\0"
@@ -442,7 +463,7 @@ static int tftp_protocol(
                                /* server seems to support options */
                                char *res;
 
-                               res = tftp_get_blksize(&rbuf[2], len - 2);
+                               res = tftp_get_option("blksize", &rbuf[2], len - 2);
                                if (res) {
                                        blksize = tftp_blksize_check(res, blksize);
                                        if (blksize < 0) {
@@ -471,7 +492,7 @@ static int tftp_protocol(
                        if (recv_blk == block_nr) {
                                int sz = full_write(local_fd, &rbuf[4], len - 4);
                                if (sz != len - 4) {
-                                       strcpy(error_pkt_str, bb_msg_write_error);
+                                       strcpy((char*)error_pkt_str, bb_msg_write_error);
                                        error_pkt_reason = ERR_WRITE;
                                        goto send_err_pkt;
                                }
@@ -517,26 +538,30 @@ static int tftp_protocol(
        return finished == 0; /* returns 1 on failure */
 
  send_read_err_pkt:
-       strcpy(error_pkt_str, bb_msg_read_error);
+       strcpy((char*)error_pkt_str, bb_msg_read_error);
  send_err_pkt:
        if (error_pkt_str[0])
-               bb_error_msg(error_pkt_str);
+               bb_error_msg((char*)error_pkt_str);
        error_pkt[1] = TFTP_ERROR;
-       xsendto(socket_fd, error_pkt, 4 + 1 + strlen(error_pkt_str),
+       xsendto(socket_fd, error_pkt, 4 + 1 + strlen((char*)error_pkt_str),
                        &peer_lsa->u.sa, peer_lsa->len);
        return EXIT_FAILURE;
+#undef remote_file
+#undef tsize
 }
 
 #if ENABLE_TFTP
 
 int tftp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
-int tftp_main(int argc ATTRIBUTE_UNUSED, char **argv)
+int tftp_main(int argc UNUSED_PARAM, char **argv)
 {
        len_and_sockaddr *peer_lsa;
        const char *local_file = NULL;
        const char *remote_file = NULL;
-       const char *blksize_str = "512";
+#if ENABLE_FEATURE_TFTP_BLOCKSIZE
+       const char *blksize_str = TFTP_BLKSIZE_DEFAULT_STR;
        int blksize;
+#endif
        int result;
        int port;
        USE_GETPUT(int opt;)
@@ -575,16 +600,18 @@ int tftp_main(int argc ATTRIBUTE_UNUSED, char **argv)
        port = bb_lookup_port(argv[1], "udp", 69);
        peer_lsa = xhost2sockaddr(argv[0], port);
 
-#if ENABLE_DEBUG_TFTP
+#if ENABLE_TFTP_DEBUG
        fprintf(stderr, "using server '%s', remote_file '%s', local_file '%s'\n",
                        xmalloc_sockaddr2dotted(&peer_lsa->u.sa),
                        remote_file, local_file);
 #endif
 
        result = tftp_protocol(
-                       NULL /* our_lsa*/, peer_lsa,
-                       local_file, remote_file,
-                       blksize);
+               NULL /*our_lsa*/, peer_lsa,
+               local_file, remote_file
+               USE_FEATURE_TFTP_BLOCKSIZE(USE_TFTPD(, NULL /*tsize*/))
+               USE_FEATURE_TFTP_BLOCKSIZE(, blksize)
+       );
 
        if (result != EXIT_SUCCESS && NOT_LONE_DASH(local_file) && CMD_GET(opt)) {
                unlink(local_file);
@@ -595,38 +622,29 @@ int tftp_main(int argc ATTRIBUTE_UNUSED, char **argv)
 #endif /* ENABLE_TFTP */
 
 #if ENABLE_TFTPD
-
-/* TODO: libbb candidate? */
-static len_and_sockaddr *get_sock_lsa(int s)
-{
-       len_and_sockaddr *lsa;
-       socklen_t len = 0;
-
-       if (getsockname(s, NULL, &len) != 0)
-               return NULL;
-       lsa = xzalloc(LSA_LEN_SIZE + len);
-       lsa->len = len;
-       getsockname(s, &lsa->u.sa, &lsa->len);
-       return lsa;
-}
-
 int tftpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
-int tftpd_main(int argc ATTRIBUTE_UNUSED, char **argv)
+int tftpd_main(int argc UNUSED_PARAM, char **argv)
 {
        len_and_sockaddr *our_lsa;
        len_and_sockaddr *peer_lsa;
        char *local_file, *mode;
        const char *error_msg;
        int opt, result, opcode;
-       int local_fd = local_fd; /* for compiler */
-       int blksize = blksize;
-       USE_GETPUT(int cmd = cmd;)
+       USE_FEATURE_TFTP_BLOCKSIZE(int blksize = TFTP_BLKSIZE_DEFAULT;)
+       USE_FEATURE_TFTP_BLOCKSIZE(char *tsize = NULL;)
 
        INIT_G();
 
        our_lsa = get_sock_lsa(STDIN_FILENO);
-       if (!our_lsa)
-               bb_perror_msg_and_die("stdin is not a socket");
+       if (!our_lsa) {
+               /* This is confusing:
+                *bb_error_msg_and_die("stdin is not a socket");
+                * Better: */
+               bb_show_usage();
+               /* Help text says that tftpd must be used as inetd service,
+                * which is by far the most usual cause of get_sock_lsa
+                * failure */
+       }
        peer_lsa = xzalloc(LSA_LEN_SIZE + our_lsa->len);
        peer_lsa->len = our_lsa->len;
 
@@ -644,7 +662,7 @@ int tftpd_main(int argc ATTRIBUTE_UNUSED, char **argv)
        opcode = ntohs(*(uint16_t*)block_buf);
        if (result < 4 || result >= sizeof(block_buf)
         || block_buf[result-1] != '\0'
-        || (USE_FEATURE_TFTP_GET(opcode != TFTP_RRQ) /* not download */
+        || (USE_FEATURE_TFTP_PUT(opcode != TFTP_RRQ) /* not download */
             USE_GETPUT(&&)
             USE_FEATURE_TFTP_GET(opcode != TFTP_WRQ) /* not upload */
            )
@@ -653,21 +671,20 @@ int tftpd_main(int argc ATTRIBUTE_UNUSED, char **argv)
        }
        local_file = block_buf + 2;
        if (local_file[0] == '.' || strstr(local_file, "/.")) {
-               error_msg = "dot in local_file";
+               error_msg = "dot in file name";
                goto err;
        }
        mode = local_file + strlen(local_file) + 1;
        if (mode >= block_buf + result || strcmp(mode, "octet") != 0) {
                goto err;
        }
-       blksize = TFTP_BLKSIZE_DEFAULT;
 #if ENABLE_FEATURE_TFTP_BLOCKSIZE
        {
                char *res;
                char *opt_str = mode + sizeof("octet");
                int opt_len = block_buf + result - opt_str;
                if (opt_len > 0) {
-                       res = tftp_get_blksize(opt_str, opt_len);
+                       res = tftp_get_option("blksize", opt_str, opt_len);
                        if (res) {
                                blksize = tftp_blksize_check(res, 65564);
                                if (blksize < 0) {
@@ -676,6 +693,8 @@ int tftpd_main(int argc ATTRIBUTE_UNUSED, char **argv)
                                        goto do_proto;
                                }
                        }
+                       /* did client ask us about file size? */
+                       tsize = tftp_get_option("tsize", opt_str, opt_len);
                }
        }
 #endif
@@ -692,21 +711,22 @@ int tftpd_main(int argc ATTRIBUTE_UNUSED, char **argv)
                USE_GETPUT(option_mask32 |= TFTP_OPT_PUT;) /* will send file's data */
        }
 
-       close(STDIN_FILENO); /* close old, possibly wildcard socket */
-       /* tftp_protocol() will create new one, bound to particular local IP */
-
        /* NB: if error_pkt_str or error_pkt_reason is set up,
         * tftp_protocol() just sends one error pkt and returns */
+
  do_proto:
+       close(STDIN_FILENO); /* close old, possibly wildcard socket */
+       /* tftp_protocol() will create new one, bound to particular local IP */
        result = tftp_protocol(
                our_lsa, peer_lsa,
-               local_file, USE_TFTP(NULL /*remote_file*/,)
-               blksize
+               local_file USE_TFTP(, NULL /*remote_file*/)
+               USE_FEATURE_TFTP_BLOCKSIZE(, tsize)
+               USE_FEATURE_TFTP_BLOCKSIZE(, blksize)
        );
 
        return result;
  err:
-       strcpy(error_pkt_str, error_msg);
+       strcpy((char*)error_pkt_str, error_msg);
        goto do_proto;
 }