bb_applet_name -> applet_name
[oweals/busybox.git] / networking / wget.c
index 1a80972fc20b74723d419a9cbd59338cf11b9ce4..0054a9876094b3e738a3bc7fec8fd663e1bd529c 100644 (file)
@@ -6,9 +6,28 @@
  *
  */
 
-#include "busybox.h"
-#include <getopt.h>
+/* We want libc to give us xxx64 functions also */
+/* http://www.unix.org/version2/whatsnew/lfs20mar.html */
+#define _LARGEFILE64_SOURCE 1
 
+#include "busybox.h"
+#include <getopt.h>    /* for struct option */
+
+#ifdef CONFIG_LFS
+# define FILEOFF_TYPE off64_t
+# define FILEOFF_FMT "%lld"
+# define LSEEK lseek64
+# define STRTOOFF strtoll
+# define SAFE_STRTOOFF safe_strtoll
+/* stat64 etc as needed...  */
+#else
+# define FILEOFF_TYPE off_t
+# define FILEOFF_FMT "%ld"
+# define LSEEK lseek
+# define STRTOOFF strtol
+# define SAFE_STRTOOFF safe_strtol
+/* Do we need to undefine O_LARGEFILE? */
+#endif
 
 struct host_info {
        char *host;
@@ -24,29 +43,21 @@ static char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc);
 static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf);
 
 /* Globals (can be accessed from signal handlers */
-static off_t filesize;         /* content-length of the file */
-static int chunked;            /* chunked transfer encoding */
+static FILEOFF_TYPE content_len;        /* Content-length of the file */
+static FILEOFF_TYPE beg_range;          /* Range at which continue begins */
+static FILEOFF_TYPE transferred;        /* Number of bytes transferred so far */
+static int chunked;                     /* chunked transfer encoding */
 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
 static void progressmeter(int flag);
-static char *curfile;          /* Name of current file being transferred. */
-static struct timeval start;   /* Time a transfer started. */
-static off_t transferred;      /* Number of bytes transferred so far. */
-/* For progressmeter() -- number of seconds before xfer considered "stalled" */
+static char *curfile;                   /* Name of current file being transferred */
+static struct timeval start;            /* Time a transfer started */
 enum {
-       STALLTIME = 5
+       STALLTIME = 5                   /* Seconds when xfer considered "stalled" */
 };
 #else
 static void progressmeter(int flag) {}
 #endif
 
-static void close_and_delete_outfile(FILE* output, char *fname_out, int do_continue)
-{
-       if (output != stdout && do_continue == 0) {
-               fclose(output);
-               unlink(fname_out);
-       }
-}
-
 /* Read NMEMB elements of SIZE bytes into PTR from STREAM.  Returns the
  * number of elements read, and a short count if an eof or non-interrupt
  * error is encountered.  */
@@ -62,21 +73,6 @@ static size_t safe_fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
        return ret;
 }
 
-/* Write NMEMB elements of SIZE bytes from PTR to STREAM.  Returns the
- * number of elements written, and a short count if an eof or non-interrupt
- * error is encountered.  */
-static size_t safe_fwrite(void *ptr, size_t size, size_t nmemb, FILE *stream)
-{
-       size_t ret = 0;
-
-       do {
-               clearerr(stream);
-               ret += fwrite((char *)ptr + (ret * size), size, nmemb - ret, stream);
-       } while (ret < nmemb && ferror(stream) && errno == EINTR);
-
-       return ret;
-}
-
 /* Read a line or SIZE - 1 bytes into S, whichever is less, from STREAM.
  * Returns S, or NULL if an eof or non-interrupt error is encountered.  */
 static char *safe_fgets(char *s, int size, FILE *stream)
@@ -91,11 +87,6 @@ static char *safe_fgets(char *s, int size, FILE *stream)
        return ret;
 }
 
