wget.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * wget - retrieve a file using HTTP or FTP
  4. *
  5. * Chip Rosenthal Covad Communications <chip@laserlink.net>
  6. *
  7. * Licensed under GPLv2, see file LICENSE in this tarball for details.
  8. */
  9. #include "libbb.h"
  10. struct host_info {
  11. // May be used if we ever will want to free() all xstrdup()s...
  12. /* char *allocated; */
  13. const char *path;
  14. const char *user;
  15. char *host;
  16. int port;
  17. smallint is_ftp;
  18. };
  19. /* Globals (can be accessed from signal handlers) */
  20. struct globals {
  21. off_t content_len; /* Content-length of the file */
  22. off_t beg_range; /* Range at which continue begins */
  23. #if ENABLE_FEATURE_WGET_STATUSBAR
  24. off_t lastsize;
  25. off_t totalsize;
  26. off_t transferred; /* Number of bytes transferred so far */
  27. const char *curfile; /* Name of current file being transferred */
  28. unsigned lastupdate_sec;
  29. unsigned start_sec;
  30. #endif
  31. smallint chunked; /* chunked transfer encoding */
  32. smallint got_clen; /* got content-length: from server */
  33. };
  34. #define G (*(struct globals*)&bb_common_bufsiz1)
  35. struct BUG_G_too_big {
  36. char BUG_G_too_big[sizeof(G) <= COMMON_BUFSIZE ? 1 : -1];
  37. };
  38. #define content_len (G.content_len )
  39. #define beg_range (G.beg_range )
  40. #define lastsize (G.lastsize )
  41. #define totalsize (G.totalsize )
  42. #define transferred (G.transferred )
  43. #define curfile (G.curfile )
  44. #define lastupdate_sec (G.lastupdate_sec )
  45. #define start_sec (G.start_sec )
  46. #define INIT_G() do { } while (0)
  47. #if ENABLE_FEATURE_WGET_STATUSBAR
  48. enum {
  49. STALLTIME = 5 /* Seconds when xfer considered "stalled" */
  50. };
  51. static unsigned int get_tty2_width(void)
  52. {
  53. unsigned width;
  54. get_terminal_width_height(2, &width, NULL);
  55. return width;
  56. }
  57. static void progress_meter(int flag)
  58. {
  59. /* We can be called from signal handler */
  60. int save_errno = errno;
  61. off_t abbrevsize;
  62. unsigned since_last_update, elapsed;
  63. unsigned ratio;
  64. int barlength, i;
  65. if (flag == -1) { /* first call to progress_meter */
  66. start_sec = monotonic_sec();
  67. lastupdate_sec = start_sec;
  68. lastsize = 0;
  69. totalsize = content_len + beg_range; /* as content_len changes.. */
  70. }
  71. ratio = 100;
  72. if (totalsize != 0 && !G.chunked) {
  73. /* long long helps to have it working even if !LFS */
  74. ratio = (unsigned) (100ULL * (transferred+beg_range) / totalsize);
  75. if (ratio > 100) ratio = 100;
  76. }
  77. fprintf(stderr, "\r%-20.20s%4d%% ", curfile, ratio);
  78. barlength = get_tty2_width() - 49;
  79. if (barlength > 0) {
  80. /* god bless gcc for variable arrays :) */
  81. i = barlength * ratio / 100;
  82. {
  83. char buf[i+1];
  84. memset(buf, '*', i);
  85. buf[i] = '\0';
  86. fprintf(stderr, "|%s%*s|", buf, barlength - i, "");
  87. }
  88. }
  89. i = 0;
  90. abbrevsize = transferred + beg_range;
  91. while (abbrevsize >= 100000) {
  92. i++;
  93. abbrevsize >>= 10;
  94. }
  95. /* see http://en.wikipedia.org/wiki/Tera */
  96. fprintf(stderr, "%6d%c ", (int)abbrevsize, " kMGTPEZY"[i]);
  97. // Nuts! Ain't it easier to update progress meter ONLY when we transferred++?
  98. elapsed = monotonic_sec();
  99. since_last_update = elapsed - lastupdate_sec;
  100. if (transferred > lastsize) {
  101. lastupdate_sec = elapsed;
  102. lastsize = transferred;
  103. if (since_last_update >= STALLTIME) {
  104. /* We "cut off" these seconds from elapsed time
  105. * by adjusting start time */
  106. start_sec += since_last_update;
  107. }
  108. since_last_update = 0; /* we are un-stalled now */
  109. }
  110. elapsed -= start_sec; /* now it's "elapsed since start" */
  111. if (since_last_update >= STALLTIME) {
  112. fprintf(stderr, " - stalled -");
  113. } else {
  114. off_t to_download = totalsize - beg_range;
  115. if (transferred <= 0 || (int)elapsed <= 0 || transferred > to_download || G.chunked) {
  116. fprintf(stderr, "--:--:-- ETA");
  117. } else {
  118. /* to_download / (transferred/elapsed) - elapsed: */
  119. int eta = (int) ((unsigned long long)to_download*elapsed/transferred - elapsed);
  120. /* (long long helps to have working ETA even if !LFS) */
  121. i = eta % 3600;
  122. fprintf(stderr, "%02d:%02d:%02d ETA", eta / 3600, i / 60, i % 60);
  123. }
  124. }
  125. if (flag == 0) {
  126. /* last call to progress_meter */
  127. alarm(0);
  128. transferred = 0;
  129. fputc('\n', stderr);
  130. } else {
  131. if (flag == -1) { /* first call to progress_meter */
  132. signal_SA_RESTART_empty_mask(SIGALRM, progress_meter);
  133. }
  134. alarm(1);
  135. }
  136. errno = save_errno;
  137. }
  138. /* Original copyright notice which applies to the CONFIG_FEATURE_WGET_STATUSBAR stuff,
  139. * much of which was blatantly stolen from openssh. */
  140. /*-
  141. * Copyright (c) 1992, 1993
  142. * The Regents of the University of California. All rights reserved.
  143. *
  144. * Redistribution and use in source and binary forms, with or without
  145. * modification, are permitted provided that the following conditions
  146. * are met:
  147. * 1. Redistributions of source code must retain the above copyright
  148. * notice, this list of conditions and the following disclaimer.
  149. * 2. Redistributions in binary form must reproduce the above copyright
  150. * notice, this list of conditions and the following disclaimer in the
  151. * documentation and/or other materials provided with the distribution.
  152. *
  153. * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
  154. * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
  155. *
  156. * 4. Neither the name of the University nor the names of its contributors
  157. * may be used to endorse or promote products derived from this software
  158. * without specific prior written permission.
  159. *
  160. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  161. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  162. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  163. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  164. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  165. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  166. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  167. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  168. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  169. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  170. * SUCH DAMAGE.
  171. *
  172. */
  173. #else /* FEATURE_WGET_STATUSBAR */
  174. static ALWAYS_INLINE void progress_meter(int flag UNUSED_PARAM) { }
  175. #endif
  176. /* IPv6 knows scoped address types i.e. link and site local addresses. Link
  177. * local addresses can have a scope identifier to specify the
  178. * interface/link an address is valid on (e.g. fe80::1%eth0). This scope
  179. * identifier is only valid on a single node.
  180. *
  181. * RFC 4007 says that the scope identifier MUST NOT be sent across the wire,
  182. * unless all nodes agree on the semantic. Apache e.g. regards zone identifiers
  183. * in the Host header as invalid requests, see
  184. * https://issues.apache.org/bugzilla/show_bug.cgi?id=35122
  185. */
  186. static void strip_ipv6_scope_id(char *host)
  187. {
  188. char *scope, *cp;
  189. /* bbox wget actually handles IPv6 addresses without [], like
  190. * wget "http://::1/xxx", but this is not standard.
  191. * To save code, _here_ we do not support it. */
  192. if (host[0] != '[')
  193. return; /* not IPv6 */
  194. scope = strchr(host, '%');
  195. if (!scope)
  196. return;
  197. /* Remove the IPv6 zone identifier from the host address */
  198. cp = strchr(host, ']');
  199. if (!cp || (cp[1] != ':' && cp[1] != '\0')) {
  200. /* malformed address (not "[xx]:nn" or "[xx]") */
  201. return;
  202. }
  203. /* cp points to "]...", scope points to "%eth0]..." */
  204. overlapping_strcpy(scope, cp);
  205. }
  206. /* Read NMEMB bytes into PTR from STREAM. Returns the number of bytes read,
  207. * and a short count if an eof or non-interrupt error is encountered. */
  208. static size_t safe_fread(void *ptr, size_t nmemb, FILE *stream)
  209. {
  210. size_t ret;
  211. char *p = (char*)ptr;
  212. do {
  213. clearerr(stream);
  214. errno = 0;
  215. ret = fread(p, 1, nmemb, stream);
  216. p += ret;
  217. nmemb -= ret;
  218. } while (nmemb && ferror(stream) && errno == EINTR);
  219. return p - (char*)ptr;
  220. }
  221. /* Read a line or SIZE-1 bytes into S, whichever is less, from STREAM.
  222. * Returns S, or NULL if an eof or non-interrupt error is encountered. */
  223. static char *safe_fgets(char *s, int size, FILE *stream)
  224. {
  225. char *ret;
  226. do {
  227. clearerr(stream);
  228. errno = 0;
  229. ret = fgets(s, size, stream);
  230. } while (ret == NULL && ferror(stream) && errno == EINTR);
  231. return ret;
  232. }
  233. #if ENABLE_FEATURE_WGET_AUTHENTICATION
  234. /* Base64-encode character string. buf is assumed to be char buf[512]. */
  235. static char *base64enc_512(char buf[512], const char *str)
  236. {
  237. unsigned len = strlen(str);
  238. if (len > 512/4*3 - 10) /* paranoia */
  239. len = 512/4*3 - 10;
  240. bb_uuencode(buf, str, len, bb_uuenc_tbl_base64);
  241. return buf;
  242. }
  243. #endif
  244. static char* sanitize_string(char *s)
  245. {
  246. unsigned char *p = (void *) s;
  247. while (*p >= ' ')
  248. p++;
  249. *p = '\0';
  250. return s;
  251. }
  252. static FILE *open_socket(len_and_sockaddr *lsa)
  253. {
  254. FILE *fp;
  255. /* glibc 2.4 seems to try seeking on it - ??! */
  256. /* hopefully it understands what ESPIPE means... */
  257. fp = fdopen(xconnect_stream(lsa), "r+");
  258. if (fp == NULL)
  259. bb_perror_msg_and_die("fdopen");
  260. return fp;
  261. }
  262. static int ftpcmd(const char *s1, const char *s2, FILE *fp, char *buf)
  263. {
  264. int result;
  265. if (s1) {
  266. if (!s2) s2 = "";
  267. fprintf(fp, "%s%s\r\n", s1, s2);
  268. fflush(fp);
  269. }
  270. do {
  271. char *buf_ptr;
  272. if (fgets(buf, 510, fp) == NULL) {
  273. bb_perror_msg_and_die("error getting response");
  274. }
  275. buf_ptr = strstr(buf, "\r\n");
  276. if (buf_ptr) {
  277. *buf_ptr = '\0';
  278. }
  279. } while (!isdigit(buf[0]) || buf[3] != ' ');
  280. buf[3] = '\0';
  281. result = xatoi_u(buf);
  282. buf[3] = ' ';
  283. return result;
  284. }
  285. static void parse_url(char *src_url, struct host_info *h)
  286. {
  287. char *url, *p, *sp;
  288. /* h->allocated = */ url = xstrdup(src_url);
  289. if (strncmp(url, "http://", 7) == 0) {
  290. h->port = bb_lookup_port("http", "tcp", 80);
  291. h->host = url + 7;
  292. h->is_ftp = 0;
  293. } else if (strncmp(url, "ftp://", 6) == 0) {
  294. h->port = bb_lookup_port("ftp", "tcp", 21);
  295. h->host = url + 6;
  296. h->is_ftp = 1;
  297. } else
  298. bb_error_msg_and_die("not an http or ftp url: %s", sanitize_string(url));
  299. // FYI:
  300. // "Real" wget 'http://busybox.net?var=a/b' sends this request:
  301. // 'GET /?var=a/b HTTP 1.0'
  302. // and saves 'index.html?var=a%2Fb' (we save 'b')
  303. // wget 'http://busybox.net?login=john@doe':
  304. // request: 'GET /?login=john@doe HTTP/1.0'
  305. // saves: 'index.html?login=john@doe' (we save '?login=john@doe')
  306. // wget 'http://busybox.net#test/test':
  307. // request: 'GET / HTTP/1.0'
  308. // saves: 'index.html' (we save 'test')
  309. //
  310. // We also don't add unique .N suffix if file exists...
  311. sp = strchr(h->host, '/');
  312. p = strchr(h->host, '?'); if (!sp || (p && sp > p)) sp = p;
  313. p = strchr(h->host, '#'); if (!sp || (p && sp > p)) sp = p;
  314. if (!sp) {
  315. h->path = "";
  316. } else if (*sp == '/') {
  317. *sp = '\0';
  318. h->path = sp + 1;
  319. } else { // '#' or '?'
  320. // http://busybox.net?login=john@doe is a valid URL
  321. // memmove converts to:
  322. // http:/busybox.nett?login=john@doe...
  323. memmove(h->host - 1, h->host, sp - h->host);
  324. h->host--;
  325. sp[-1] = '\0';
  326. h->path = sp;
  327. }
  328. sp = strrchr(h->host, '@');
  329. h->user = NULL;
  330. if (sp != NULL) {
  331. h->user = h->host;
  332. *sp = '\0';
  333. h->host = sp + 1;
  334. }
  335. sp = h->host;
  336. }
  337. static char *gethdr(char *buf, size_t bufsiz, FILE *fp /*, int *istrunc*/)
  338. {
  339. char *s, *hdrval;
  340. int c;
  341. /* *istrunc = 0; */
  342. /* retrieve header line */
  343. if (fgets(buf, bufsiz, fp) == NULL)
  344. return NULL;
  345. /* see if we are at the end of the headers */
  346. for (s = buf; *s == '\r'; ++s)
  347. continue;
  348. if (*s == '\n')
  349. return NULL;
  350. /* convert the header name to lower case */
  351. for (s = buf; isalnum(*s) || *s == '-' || *s == '.'; ++s)
  352. *s = tolower(*s);
  353. /* verify we are at the end of the header name */
  354. if (*s != ':')
  355. bb_error_msg_and_die("bad header line: %s", sanitize_string(buf));
  356. /* locate the start of the header value */
  357. *s++ = '\0';
  358. hdrval = skip_whitespace(s);
  359. /* locate the end of header */
  360. while (*s && *s != '\r' && *s != '\n')
  361. ++s;
  362. /* end of header found */
  363. if (*s) {
  364. *s = '\0';
  365. return hdrval;
  366. }
  367. /* Rats! The buffer isn't big enough to hold the entire header value */
  368. while (c = getc(fp), c != EOF && c != '\n')
  369. continue;
  370. /* *istrunc = 1; */
  371. return hdrval;
  372. }
  373. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  374. static char *URL_escape(const char *str)
  375. {
  376. /* URL encode, see RFC 2396 */
  377. char *dst;
  378. char *res = dst = xmalloc(strlen(str) * 3 + 1);
  379. unsigned char c;
  380. while (1) {
  381. c = *str++;
  382. if (c == '\0'
  383. /* || strchr("!&'()*-.=_~", c) - more code */
  384. || c == '!'
  385. || c == '&'
  386. || c == '\''
  387. || c == '('
  388. || c == ')'
  389. || c == '*'
  390. || c == '-'
  391. || c == '.'
  392. || c == '='
  393. || c == '_'
  394. || c == '~'
  395. || (c >= '0' && c <= '9')
  396. || ((c|0x20) >= 'a' && (c|0x20) <= 'z')
  397. ) {
  398. *dst++ = c;
  399. if (c == '\0')
  400. return res;
  401. } else {
  402. *dst++ = '%';
  403. *dst++ = bb_hexdigits_upcase[c >> 4];
  404. *dst++ = bb_hexdigits_upcase[c & 0xf];
  405. }
  406. }
  407. }
  408. #endif
  409. static FILE* prepare_ftp_session(FILE **dfpp, struct host_info *target, len_and_sockaddr *lsa)
  410. {
  411. char buf[512];
  412. FILE *sfp;
  413. char *str;
  414. int port;
  415. if (!target->user)
  416. target->user = xstrdup("anonymous:busybox@");
  417. sfp = open_socket(lsa);
  418. if (ftpcmd(NULL, NULL, sfp, buf) != 220)
  419. bb_error_msg_and_die("%s", sanitize_string(buf+4));
  420. /*
  421. * Splitting username:password pair,
  422. * trying to log in
  423. */
  424. str = strchr(target->user, ':');
  425. if (str)
  426. *str++ = '\0';
  427. switch (ftpcmd("USER ", target->user, sfp, buf)) {
  428. case 230:
  429. break;
  430. case 331:
  431. if (ftpcmd("PASS ", str, sfp, buf) == 230)
  432. break;
  433. /* fall through (failed login) */
  434. default:
  435. bb_error_msg_and_die("ftp login: %s", sanitize_string(buf+4));
  436. }
  437. ftpcmd("TYPE I", NULL, sfp, buf);
  438. /*
  439. * Querying file size
  440. */
  441. if (ftpcmd("SIZE ", target->path, sfp, buf) == 213) {
  442. content_len = BB_STRTOOFF(buf+4, NULL, 10);
  443. if (errno || content_len < 0) {
  444. bb_error_msg_and_die("SIZE value is garbage");
  445. }
  446. G.got_clen = 1;
  447. }
  448. /*
  449. * Entering passive mode
  450. */
  451. if (ftpcmd("PASV", NULL, sfp, buf) != 227) {
  452. pasv_error:
  453. bb_error_msg_and_die("bad response to %s: %s", "PASV", sanitize_string(buf));
  454. }
  455. // Response is "227 garbageN1,N2,N3,N4,P1,P2[)garbage]
  456. // Server's IP is N1.N2.N3.N4 (we ignore it)
  457. // Server's port for data connection is P1*256+P2
  458. str = strrchr(buf, ')');
  459. if (str) str[0] = '\0';
  460. str = strrchr(buf, ',');
  461. if (!str) goto pasv_error;
  462. port = xatou_range(str+1, 0, 255);
  463. *str = '\0';
  464. str = strrchr(buf, ',');
  465. if (!str) goto pasv_error;
  466. port += xatou_range(str+1, 0, 255) * 256;
  467. set_nport(lsa, htons(port));
  468. *dfpp = open_socket(lsa);
  469. if (beg_range) {
  470. sprintf(buf, "REST %"OFF_FMT"d", beg_range);
  471. if (ftpcmd(buf, NULL, sfp, buf) == 350)
  472. content_len -= beg_range;
  473. }
  474. if (ftpcmd("RETR ", target->path, sfp, buf) > 150)
  475. bb_error_msg_and_die("bad response to %s: %s", "RETR", sanitize_string(buf));
  476. return sfp;
  477. }
  478. /* Must match option string! */
  479. enum {
  480. WGET_OPT_CONTINUE = (1 << 0),
  481. WGET_OPT_SPIDER = (1 << 1),
  482. WGET_OPT_QUIET = (1 << 2),
  483. WGET_OPT_OUTNAME = (1 << 3),
  484. WGET_OPT_PREFIX = (1 << 4),
  485. WGET_OPT_PROXY = (1 << 5),
  486. WGET_OPT_USER_AGENT = (1 << 6),
  487. WGET_OPT_RETRIES = (1 << 7),
  488. WGET_OPT_NETWORK_READ_TIMEOUT = (1 << 8),
  489. WGET_OPT_PASSIVE = (1 << 9),
  490. WGET_OPT_HEADER = (1 << 10) * ENABLE_FEATURE_WGET_LONG_OPTIONS,
  491. WGET_OPT_POST_DATA = (1 << 11) * ENABLE_FEATURE_WGET_LONG_OPTIONS,
  492. };
  493. static void NOINLINE retrieve_file_data(FILE *dfp, int output_fd)
  494. {
  495. char buf[512];
  496. if (!(option_mask32 & WGET_OPT_QUIET))
  497. progress_meter(-1);
  498. if (G.chunked)
  499. goto get_clen;
  500. /* Loops only if chunked */
  501. while (1) {
  502. while (content_len > 0 || !G.got_clen) {
  503. int n;
  504. unsigned rdsz = sizeof(buf);
  505. if (content_len < sizeof(buf) && (G.chunked || G.got_clen))
  506. rdsz = (unsigned)content_len;
  507. n = safe_fread(buf, rdsz, dfp);
  508. if (n <= 0) {
  509. if (ferror(dfp)) {
  510. /* perror will not work: ferror doesn't set errno */
  511. bb_error_msg_and_die(bb_msg_read_error);
  512. }
  513. break;
  514. }
  515. xwrite(output_fd, buf, n);
  516. #if ENABLE_FEATURE_WGET_STATUSBAR
  517. transferred += n;
  518. #endif
  519. if (G.got_clen)
  520. content_len -= n;
  521. }
  522. if (!G.chunked)
  523. break;
  524. safe_fgets(buf, sizeof(buf), dfp); /* This is a newline */
  525. get_clen:
  526. safe_fgets(buf, sizeof(buf), dfp);
  527. content_len = STRTOOFF(buf, NULL, 16);
  528. /* FIXME: error check? */
  529. if (content_len == 0)
  530. break; /* all done! */
  531. }
  532. if (!(option_mask32 & WGET_OPT_QUIET))
  533. progress_meter(0);
  534. }
  535. int wget_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  536. int wget_main(int argc UNUSED_PARAM, char **argv)
  537. {
  538. char buf[512];
  539. struct host_info server, target;
  540. len_and_sockaddr *lsa;
  541. unsigned opt;
  542. int redir_limit;
  543. char *proxy = NULL;
  544. char *dir_prefix = NULL;
  545. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  546. char *post_data;
  547. char *extra_headers = NULL;
  548. llist_t *headers_llist = NULL;
  549. #endif
  550. FILE *sfp; /* socket to web/ftp server */
  551. FILE *dfp; /* socket to ftp server (data) */
  552. char *fname_out; /* where to direct output (-O) */
  553. int output_fd = -1;
  554. bool use_proxy; /* Use proxies if env vars are set */
  555. const char *proxy_flag = "on"; /* Use proxies if env vars are set */
  556. const char *user_agent = "Wget";/* "User-Agent" header field */
  557. static const char keywords[] ALIGN1 =
  558. "content-length\0""transfer-encoding\0""chunked\0""location\0";
  559. enum {
  560. KEY_content_length = 1, KEY_transfer_encoding, KEY_chunked, KEY_location
  561. };
  562. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  563. static const char wget_longopts[] ALIGN1 =
  564. /* name, has_arg, val */
  565. "continue\0" No_argument "c"
  566. "spider\0" No_argument "s"
  567. "quiet\0" No_argument "q"
  568. "output-document\0" Required_argument "O"
  569. "directory-prefix\0" Required_argument "P"
  570. "proxy\0" Required_argument "Y"
  571. "user-agent\0" Required_argument "U"
  572. /* Ignored: */
  573. // "tries\0" Required_argument "t"
  574. // "timeout\0" Required_argument "T"
  575. /* Ignored (we always use PASV): */
  576. "passive-ftp\0" No_argument "\xff"
  577. "header\0" Required_argument "\xfe"
  578. "post-data\0" Required_argument "\xfd"
  579. ;
  580. #endif
  581. INIT_G();
  582. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  583. applet_long_options = wget_longopts;
  584. #endif
  585. /* server.allocated = target.allocated = NULL; */
  586. opt_complementary = "-1" IF_FEATURE_WGET_LONG_OPTIONS(":\xfe::");
  587. opt = getopt32(argv, "csqO:P:Y:U:" /*ignored:*/ "t:T:",
  588. &fname_out, &dir_prefix,
  589. &proxy_flag, &user_agent,
  590. NULL, /* -t RETRIES */
  591. NULL /* -T NETWORK_READ_TIMEOUT */
  592. IF_FEATURE_WGET_LONG_OPTIONS(, &headers_llist)
  593. IF_FEATURE_WGET_LONG_OPTIONS(, &post_data)
  594. );
  595. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  596. if (headers_llist) {
  597. int size = 1;
  598. char *cp;
  599. llist_t *ll = headers_llist;
  600. while (ll) {
  601. size += strlen(ll->data) + 2;
  602. ll = ll->link;
  603. }
  604. extra_headers = cp = xmalloc(size);
  605. while (headers_llist) {
  606. cp += sprintf(cp, "%s\r\n", (char*)llist_pop(&headers_llist));
  607. }
  608. }
  609. #endif
  610. /* TODO: compat issue: should handle "wget URL1 URL2..." */
  611. parse_url(argv[optind], &target);
  612. /* Use the proxy if necessary */
  613. use_proxy = (strcmp(proxy_flag, "off") != 0);
  614. if (use_proxy) {
  615. proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
  616. if (proxy && proxy[0]) {
  617. parse_url(proxy, &server);
  618. } else {
  619. use_proxy = 0;
  620. }
  621. }
  622. if (!use_proxy) {
  623. server.port = target.port;
  624. if (ENABLE_FEATURE_IPV6) {
  625. server.host = xstrdup(target.host);
  626. } else {
  627. server.host = target.host;
  628. }
  629. }
  630. if (ENABLE_FEATURE_IPV6)
  631. strip_ipv6_scope_id(target.host);
  632. /* Guess an output filename, if there was no -O FILE */
  633. if (!(opt & WGET_OPT_OUTNAME)) {
  634. fname_out = bb_get_last_path_component_nostrip(target.path);
  635. /* handle "wget http://kernel.org//" */
  636. if (fname_out[0] == '/' || !fname_out[0])
  637. fname_out = (char*)"index.html";
  638. /* -P DIR is considered only if there was no -O FILE */
  639. if (dir_prefix)
  640. fname_out = concat_path_file(dir_prefix, fname_out);
  641. } else {
  642. if (LONE_DASH(fname_out)) {
  643. /* -O - */
  644. output_fd = 1;
  645. opt &= ~WGET_OPT_CONTINUE;
  646. }
  647. }
  648. #if ENABLE_FEATURE_WGET_STATUSBAR
  649. curfile = bb_get_last_path_component_nostrip(fname_out);
  650. #endif
  651. /* Impossible?
  652. if ((opt & WGET_OPT_CONTINUE) && !fname_out)
  653. bb_error_msg_and_die("cannot specify continue (-c) without a filename (-O)");
  654. */
  655. /* Determine where to start transfer */
  656. if (opt & WGET_OPT_CONTINUE) {
  657. output_fd = open(fname_out, O_WRONLY);
  658. if (output_fd >= 0) {
  659. beg_range = xlseek(output_fd, 0, SEEK_END);
  660. }
  661. /* File doesn't exist. We do not create file here yet.
  662. * We are not sure it exists on remove side */
  663. }
  664. redir_limit = 5;
  665. resolve_lsa:
  666. lsa = xhost2sockaddr(server.host, server.port);
  667. if (!(opt & WGET_OPT_QUIET)) {
  668. char *s = xmalloc_sockaddr2dotted(&lsa->u.sa);
  669. fprintf(stderr, "Connecting to %s (%s)\n", server.host, s);
  670. free(s);
  671. }
  672. establish_session:
  673. if (use_proxy || !target.is_ftp) {
  674. /*
  675. * HTTP session
  676. */
  677. char *str;
  678. int status;
  679. /* Open socket to http server */
  680. sfp = open_socket(lsa);
  681. /* Send HTTP request */
  682. if (use_proxy) {
  683. fprintf(sfp, "GET %stp://%s/%s HTTP/1.1\r\n",
  684. target.is_ftp ? "f" : "ht", target.host,
  685. target.path);
  686. } else {
  687. if (opt & WGET_OPT_POST_DATA)
  688. fprintf(sfp, "POST /%s HTTP/1.1\r\n", target.path);
  689. else
  690. fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
  691. }
  692. fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n",
  693. target.host, user_agent);
  694. #if ENABLE_FEATURE_WGET_AUTHENTICATION
  695. if (target.user) {
  696. fprintf(sfp, "Proxy-Authorization: Basic %s\r\n"+6,
  697. base64enc_512(buf, target.user));
  698. }
  699. if (use_proxy && server.user) {
  700. fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
  701. base64enc_512(buf, server.user));
  702. }
  703. #endif
  704. if (beg_range)
  705. fprintf(sfp, "Range: bytes=%"OFF_FMT"d-\r\n", beg_range);
  706. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  707. if (extra_headers)
  708. fputs(extra_headers, sfp);
  709. if (opt & WGET_OPT_POST_DATA) {
  710. char *estr = URL_escape(post_data);
  711. fprintf(sfp, "Content-Type: application/x-www-form-urlencoded\r\n");
  712. fprintf(sfp, "Content-Length: %u\r\n" "\r\n" "%s",
  713. (int) strlen(estr), estr);
  714. /*fprintf(sfp, "Connection: Keep-Alive\r\n\r\n");*/
  715. /*fprintf(sfp, "%s\r\n", estr);*/
  716. free(estr);
  717. } else
  718. #endif
  719. { /* If "Connection:" is needed, document why */
  720. fprintf(sfp, /* "Connection: close\r\n" */ "\r\n");
  721. }
  722. /*
  723. * Retrieve HTTP response line and check for "200" status code.
  724. */
  725. read_response:
  726. if (fgets(buf, sizeof(buf), sfp) == NULL)
  727. bb_error_msg_and_die("no response from server");
  728. str = buf;
  729. str = skip_non_whitespace(str);
  730. str = skip_whitespace(str);
  731. // FIXME: no error check
  732. // xatou wouldn't work: "200 OK"
  733. status = atoi(str);
  734. switch (status) {
  735. case 0:
  736. case 100:
  737. while (gethdr(buf, sizeof(buf), sfp /*, &n*/) != NULL)
  738. /* eat all remaining headers */;
  739. goto read_response;
  740. case 200:
  741. /*
  742. Response 204 doesn't say "null file", it says "metadata
  743. has changed but data didn't":
  744. "10.2.5 204 No Content
  745. The server has fulfilled the request but does not need to return
  746. an entity-body, and might want to return updated metainformation.
  747. The response MAY include new or updated metainformation in the form
  748. of entity-headers, which if present SHOULD be associated with
  749. the requested variant.
  750. If the client is a user agent, it SHOULD NOT change its document
  751. view from that which caused the request to be sent. This response
  752. is primarily intended to allow input for actions to take place
  753. without causing a change to the user agent's active document view,
  754. although any new or updated metainformation SHOULD be applied
  755. to the document currently in the user agent's active view.
  756. The 204 response MUST NOT include a message-body, and thus
  757. is always terminated by the first empty line after the header fields."
  758. However, in real world it was observed that some web servers
  759. (e.g. Boa/0.94.14rc21) simply use code 204 when file size is zero.
  760. */
  761. case 204:
  762. break;
  763. case 300: /* redirection */
  764. case 301:
  765. case 302:
  766. case 303:
  767. break;
  768. case 206:
  769. if (beg_range)
  770. break;
  771. /* fall through */
  772. default:
  773. bb_error_msg_and_die("server returned error: %s", sanitize_string(buf));
  774. }
  775. /*
  776. * Retrieve HTTP headers.
  777. */
  778. while ((str = gethdr(buf, sizeof(buf), sfp /*, &n*/)) != NULL) {
  779. /* gethdr converted "FOO:" string to lowercase */
  780. smalluint key = index_in_strings(keywords, buf) + 1;
  781. if (key == KEY_content_length) {
  782. content_len = BB_STRTOOFF(str, NULL, 10);
  783. if (errno || content_len < 0) {
  784. bb_error_msg_and_die("content-length %s is garbage", sanitize_string(str));
  785. }
  786. G.got_clen = 1;
  787. continue;
  788. }
  789. if (key == KEY_transfer_encoding) {
  790. if (index_in_strings(keywords, str_tolower(str)) + 1 != KEY_chunked)
  791. bb_error_msg_and_die("transfer encoding '%s' is not supported", sanitize_string(str));
  792. G.chunked = G.got_clen = 1;
  793. }
  794. if (key == KEY_location && status >= 300) {
  795. if (--redir_limit == 0)
  796. bb_error_msg_and_die("too many redirections");
  797. fclose(sfp);
  798. G.got_clen = 0;
  799. G.chunked = 0;
  800. if (str[0] == '/')
  801. /* free(target.allocated); */
  802. target.path = /* target.allocated = */ xstrdup(str+1);
  803. /* lsa stays the same: it's on the same server */
  804. else {
  805. parse_url(str, &target);
  806. if (!use_proxy) {
  807. server.host = target.host;
  808. /* strip_ipv6_scope_id(target.host); - no! */
  809. /* we assume remote never gives us IPv6 addr with scope id */
  810. server.port = target.port;
  811. free(lsa);
  812. goto resolve_lsa;
  813. } /* else: lsa stays the same: we use proxy */
  814. }
  815. goto establish_session;
  816. }
  817. }
  818. // if (status >= 300)
  819. // bb_error_msg_and_die("bad redirection (no Location: header from server)");
  820. /* For HTTP, data is pumped over the same connection */
  821. dfp = sfp;
  822. } else {
  823. /*
  824. * FTP session
  825. */
  826. sfp = prepare_ftp_session(&dfp, &target, lsa);
  827. }
  828. if (opt & WGET_OPT_SPIDER) {
  829. if (ENABLE_FEATURE_CLEAN_UP)
  830. fclose(sfp);
  831. return EXIT_SUCCESS;
  832. }
  833. if (output_fd < 0) {
  834. int o_flags = O_WRONLY | O_CREAT | O_TRUNC | O_EXCL;
  835. /* compat with wget: -O FILE can overwrite */
  836. if (opt & WGET_OPT_OUTNAME)
  837. o_flags = O_WRONLY | O_CREAT | O_TRUNC;
  838. output_fd = xopen(fname_out, o_flags);
  839. }
  840. retrieve_file_data(dfp, output_fd);
  841. if (dfp != sfp) {
  842. /* It's ftp. Close it properly */
  843. fclose(dfp);
  844. if (ftpcmd(NULL, NULL, sfp, buf) != 226)
  845. bb_error_msg_and_die("ftp error: %s", sanitize_string(buf+4));
  846. ftpcmd("QUIT", NULL, sfp, buf);
  847. }
  848. return EXIT_SUCCESS;
  849. }