aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

wget.c (16965B)


      1 /* see license file for copyright and license details */
      2 
      3 #ifndef _XOPEN_SOURCE
      4 #define _XOPEN_SOURCE 500
      5 #endif
      6 
      7 #include "arg.h"
      8 #include "tls.h"
      9 #include "util.h"
     10 
     11 #include <arpa/inet.h>
     12 #include <ctype.h>
     13 #include <errno.h>
     14 #include <fcntl.h>
     15 #include <limits.h>
     16 #include <netdb.h>
     17 #include <netinet/in.h>
     18 #include <stdio.h>
     19 #include <stdlib.h>
     20 #include <string.h>
     21 #include <strings.h>
     22 #include <sys/socket.h>
     23 #include <sys/stat.h>
     24 #include <sys/time.h>
     25 #include <sys/types.h>
     26 #include <unistd.h>
     27 
     28 struct Stream {
     29   struct TlsSocket *ts;
     30   char              buf[8192];
     31   size_t            len;
     32   size_t            idx;
     33 };
     34 
     35 static int    qflag                = 0;
     36 static int    Sflag                = 0;
     37 static int    cflag                = 0;
     38 static int    spider               = 0;
     39 static int    no_check_certificate = 0;
     40 static int    timeout_sec          = 900;
     41 static int    tries                = 20;
     42 static char  *Pflag                = NULL;
     43 static char  *Oflag                = NULL;
     44 static char  *user_agent           = "wget/aruu";
     45 static char  *post_data            = NULL;
     46 static char  *post_file            = NULL;
     47 static char **custom_headers       = NULL;
     48 static size_t custom_headers_num   = 0;
     49 
     50 static void
     51 usage(void)
     52 {
     53   eprintf(
     54       "usage: %s [-cqS] [-O file] [-P dir] [-T timeout] [-t tries] [-U "
     55       "user_agent] "
     56       "[-post-data data] [-post-file file] [-header header] "
     57       "[-no-check-certificate] [-spider] url\n",
     58       argv0
     59   );
     60 }
     61 
     62 static void
     63 add_header(const char *hdr)
     64 {
     65   custom_headers = ereallocarray(custom_headers, custom_headers_num + 1, sizeof(*custom_headers));
     66   custom_headers[custom_headers_num++] = estrdup(hdr);
     67 }
     68 
     69 static int
     70 dial(const char *host, const char *port)
     71 {
     72   struct addrinfo hints, *res, *rp;
     73   int             fd = -1, r;
     74 
     75   memset(&hints, 0, sizeof(hints));
     76   hints.ai_family   = AF_UNSPEC;
     77   hints.ai_socktype = SOCK_STREAM;
     78 
     79   r = getaddrinfo(host, port, &hints, &res);
     80   if (r != 0) {
     81     if (!qflag)
     82       weprintf("getaddrinfo %s:%s: %s\n", host, port, gai_strerror(r));
     83     return -1;
     84   }
     85 
     86   for (rp = res; rp; rp = rp->ai_next) {
     87     fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
     88     if (fd < 0)
     89       continue;
     90     if (timeout_sec > 0) {
     91       struct timeval tv;
     92       tv.tv_sec  = timeout_sec;
     93       tv.tv_usec = 0;
     94       setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
     95       setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
     96     }
     97     if (connect(fd, rp->ai_addr, rp->ai_addrlen) == 0)
     98       break;
     99     close(fd);
    100     fd = -1;
    101   }
    102 
    103   freeaddrinfo(res);
    104   return fd;
    105 }
    106 
    107 static void
    108 parse_url(char *url, char **host, char **port, char **path, int *is_tls)
    109 {
    110   char *p, *ss;
    111 
    112   *is_tls = 0;
    113   if (strncasecmp(url, "http:// ", 7) == 0) {
    114     url += 7;
    115   } else if (strncasecmp(url, "https:// ", 8) == 0) {
    116     url += 8;
    117     *is_tls = 1;
    118   } else {
    119     eprintf("unsupported protocol or invalid url: %s\n", url);
    120   }
    121 
    122   *host = url;
    123   p     = strchr(url, '/');
    124   if (p) {
    125     *p    = '\0';
    126     *path = p + 1;
    127   } else {
    128     *path = "";
    129   }
    130 
    131   /* handle ipv6 brackets or host:port */
    132   if (**host == '[') {
    133     (*host)++;
    134     ss = strchr(*host, ']');
    135     if (ss) {
    136       *ss = '\0';
    137       ss++;
    138       if (*ss == ':')
    139         *port = ss + 1;
    140       else
    141         *port = *is_tls ? "443" : "80";
    142     } else {
    143       eprintf("invalid ipv6 literal: %s\n", *host);
    144     }
    145   } else {
    146     p = strrchr(*host, ':');
    147     if (p) {
    148       *p    = '\0';
    149       *port = p + 1;
    150     } else {
    151       *port = *is_tls ? "443" : "80";
    152     }
    153   }
    154 }
    155 
    156 static char *
    157 find_header(const char *headers, const char *name)
    158 {
    159   const char *p;
    160   size_t      len = strlen(name);
    161 
    162   p = headers;
    163   while (p && *p) {
    164     if (strncasecmp(p, name, len) == 0) {
    165       p += len;
    166       while (*p == ' ' || *p == '\t')
    167         p++;
    168       len = strcspn(p, "\r\n");
    169       return estrndup(p, len);
    170     }
    171     p = strchr(p, '\n');
    172     if (p)
    173       p++;
    174   }
    175   return NULL;
    176 }
    177 
    178 static int
    179 stream_getc(struct Stream *s)
    180 {
    181   ssize_t r;
    182 
    183   if (s->idx < s->len) {
    184     return (unsigned char)s->buf[s->idx++];
    185   }
    186   s->idx = 0;
    187   r      = tlss_read(s->ts, s->buf, sizeof(s->buf));
    188   if (r <= 0) {
    189     s->len = 0;
    190     return EOF;
    191   }
    192   s->len = (size_t)r;
    193   return (unsigned char)s->buf[s->idx++];
    194 }
    195 
    196 static size_t
    197 stream_read(struct Stream *s, void *ptr, size_t size)
    198 {
    199   size_t  total = 0;
    200   size_t  n;
    201   char   *p = ptr;
    202   ssize_t r;
    203 
    204   while (total < size) {
    205     if (s->idx < s->len) {
    206       n = MIN(size - total, s->len - s->idx);
    207       memcpy(p + total, s->buf + s->idx, n);
    208       s->idx += n;
    209       total += n;
    210     } else {
    211       s->idx = 0;
    212       r      = tlss_read(s->ts, s->buf, sizeof(s->buf));
    213       if (r <= 0) {
    214         s->len = 0;
    215         break;
    216       }
    217       s->len = (size_t)r;
    218     }
    219   }
    220   return total;
    221 }
    222 
    223 static void
    224 read_chunked(struct Stream *s, int out_fd)
    225 {
    226   char      line[128];
    227   char      chunk_buf[8192];
    228   size_t    line_len, n;
    229   long long chunk_size, remaining;
    230   int       c;
    231 
    232   for (;;) {
    233     line_len = 0;
    234     for (;;) {
    235       c = stream_getc(s);
    236       if (c == EOF)
    237         eprintf(
    238             "unexpected end of file reading chunk "
    239             "size\n"
    240         );
    241       if (c == '\n') {
    242         line[line_len] = '\0';
    243         break;
    244       }
    245       if (c != '\r' && line_len < sizeof(line) - 1) {
    246         line[line_len++] = c;
    247       }
    248     }
    249 
    250     chunk_size = strtoll(line, NULL, 16);
    251     if (chunk_size == 0) {
    252       stream_getc(s);
    253       stream_getc(s);
    254       break;
    255     }
    256 
    257     remaining = chunk_size;
    258     while (remaining > 0) {
    259       n = stream_read(s, chunk_buf, MIN(remaining, (long long)sizeof(chunk_buf)));
    260       if (n == 0)
    261         eprintf(
    262             "unexpected end of file in chunk "
    263             "data\n"
    264         );
    265       if (writeall(out_fd, chunk_buf, n) < 0)
    266         eprintf("write output:\n");
    267       remaining -= n;
    268     }
    269 
    270     stream_getc(s);
    271     stream_getc(s);
    272   }
    273 }
    274 
    275 static void
    276 read_non_chunked(struct Stream *s, int out_fd, long long content_len)
    277 {
    278   char      chunk_buf[8192];
    279   long long remaining = content_len;
    280   size_t    n, to_read;
    281 
    282   while (content_len < 0 || remaining > 0) {
    283     to_read = sizeof(chunk_buf);
    284     if (content_len >= 0)
    285       to_read = (size_t)MIN(remaining, (long long)sizeof(chunk_buf));
    286     n = stream_read(s, chunk_buf, to_read);
    287     if (n == 0) {
    288       if (content_len >= 0)
    289         eprintf("unexpected end of file\n");
    290       break;
    291     }
    292     if (writeall(out_fd, chunk_buf, n) < 0)
    293       eprintf("write output:\n");
    294     if (content_len >= 0)
    295       remaining -= n;
    296   }
    297 }
    298 
    299 static void
    300 req_printf(struct TlsSocket *ts, const char *fmt, ...)
    301 {
    302   va_list ap;
    303   char    buf[1024];
    304   int     len;
    305 
    306   va_start(ap, fmt);
    307   len = vsnprintf(buf, sizeof(buf), fmt, ap);
    308   va_end(ap);
    309   if (len > 0)
    310     tlss_write(ts, buf, len);
    311 }
    312 
    313 // ?man wget: retrieve files from the web
    314 // ?man arguments: url
    315 // ?man download files over http or https
    316 int
    317 main(int argc, char *argv[])
    318 {
    319   struct Stream     s;
    320   char             *url, *host, *port, *path, *loc;
    321   char             *curr_host, *curr_port, *curr_path;
    322   char             *new_url;
    323   char             *cl_str;
    324   char             *te_str;
    325   char             *header_end;
    326   char             *out_name;
    327   int               redirects     = 0;
    328   int               max_redirects = 20;
    329   int               sock_fd       = -1;
    330   int               out_fd        = 1;
    331   int               chunked;
    332   int               status;
    333   long long         content_len;
    334   size_t            total_read;
    335   ssize_t           n;
    336   size_t            dir_len;
    337   char             *last_slash;
    338   int               is_tls        = 0;
    339   struct TlsSocket *tls_sock      = NULL;
    340   off_t             resume_offset = 0;
    341   int               out_mode      = O_WRONLY | O_CREAT | O_TRUNC;
    342   long long         post_len      = 0;
    343   int               post_fd       = -1;
    344   size_t            i;
    345   int               attempt;
    346   int               max_tries;
    347 
    348   ARGBEGIN
    349   {
    350     // ?man -O:str: specify output file path
    351     case 'O':
    352       Oflag = EARGF(usage());
    353       break;
    354     // ?man -P:str: specify output directory prefix
    355     case 'P':
    356       Pflag = EARGF(usage());
    357       break;
    358     // ?man -T:num: set network read and connect timeout
    359     case 'T':
    360       timeout_sec = estrtonum(EARGF(usage()), 0, 100000);
    361       break;
    362     // ?man -t:num: set number of connection retries, 0 retries forever
    363     case 't':
    364       tries = estrtonum(EARGF(usage()), 0, 1000000);
    365       break;
    366     // ?man -U:str: set User-Agent header
    367     case 'U':
    368       user_agent = EARGF(usage());
    369       break;
    370     // ?man -c: continue retrieval of aborted transfer
    371     case 'c':
    372       cflag = 1;
    373       break;
    374     // ?man -q: quiet mode to suppress stderr output
    375     case 'q':
    376       qflag = 1;
    377       break;
    378     // ?man -S: print server response headers to stderr
    379     case 'S':
    380       Sflag = 1;
    381       break;
    382     // ?man --: specify - option
    383     case '-':
    384       if (strcmp(argv[0], "-no-check-certificate") == 0) {
    385         no_check_certificate = 1;
    386         brk_                 = 1;
    387       } else if (strncmp(argv[0], "-header=", 8) == 0) {
    388         add_header(argv[0] + 8);
    389         brk_ = 1;
    390       } else if (strcmp(argv[0], "-header") == 0) {
    391         brk_ = 1;
    392         if (!argv[1])
    393           usage();
    394         add_header(argv[1]);
    395         argv++;
    396         argc--;
    397       } else if (strncmp(argv[0], "-post-data=", 11) == 0) {
    398         post_data = argv[0] + 11;
    399         brk_      = 1;
    400       } else if (strcmp(argv[0], "-post-data") == 0) {
    401         brk_ = 1;
    402         if (!argv[1])
    403           usage();
    404         post_data = argv[1];
    405         argv++;
    406         argc--;
    407       } else if (strncmp(argv[0], "-post-file=", 11) == 0) {
    408         post_file = argv[0] + 11;
    409         brk_      = 1;
    410       } else if (strcmp(argv[0], "-post-file") == 0) {
    411         brk_ = 1;
    412         if (!argv[1])
    413           usage();
    414         post_file = argv[1];
    415         argv++;
    416         argc--;
    417       } else if (strcmp(argv[0], "-spider") == 0) {
    418         spider = 1;
    419         brk_   = 1;
    420       } else {
    421         usage();
    422       }
    423       break;
    424     default:
    425       usage();
    426   }
    427   ARGEND
    428 
    429   if (argc < 1)
    430     usage();
    431 
    432   url = estrdup(argv[0]);
    433 
    434   /* determine output filename early to check for resume */
    435   out_name = NULL;
    436   if (Oflag) {
    437     out_name = Oflag;
    438   } else {
    439     last_slash = strrchr(url, '/');
    440     if (last_slash && *(last_slash + 1))
    441       out_name = last_slash + 1;
    442     else
    443       out_name = "index.html";
    444 
    445     if (Pflag) {
    446       char *tmp = emalloc(strlen(Pflag) + 1 + strlen(out_name) + 1);
    447       sprintf(tmp, "%s/%s", Pflag, out_name);
    448       out_name = tmp;
    449     }
    450   }
    451 
    452   if (cflag && out_name && strcmp(out_name, "-") != 0) {
    453     struct stat st;
    454     if (stat(out_name, &st) == 0 && S_ISREG(st.st_mode)) {
    455       resume_offset = st.st_size;
    456     }
    457   }
    458 
    459   if (post_data) {
    460     post_len = strlen(post_data);
    461   } else if (post_file) {
    462     struct stat st;
    463     post_fd = open(post_file, O_RDONLY);
    464     if (post_fd < 0)
    465       eprintf("open %s:\n", post_file);
    466     if (fstat(post_fd, &st) < 0)
    467       eprintf("stat %s:\n", post_file);
    468     post_len = st.st_size;
    469   }
    470 
    471   /* -t 0 means retry forever */
    472   max_tries = tries == 0 ? INT_MAX : tries;
    473 
    474   while (!tls_sock) {
    475     if (redirects > max_redirects)
    476       eprintf("too many redirects\n");
    477 
    478     curr_host = curr_port = curr_path = NULL;
    479     parse_url(url, &curr_host, &curr_port, &curr_path, &is_tls);
    480 
    481     host = estrdup(curr_host);
    482     port = estrdup(curr_port);
    483     path = estrdup(curr_path);
    484 
    485     for (attempt = 1; attempt <= max_tries; attempt++) {
    486       sock_fd = dial(host, port);
    487       if (sock_fd < 0) {
    488         if (attempt == max_tries)
    489           eprintf("failed to connect to %s:%s\n", host, port);
    490         continue;
    491       }
    492 
    493       tls_sock = tlss_connect(sock_fd, host, !no_check_certificate, is_tls);
    494       if (!tls_sock) {
    495         close(sock_fd);
    496         if (attempt == max_tries)
    497           eprintf("failed to establish TLS connection with %s\n", host);
    498         continue;
    499       }
    500 
    501       break;
    502     }
    503 
    504     /* send http request */
    505     const char *method = spider ? "HEAD" : ((post_data || post_file) ? "POST" : "GET");
    506     req_printf(tls_sock, "%s /%s HTTP/1.1\r\n", method, path);
    507     req_printf(tls_sock, "Host: %s\r\n", host);
    508     req_printf(tls_sock, "User-Agent: %s\r\n", user_agent);
    509     req_printf(tls_sock, "Connection: close\r\n");
    510 
    511     if (resume_offset > 0) {
    512       req_printf(tls_sock, "Range: bytes=%lld-\r\n", (long long)resume_offset);
    513     }
    514 
    515     if (post_data || post_file) {
    516       int has_ct = 0;
    517       for (i = 0; i < custom_headers_num; i++) {
    518         if (strncasecmp(custom_headers[i], "Content-Type:", 13) == 0) {
    519           has_ct = 1;
    520           break;
    521         }
    522       }
    523       if (!has_ct) {
    524         req_printf(
    525             tls_sock,
    526             "Content-Type: "
    527             "application/"
    528             "x-www-form-urlencoded\r\n"
    529         );
    530       }
    531       req_printf(tls_sock, "Content-Length: %lld\r\n", post_len);
    532     }
    533 
    534     for (i = 0; i < custom_headers_num; i++) {
    535       req_printf(tls_sock, "%s\r\n", custom_headers[i]);
    536     }
    537 
    538     req_printf(tls_sock, "\r\n");
    539 
    540     if (post_data) {
    541       tlss_write(tls_sock, post_data, strlen(post_data));
    542     } else if (post_file) {
    543       char    io_buf[8192];
    544       ssize_t r;
    545       while ((r = read(post_fd, io_buf, sizeof(io_buf))) > 0) {
    546         if (tlss_write(tls_sock, io_buf, r) < 0) {
    547           eprintf("failed to write post data:\n");
    548         }
    549       }
    550       close(post_fd);
    551       post_fd = -1;
    552     }
    553 
    554     /* read headers */
    555     total_read = 0;
    556     header_end = NULL;
    557     memset(s.buf, 0, sizeof(s.buf));
    558     while (total_read < sizeof(s.buf) - 1) {
    559       n = tlss_read(tls_sock, s.buf + total_read, sizeof(s.buf) - 1 - total_read);
    560       if (n <= 0) {
    561         if (n < 0)
    562           eprintf("read socket:\n");
    563         else
    564           eprintf(
    565               "connection closed by "
    566               "server\n"
    567           );
    568       }
    569       total_read += n;
    570       s.buf[total_read] = '\0';
    571       header_end        = strstr(s.buf, "\r\n\r\n");
    572       if (header_end)
    573         break;
    574     }
    575 
    576     if (!header_end)
    577       eprintf("http header too large or not found\n");
    578 
    579     *header_end = '\0';
    580     s.ts        = tls_sock;
    581     s.len       = total_read;
    582     s.idx       = (header_end + 4) - s.buf;
    583 
    584     if (Sflag) {
    585       fprintf(stderr, "%s\n\n", s.buf);
    586     }
    587 
    588     if (strncasecmp(s.buf, "HTTP/1.1 ", 9) != 0 && strncasecmp(s.buf, "HTTP/1.0 ", 9) != 0) {
    589       eprintf("invalid http response: %s\n", s.buf);
    590     }
    591     status = atoi(s.buf + 9);
    592 
    593     if (status >= 300 && status < 400) {
    594       loc = find_header(s.buf, "Location:");
    595       if (!loc)
    596         eprintf(
    597             "redirect response without location "
    598             "header\n"
    599         );
    600 
    601       if (strncasecmp(loc, "http:// ", 7) == 0 || strncasecmp(loc, "https://", 8) == 0) {
    602         new_url = estrdup(loc);
    603       } else if (loc[0] == '/') {
    604         new_url = emalloc(8 + strlen(host) + strlen(port) + strlen(loc) + 2);
    605         sprintf(new_url, "%s:// %s:%s%s", is_tls ? "https" : "http", host, port, loc);
    606       } else {
    607         last_slash = strrchr(path, '/');
    608         dir_len    = 0;
    609         if (last_slash)
    610           dir_len = last_slash - path + 1;
    611         new_url = emalloc(8 + strlen(host) + strlen(port) + 1 + dir_len + strlen(loc) + 2);
    612         sprintf(new_url, "%s:// %s:%s/", is_tls ? "https" : "http", host, port);
    613         if (dir_len > 0)
    614           strncat(new_url, path, dir_len);
    615         strcat(new_url, loc);
    616       }
    617 
    618       free(loc);
    619       free(url);
    620       url = new_url;
    621       tlss_close(tls_sock, 1);
    622       tls_sock = NULL;
    623       redirects++;
    624     } else if (status == 206) {
    625       out_mode = O_WRONLY | O_CREAT | O_APPEND;
    626     } else if (status == 200) {
    627       out_mode = O_WRONLY | O_CREAT | O_TRUNC;
    628     } else if (status == 416) {
    629       if (!qflag)
    630         weprintf(
    631             "file already fully retrieved or "
    632             "range invalid\n"
    633         );
    634       tlss_close(tls_sock, 1);
    635       free(url);
    636       free(host);
    637       free(port);
    638       free(path);
    639       return 0;
    640     } else {
    641       eprintf("server returned status: %d\n", status);
    642     }
    643 
    644     free(host);
    645     free(port);
    646     free(path);
    647   }
    648 
    649   if (spider) {
    650     tlss_close(tls_sock, 1);
    651     free(url);
    652     return 0;
    653   }
    654 
    655   cl_str      = find_header(s.buf, "Content-Length:");
    656   content_len = -1;
    657   if (cl_str) {
    658     content_len = strtoll(cl_str, NULL, 10);
    659     free(cl_str);
    660   }
    661 
    662   te_str  = find_header(s.buf, "Transfer-Encoding:");
    663   chunked = 0;
    664   if (te_str) {
    665     if (strcasecmp(te_str, "chunked") == 0)
    666       chunked = 1;
    667     free(te_str);
    668   }
    669 
    670   if (strcmp(out_name, "-") != 0) {
    671     out_fd = open(out_name, out_mode, 0644);
    672     if (out_fd < 0)
    673       eprintf("open %s:\n", out_name);
    674   }
    675 
    676   if (chunked)
    677     read_chunked(&s, out_fd);
    678   else
    679     read_non_chunked(&s, out_fd, content_len);
    680 
    681   tlss_close(tls_sock, 1);
    682   if (out_fd != 1)
    683     close(out_fd);
    684   if (Oflag != out_name && Pflag)
    685     free(out_name);
    686   free(url);
    687 
    688   for (i = 0; i < custom_headers_num; i++) {
    689     free(custom_headers[i]);
    690   }
    691   free(custom_headers);
    692 
    693   return 0;
    694 }