-#define close_delete_and_die(s...) { \
-       close_and_delete_outfile(output, fname_out, do_continue); \
-       bb_error_msg_and_die(s); }
-
-
 #ifdef CONFIG_FEATURE_WGET_AUTHENTICATION
 /*
  *  Base64-encode character string and return the string.
@@ -107,20 +98,20 @@ static char *base64enc(unsigned char *p, char *buf, int len)
 }
 #endif
 
-#define WGET_OPT_CONTINUE      1
-#define WGET_OPT_QUIET 2
-#define WGET_OPT_PASSIVE       4
-#define WGET_OPT_OUTNAME       8
-#define WGET_OPT_HEADER        16
-#define WGET_OPT_PREFIX        32
-#define WGET_OPT_PROXY 64
-#define WGET_OPT_USER_AGENT    128
+#define WGET_OPT_CONTINUE     1
+#define WGET_OPT_QUIET        2
+#define WGET_OPT_PASSIVE      4
+#define WGET_OPT_OUTNAME      8
+#define WGET_OPT_HEADER      16
+#define WGET_OPT_PREFIX      32
+#define WGET_OPT_PROXY       64
+#define WGET_OPT_USER_AGENT 128
 
 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
 static const struct option wget_long_options[] = {
        { "continue",        0, NULL, 'c' },
        { "quiet",           0, NULL, 'q' },
-       { "passive-ftp",     0, NULL, 139 },
+       { "passive-ftp",     0, NULL, 139 }, /* FIXME: what is this - 139?? */
        { "output-document", 1, NULL, 'O' },
        { "header",          1, NULL, 131 },
        { "directory-prefix",1, NULL, 'P' },
@@ -133,12 +124,11 @@ static const struct option wget_long_options[] = {
 int wget_main(int argc, char **argv)
 {
        int n, try=5, status;
-       unsigned long opt;
+       unsigned opt;
        int port;
        char *proxy = 0;
        char *dir_prefix=NULL;
        char *s, buf[512];
-       struct stat sbuf;
        char extra_headers[1024];
        char *extra_headers_ptr = extra_headers;
        int extra_headers_left = sizeof(extra_headers);
@@ -146,34 +136,25 @@ int wget_main(int argc, char **argv)
        struct sockaddr_in s_in;
        llist_t *headers_llist = NULL;
 
-       FILE *sfp = NULL;               /* socket to web/ftp server         */
-       FILE *dfp = NULL;               /* socket to ftp server (data)      */
-       char *fname_out = NULL;         /* where to direct output (-O)      */
-       int do_continue = 0;            /* continue a prev transfer (-c)    */
-       long beg_range = 0L;            /*   range at which continue begins */
-       int got_clen = 0;               /* got content-length: from server  */
-       FILE *output;                   /* socket to web server             */
-       int quiet_flag = FALSE;         /* Be verry, verry quiet...         */
-       int use_proxy = 1;              /* Use proxies if env vars are set  */
-       char *proxy_flag = "on";        /* Use proxies if env vars are set  */
-       char *user_agent = "Wget"; /* Content of the "User-Agent" header field */
+       FILE *sfp = NULL;               /* socket to web/ftp server         */
+       FILE *dfp = NULL;               /* socket to ftp server (data)      */
+       char *fname_out = NULL;         /* where to direct output (-O)      */
+       int got_clen = 0;               /* got content-length: from server  */
+       int output_fd = -1;
+       int use_proxy = 1;              /* Use proxies if env vars are set  */
+       char *proxy_flag = "on";        /* Use proxies if env vars are set  */
+       char *user_agent = "Wget";      /* Content of the "User-Agent" header field */
 
        /*
         * Crack command line.
         */
-       bb_opt_complementally = "-1:\203::";
+       opt_complementary = "-1:\203::";
 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
-       bb_applet_long_options = wget_long_options;
+       applet_long_options = wget_long_options;
 #endif
-       opt = bb_getopt_ulflags(argc, argv, "cq\213O:\203:P:Y:U:",
+       opt = getopt32(argc, argv, "cq\213O:\203:P:Y:U:",
                                        &fname_out, &headers_llist,
                                        &dir_prefix, &proxy_flag, &user_agent);
-       if (opt & WGET_OPT_CONTINUE) {
-               ++do_continue;
-       }
-       if (opt & WGET_OPT_QUIET) {
-               quiet_flag = TRUE;
-       }
        if (strcmp(proxy_flag, "off") == 0) {
                /* Use the proxy if necessary. */
                use_proxy = 0;
@@ -221,7 +202,7 @@ int wget_main(int argc, char **argv)
 #endif
                                bb_get_last_path_component(target.path);
                }
-               if (fname_out == NULL || strlen(fname_out) < 1) {
+               if (!fname_out || !fname_out[0]) {
                        fname_out =
 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
                                curfile =
@@ -235,30 +216,25 @@ int wget_main(int argc, char **argv)
                curfile = bb_get_last_path_component(fname_out);
 #endif
        }
-       if (do_continue && !fname_out)
+       if ((opt & WGET_OPT_CONTINUE) && !fname_out)
                bb_error_msg_and_die("cannot specify continue (-c) without a filename (-O)");
 
-
-       /*
-        * Open the output file stream.
-        */
-       if (strcmp(fname_out, "-") == 0) {
-               output = stdout;
-               quiet_flag = TRUE;
-       } else {
-               output = xfopen(fname_out, (do_continue ? "a" : "w"));
-       }
-
        /*
         * Determine where to start transfer.
         */
-       if (do_continue) {
-               if (fstat(fileno(output), &sbuf) < 0)
-                       bb_perror_msg_and_die("fstat");
-               if (sbuf.st_size > 0)
-                       beg_range = sbuf.st_size;
-               else
-                       do_continue = 0;
+       if (!strcmp(fname_out, "-")) {
+               output_fd = 1;
+               opt |= WGET_OPT_QUIET;
+               opt &= ~WGET_OPT_CONTINUE;
+       } else if (opt & WGET_OPT_CONTINUE) {
+               output_fd = open(fname_out, O_WRONLY|O_LARGEFILE);
+               if (output_fd >= 0) {
+                       beg_range = LSEEK(output_fd, 0, SEEK_END);
+                       if (beg_range == (FILEOFF_TYPE)-1)
+                               bb_perror_msg_and_die("lseek");
+               }
+               /* File doesn't exist. We do not create file here yet.
+                  We are not sure it exists on remove side */
        }
 
        /* We want to do exactly _one_ DNS lookup, since some
@@ -266,7 +242,7 @@ int wget_main(int argc, char **argv)
         * and we want to connect to only one IP... */
        bb_lookup_host(&s_in, server.host);
        s_in.sin_port = server.port;
-       if (quiet_flag == FALSE) {
+       if (!(opt & WGET_OPT_QUIET)) {
                printf("Connecting to %s[%s]:%d\n",
                                server.host, inet_ntoa(s_in.sin_addr), ntohs(server.port));
        }
@@ -279,7 +255,7 @@ int wget_main(int argc, char **argv)
                        got_clen = chunked = 0;
 
                        if (!--try)
-                               close_delete_and_die("too many redirections");
+                               bb_error_msg_and_die("too many redirections");
 
                        /*
                         * Open socket to http server
@@ -317,8 +293,8 @@ int wget_main(int argc, char **argv)
                        }
 #endif
 
-                       if (do_continue)
-                               fprintf(sfp, "Range: bytes=%ld-\r\n", beg_range);
+                       if (beg_range)
+                               fprintf(sfp, "Range: bytes="FILEOFF_FMT"-\r\n", beg_range);
                        if(extra_headers_left < sizeof(extra_headers))
                                fputs(extra_headers,sfp);
                        fprintf(sfp,"Connection: close\r\n\r\n");
@@ -328,7 +304,7 @@ int wget_main(int argc, char **argv)
                        */
 read_response:
                        if (fgets(buf, sizeof(buf), sfp) == NULL)
-                               close_delete_and_die("no response from server");
+                               bb_error_msg_and_die("no response from server");
 
                        for (s = buf ; *s != '\0' && !isspace(*s) ; ++s)
                                ;
@@ -340,9 +316,6 @@ read_response:
                                        while (gethdr(buf, sizeof(buf), sfp, &n) != NULL);
                                        goto read_response;
                                case 200:
-                                       if (do_continue && output != stdout)
-                                               output = freopen(fname_out, "w", output);
-                                       do_continue = 0;
                                        break;
                                case 300:       /* redirection */
                                case 301:
@@ -350,12 +323,12 @@ read_response:
                                case 303:
                                        break;
                                case 206:
-                                       if (do_continue)
+                                       if (beg_range)
                                                break;
                                        /*FALLTHRU*/
                                default:
                                        chomp(buf);
-                                       close_delete_and_die("server returned error %d: %s", atoi(s), buf);
+                                       bb_error_msg_and_die("server returned error %d: %s", atoi(s), buf);
                        }
 
                        /*
@@ -363,11 +336,9 @@ read_response:
                         */
                        while ((s = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
                                if (strcasecmp(buf, "content-length") == 0) {
-                                       unsigned long value;
-                                       if (safe_strtoul(s, &value)) {
-                                               close_delete_and_die("content-length %s is garbage", s);
+                                       if (SAFE_STRTOOFF(s, &content_len) || content_len < 0) {
+                                               bb_error_msg_and_die("content-length %s is garbage", s);
                                        }
-                                       filesize = value;
                                        got_clen = 1;
                                        continue;
                                }
@@ -375,7 +346,7 @@ read_response:
                                        if (strcasecmp(s, "chunked") == 0) {
                                                chunked = got_clen = 1;
                                        } else {
-                                               close_delete_and_die("server wants to do %s transfer encoding", s);
+                                               bb_error_msg_and_die("server wants to do %s transfer encoding", s);
                                        }
                                }
                                if (strcasecmp(buf, "location") == 0) {
@@ -407,7 +378,7 @@ read_response:
 
                sfp = open_socket(&s_in);
                if (ftpcmd(NULL, NULL, sfp, buf) != 220)
-                       close_delete_and_die("%s", buf+4);
+                       bb_error_msg_and_die("%s", buf+4);
 
                /*
                 * Splitting username:password pair,
@@ -416,7 +387,7 @@ read_response:
                s = strchr(target.user, ':');
                if (s)
                        *(s++) = '\0';
-               switch(ftpcmd("USER ", target.user, sfp, buf)) {
+               switch (ftpcmd("USER ", target.user, sfp, buf)) {
                        case 230:
                                break;
                        case 331:
@@ -424,7 +395,7 @@ read_response:
                                        break;
                                /* FALLTHRU (failed login) */
                        default:
-                               close_delete_and_die("ftp login: %s", buf+4);
+                               bb_error_msg_and_die("ftp login: %s", buf+4);
                }
 
                ftpcmd("TYPE I", NULL, sfp, buf);
@@ -433,11 +404,9 @@ read_response:
                 * Querying file size
                 */
                if (ftpcmd("SIZE ", target.path, sfp, buf) == 213) {
-                       unsigned long value;
-                       if (safe_strtoul(buf+4, &value)) {
-                               close_delete_and_die("SIZE value is garbage");
+                       if (SAFE_STRTOOFF(buf+4, &content_len) || content_len < 0) {
+                               bb_error_msg_and_die("SIZE value is garbage");
                        }
-                       filesize = value;
                        got_clen = 1;
                }
 
@@ -445,7 +414,7 @@ read_response:
                 * Entering passive mode
                 */
                if (ftpcmd("PASV", NULL, sfp, buf) !=  227)
-                       close_delete_and_die("PASV: %s", buf+4);
+                       bb_error_msg_and_die("PASV: %s", buf+4);
                s = strrchr(buf, ',');
                *s = 0;
                port = atoi(s+1);
@@ -454,18 +423,14 @@ read_response:
                s_in.sin_port = htons(port);
                dfp = open_socket(&s_in);
 
-               if (do_continue) {
-                       sprintf(buf, "REST %ld", beg_range);
-                       if (ftpcmd(buf, NULL, sfp, buf) != 350) {
-                               if (output != stdout)
-                                       output = freopen(fname_out, "w", output);
-                               do_continue = 0;
-                       } else
-                               filesize -= beg_range;
+               if (beg_range) {
+                       sprintf(buf, "REST "FILEOFF_FMT, beg_range);
+                       if (ftpcmd(buf, NULL, sfp, buf) == 350)
+                               content_len -= beg_range;
                }
 
                if (ftpcmd("RETR ", target.path, sfp, buf) > 150)
-                       close_delete_and_die("RETR: %s", buf+4);
+                       bb_error_msg_and_die("RETR: %s", buf+4);
        }
 
 
@@ -474,36 +439,43 @@ read_response:
         */
        if (chunked) {
                fgets(buf, sizeof(buf), dfp);
-               filesize = strtol(buf, (char **) NULL, 16);
+               content_len = STRTOOFF(buf, (char **) NULL, 16);
+               /* FIXME: error check?? */
        }
 
-       if (quiet_flag == FALSE)
+       /* Do it before progressmeter (want to have nice error message) */
+       if (output_fd < 0)
+               output_fd = xopen3(fname_out,
+                       O_WRONLY|O_CREAT|O_EXCL|O_TRUNC|O_LARGEFILE, 0666);
+
+       if (!(opt & WGET_OPT_QUIET))
                progressmeter(-1);
 
        do {
-               while (filesize > 0 || !got_clen) {
+               while (content_len > 0 || !got_clen) {
                        unsigned rdsz = sizeof(buf);
-                       if (filesize < sizeof(buf) && (chunked || got_clen))
-                               rdsz = filesize;
+                       if (content_len < sizeof(buf) && (chunked || got_clen))
+                               rdsz = (unsigned)content_len;
                        n = safe_fread(buf, 1, rdsz, dfp);
                        if (n <= 0)
                                break;
-                       if (safe_fwrite(buf, 1, n, output) != n) {
+                       if (full_write(output_fd, buf, n) != n) {
                                bb_perror_msg_and_die(bb_msg_write_error);
                        }
 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
                        transferred += n;
 #endif
                        if (got_clen) {
-                               filesize -= n;
+                               content_len -= n;
                        }
                }
 
                if (chunked) {
                        safe_fgets(buf, sizeof(buf), dfp); /* This is a newline */
                        safe_fgets(buf, sizeof(buf), dfp);
-                       filesize = strtol(buf, (char **) NULL, 16);
-                       if (filesize == 0) {
+                       content_len = STRTOOFF(buf, (char **) NULL, 16);
+                       /* FIXME: error check? */
+                       if (content_len == 0) {
                                chunked = 0; /* all done! */
                        }
                }
@@ -513,7 +485,7 @@ read_response:
                }
        } while (chunked);
 
-       if (quiet_flag == FALSE)
+       if (!(opt & WGET_OPT_QUIET))
                progressmeter(1);
 
        if ((use_proxy == 0) && target.is_ftp) {
@@ -526,7 +498,7 @@ read_response:
 }
 
 
-void parse_url(char *url, struct host_info *h)
+static void parse_url(char *url, struct host_info *h)
 {
        char *cp, *sp, *up, *pp;
 
@@ -581,7 +553,7 @@ void parse_url(char *url, struct host_info *h)
 }
 
 
-FILE *open_socket(struct sockaddr_in *s_in)
+static FILE *open_socket(struct sockaddr_in *s_in)
 {
        FILE *fp;
 
@@ -593,7 +565,7 @@ FILE *open_socket(struct sockaddr_in *s_in)
 }
 
 
-char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
+static char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
 {
        char *s, *hdrval;
        int c;
@@ -666,10 +638,7 @@ static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf)
 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
 /* Stuff below is from BSD rcp util.c, as added to openshh.
  * Original copyright notice is retained at the end of this file.
- *
  */
-
-
 static int
 getttywidth(void)
 {
@@ -702,24 +671,24 @@ static void
 progressmeter(int flag)
 {
        static struct timeval lastupdate;
-       static off_t lastsize, totalsize;
+       static FILEOFF_TYPE lastsize, totalsize;
 
        struct timeval now, td, tvwait;
-       off_t abbrevsize;
+       FILEOFF_TYPE abbrevsize;
        int elapsed, ratio, barlength, i;
        char buf[256];
 
-       if (flag == -1) {
+       if (flag == -1) { /* first call to progressmeter */
                (void) gettimeofday(&start, (struct timezone *) 0);
                lastupdate = start;
                lastsize = 0;
-               totalsize = filesize; /* as filesize changes.. */
+               totalsize = content_len + beg_range; /* as content_len changes.. */
        }
 
        (void) gettimeofday(&now, (struct timezone *) 0);
        ratio = 100;
        if (totalsize != 0 && !chunked) {
-               ratio = (int) (100 * transferred / totalsize);
+               ratio = (int) (100 * (transferred+beg_range) / totalsize);
                ratio = MIN(ratio, 100);
        }
 
@@ -734,7 +703,7 @@ progressmeter(int flag)
                fprintf(stderr, "|%s|", buf);
        }
        i = 0;
-       abbrevsize = transferred;
+       abbrevsize = transferred + beg_range;
        while (abbrevsize >= 100000) {
                i++;
                abbrevsize >>= 10;
@@ -755,23 +724,26 @@ progressmeter(int flag)
 
        if (tvwait.tv_sec >= STALLTIME) {
                fprintf(stderr, " - stalled -");
-       } else if (transferred <= 0 || elapsed <= 0 || transferred > totalsize || chunked) {
-               fprintf(stderr, "--:--:-- ETA");
        } else {
-               /* totalsize / (transferred/elapsed) - elapsed: */
-               int eta = (int) (totalsize*elapsed/transferred - elapsed);
-               i = eta % 3600;
-               fprintf(stderr, "%02d:%02d:%02d ETA", eta / 3600, i / 60, i % 60);
+               FILEOFF_TYPE to_download = totalsize - beg_range;
+               if (transferred <= 0 || elapsed <= 0 || transferred > to_download || chunked) {
+                       fprintf(stderr, "--:--:-- ETA");
+               } else {
+                       /* to_download / (transferred/elapsed) - elapsed: */
+                       int eta = (int) (to_download*elapsed/transferred - elapsed);
+                       i = eta % 3600;
+                       fprintf(stderr, "%02d:%02d:%02d ETA", eta / 3600, i / 60, i % 60);
+               }
        }
 
-       if (flag == -1) {
+       if (flag == -1) { /* first call to progressmeter */
                struct sigaction sa;
                sa.sa_handler = updateprogressmeter;
                sigemptyset(&sa.sa_mask);
                sa.sa_flags = SA_RESTART;
                sigaction(SIGALRM, &sa, NULL);
                alarmtimer(1);
-       } else if (flag == 1) {
+       } else if (flag == 1) { /* last call to progressmeter */
                alarmtimer(0);
                transferred = 0;
                putc('\n', stderr);