3
0

wget.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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. * Licensed under GPLv2, see file LICENSE in this source tree.
  7. *
  8. * Copyright (C) 2010 Bradley M. Kuhn <bkuhn@ebb.org>
  9. * Kuhn's copyrights are licensed GPLv2-or-later. File as a whole remains GPLv2.
  10. */
  11. //usage:#define wget_trivial_usage
  12. //usage: IF_FEATURE_WGET_LONG_OPTIONS(
  13. //usage: "[-c|--continue] [-s|--spider] [-q|--quiet] [-O|--output-document FILE]\n"
  14. //usage: " [--header 'header: value'] [-Y|--proxy on/off] [-P DIR]\n"
  15. /* Since we ignore these opts, we don't show them in --help */
  16. /* //usage: " [--no-check-certificate] [--no-cache]" */
  17. //usage: " [-U|--user-agent AGENT]" IF_FEATURE_WGET_TIMEOUT(" [-T SEC]") " URL..."
  18. //usage: )
  19. //usage: IF_NOT_FEATURE_WGET_LONG_OPTIONS(
  20. //usage: "[-csq] [-O FILE] [-Y on/off] [-P DIR] [-U AGENT]"
  21. //usage: IF_FEATURE_WGET_TIMEOUT(" [-T SEC]") " URL..."
  22. //usage: )
  23. //usage:#define wget_full_usage "\n\n"
  24. //usage: "Retrieve files via HTTP or FTP\n"
  25. //usage: "\n -s Spider mode - only check file existence"
  26. //usage: "\n -c Continue retrieval of aborted transfer"
  27. //usage: "\n -q Quiet"
  28. //usage: "\n -P DIR Save to DIR (default .)"
  29. //usage: IF_FEATURE_WGET_TIMEOUT(
  30. //usage: "\n -T SEC Network read timeout is SEC seconds"
  31. //usage: )
  32. //usage: "\n -O FILE Save to FILE ('-' for stdout)"
  33. //usage: "\n -U STR Use STR for User-Agent header"
  34. //usage: "\n -Y Use proxy ('on' or 'off')"
  35. #include "libbb.h"
  36. #if 0
  37. # define log_io(...) bb_error_msg(__VA_ARGS__)
  38. #else
  39. # define log_io(...) ((void)0)
  40. #endif
  41. struct host_info {
  42. char *allocated;
  43. const char *path;
  44. const char *user;
  45. char *host;
  46. int port;
  47. smallint is_ftp;
  48. };
  49. /* Globals */
  50. struct globals {
  51. off_t content_len; /* Content-length of the file */
  52. off_t beg_range; /* Range at which continue begins */
  53. #if ENABLE_FEATURE_WGET_STATUSBAR
  54. off_t transferred; /* Number of bytes transferred so far */
  55. const char *curfile; /* Name of current file being transferred */
  56. bb_progress_t pmt;
  57. #endif
  58. char *dir_prefix;
  59. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  60. char *post_data;
  61. char *extra_headers;
  62. #endif
  63. char *fname_out; /* where to direct output (-O) */
  64. const char *proxy_flag; /* Use proxies if env vars are set */
  65. const char *user_agent; /* "User-Agent" header field */
  66. #if ENABLE_FEATURE_WGET_TIMEOUT
  67. unsigned timeout_seconds;
  68. #endif
  69. int output_fd;
  70. int o_flags;
  71. smallint chunked; /* chunked transfer encoding */
  72. smallint got_clen; /* got content-length: from server */
  73. /* Local downloads do benefit from big buffer.
  74. * With 512 byte buffer, it was measured to be
  75. * an order of magnitude slower than with big one.
  76. */
  77. uint64_t just_to_align_next_member;
  78. char wget_buf[CONFIG_FEATURE_COPYBUF_KB*1024];
  79. } FIX_ALIASING;
  80. #define G (*ptr_to_globals)
  81. #define INIT_G() do { \
  82. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  83. IF_FEATURE_WGET_TIMEOUT(G.timeout_seconds = 900;) \
  84. } while (0)
  85. /* Must match option string! */
  86. enum {
  87. WGET_OPT_CONTINUE = (1 << 0),
  88. WGET_OPT_SPIDER = (1 << 1),
  89. WGET_OPT_QUIET = (1 << 2),
  90. WGET_OPT_OUTNAME = (1 << 3),
  91. WGET_OPT_PREFIX = (1 << 4),
  92. WGET_OPT_PROXY = (1 << 5),
  93. WGET_OPT_USER_AGENT = (1 << 6),
  94. WGET_OPT_NETWORK_READ_TIMEOUT = (1 << 7),
  95. WGET_OPT_RETRIES = (1 << 8),
  96. WGET_OPT_PASSIVE = (1 << 9),
  97. WGET_OPT_HEADER = (1 << 10) * ENABLE_FEATURE_WGET_LONG_OPTIONS,
  98. WGET_OPT_POST_DATA = (1 << 11) * ENABLE_FEATURE_WGET_LONG_OPTIONS,
  99. };
  100. enum {
  101. PROGRESS_START = -1,
  102. PROGRESS_END = 0,
  103. PROGRESS_BUMP = 1,
  104. };
  105. #if ENABLE_FEATURE_WGET_STATUSBAR
  106. static void progress_meter(int flag)
  107. {
  108. if (option_mask32 & WGET_OPT_QUIET)
  109. return;
  110. if (flag == PROGRESS_START)
  111. bb_progress_init(&G.pmt, G.curfile);
  112. bb_progress_update(&G.pmt,
  113. G.beg_range,
  114. G.transferred,
  115. (G.chunked || !G.got_clen) ? 0 : G.beg_range + G.transferred + G.content_len
  116. );
  117. if (flag == PROGRESS_END) {
  118. bb_progress_free(&G.pmt);
  119. bb_putchar_stderr('\n');
  120. G.transferred = 0;
  121. }
  122. }
  123. #else
  124. static ALWAYS_INLINE void progress_meter(int flag UNUSED_PARAM) { }
  125. #endif
  126. /* IPv6 knows scoped address types i.e. link and site local addresses. Link
  127. * local addresses can have a scope identifier to specify the
  128. * interface/link an address is valid on (e.g. fe80::1%eth0). This scope
  129. * identifier is only valid on a single node.
  130. *
  131. * RFC 4007 says that the scope identifier MUST NOT be sent across the wire,
  132. * unless all nodes agree on the semantic. Apache e.g. regards zone identifiers
  133. * in the Host header as invalid requests, see
  134. * https://issues.apache.org/bugzilla/show_bug.cgi?id=35122
  135. */
  136. static void strip_ipv6_scope_id(char *host)
  137. {
  138. char *scope, *cp;
  139. /* bbox wget actually handles IPv6 addresses without [], like
  140. * wget "http://::1/xxx", but this is not standard.
  141. * To save code, _here_ we do not support it. */
  142. if (host[0] != '[')
  143. return; /* not IPv6 */
  144. scope = strchr(host, '%');
  145. if (!scope)
  146. return;
  147. /* Remove the IPv6 zone identifier from the host address */
  148. cp = strchr(host, ']');
  149. if (!cp || (cp[1] != ':' && cp[1] != '\0')) {
  150. /* malformed address (not "[xx]:nn" or "[xx]") */
  151. return;
  152. }
  153. /* cp points to "]...", scope points to "%eth0]..." */
  154. overlapping_strcpy(scope, cp);
  155. }
  156. #if ENABLE_FEATURE_WGET_AUTHENTICATION
  157. /* Base64-encode character string. */
  158. static char *base64enc(const char *str)
  159. {
  160. unsigned len = strlen(str);
  161. if (len > sizeof(G.wget_buf)/4*3 - 10) /* paranoia */
  162. len = sizeof(G.wget_buf)/4*3 - 10;
  163. bb_uuencode(G.wget_buf, str, len, bb_uuenc_tbl_base64);
  164. return G.wget_buf;
  165. }
  166. #endif
  167. static char* sanitize_string(char *s)
  168. {
  169. unsigned char *p = (void *) s;
  170. while (*p >= ' ')
  171. p++;
  172. *p = '\0';
  173. return s;
  174. }
  175. static FILE *open_socket(len_and_sockaddr *lsa)
  176. {
  177. FILE *fp;
  178. /* glibc 2.4 seems to try seeking on it - ??! */
  179. /* hopefully it understands what ESPIPE means... */
  180. fp = fdopen(xconnect_stream(lsa), "r+");
  181. if (fp == NULL)
  182. bb_perror_msg_and_die(bb_msg_memory_exhausted);
  183. return fp;
  184. }
  185. /* Returns '\n' if it was seen, else '\0'. Trims at first '\r' or '\n' */
  186. static char fgets_and_trim(FILE *fp)
  187. {
  188. char c;
  189. char *buf_ptr;
  190. if (fgets(G.wget_buf, sizeof(G.wget_buf) - 1, fp) == NULL)
  191. bb_perror_msg_and_die("error getting response");
  192. buf_ptr = strchrnul(G.wget_buf, '\n');
  193. c = *buf_ptr;
  194. *buf_ptr = '\0';
  195. buf_ptr = strchrnul(G.wget_buf, '\r');
  196. *buf_ptr = '\0';
  197. log_io("< %s", G.wget_buf);
  198. return c;
  199. }
  200. static int ftpcmd(const char *s1, const char *s2, FILE *fp)
  201. {
  202. int result;
  203. if (s1) {
  204. if (!s2)
  205. s2 = "";
  206. fprintf(fp, "%s%s\r\n", s1, s2);
  207. fflush(fp);
  208. log_io("> %s%s", s1, s2);
  209. }
  210. do {
  211. fgets_and_trim(fp);
  212. } while (!isdigit(G.wget_buf[0]) || G.wget_buf[3] != ' ');
  213. G.wget_buf[3] = '\0';
  214. result = xatoi_positive(G.wget_buf);
  215. G.wget_buf[3] = ' ';
  216. return result;
  217. }
  218. static void parse_url(const char *src_url, struct host_info *h)
  219. {
  220. char *url, *p, *sp;
  221. free(h->allocated);
  222. h->allocated = url = xstrdup(src_url);
  223. if (strncmp(url, "http://", 7) == 0) {
  224. h->port = bb_lookup_port("http", "tcp", 80);
  225. h->host = url + 7;
  226. h->is_ftp = 0;
  227. } else if (strncmp(url, "ftp://", 6) == 0) {
  228. h->port = bb_lookup_port("ftp", "tcp", 21);
  229. h->host = url + 6;
  230. h->is_ftp = 1;
  231. } else
  232. bb_error_msg_and_die("not an http or ftp url: %s", sanitize_string(url));
  233. // FYI:
  234. // "Real" wget 'http://busybox.net?var=a/b' sends this request:
  235. // 'GET /?var=a/b HTTP 1.0'
  236. // and saves 'index.html?var=a%2Fb' (we save 'b')
  237. // wget 'http://busybox.net?login=john@doe':
  238. // request: 'GET /?login=john@doe HTTP/1.0'
  239. // saves: 'index.html?login=john@doe' (we save '?login=john@doe')
  240. // wget 'http://busybox.net#test/test':
  241. // request: 'GET / HTTP/1.0'
  242. // saves: 'index.html' (we save 'test')
  243. //
  244. // We also don't add unique .N suffix if file exists...
  245. sp = strchr(h->host, '/');
  246. p = strchr(h->host, '?'); if (!sp || (p && sp > p)) sp = p;
  247. p = strchr(h->host, '#'); if (!sp || (p && sp > p)) sp = p;
  248. if (!sp) {
  249. h->path = "";
  250. } else if (*sp == '/') {
  251. *sp = '\0';
  252. h->path = sp + 1;
  253. } else { // '#' or '?'
  254. // http://busybox.net?login=john@doe is a valid URL
  255. // memmove converts to:
  256. // http:/busybox.nett?login=john@doe...
  257. memmove(h->host - 1, h->host, sp - h->host);
  258. h->host--;
  259. sp[-1] = '\0';
  260. h->path = sp;
  261. }
  262. // We used to set h->user to NULL here, but this interferes
  263. // with handling of code 302 ("object was moved")
  264. sp = strrchr(h->host, '@');
  265. if (sp != NULL) {
  266. // URL-decode "user:password" string before base64-encoding:
  267. // wget http://test:my%20pass@example.com should send
  268. // Authorization: Basic dGVzdDpteSBwYXNz
  269. // which decodes to "test:my pass".
  270. // Standard wget and curl do this too.
  271. *sp = '\0';
  272. h->user = percent_decode_in_place(h->host, /*strict:*/ 0);
  273. h->host = sp + 1;
  274. }
  275. sp = h->host;
  276. }
  277. static char *gethdr(FILE *fp)
  278. {
  279. char *s, *hdrval;
  280. int c;
  281. /* retrieve header line */
  282. c = fgets_and_trim(fp);
  283. /* end of the headers? */
  284. if (G.wget_buf[0] == '\0')
  285. return NULL;
  286. /* convert the header name to lower case */
  287. for (s = G.wget_buf; isalnum(*s) || *s == '-' || *s == '.'; ++s) {
  288. /* tolower for "A-Z", no-op for "0-9a-z-." */
  289. *s |= 0x20;
  290. }
  291. /* verify we are at the end of the header name */
  292. if (*s != ':')
  293. bb_error_msg_and_die("bad header line: %s", sanitize_string(G.wget_buf));
  294. /* locate the start of the header value */
  295. *s++ = '\0';
  296. hdrval = skip_whitespace(s);
  297. if (c != '\n') {
  298. /* Rats! The buffer isn't big enough to hold the entire header value */
  299. while (c = getc(fp), c != EOF && c != '\n')
  300. continue;
  301. }
  302. return hdrval;
  303. }
  304. static void reset_beg_range_to_zero(void)
  305. {
  306. bb_error_msg("restart failed");
  307. G.beg_range = 0;
  308. xlseek(G.output_fd, 0, SEEK_SET);
  309. /* Done at the end instead: */
  310. /* ftruncate(G.output_fd, 0); */
  311. }
  312. static FILE* prepare_ftp_session(FILE **dfpp, struct host_info *target, len_and_sockaddr *lsa)
  313. {
  314. FILE *sfp;
  315. char *str;
  316. int port;
  317. if (!target->user)
  318. target->user = xstrdup("anonymous:busybox@");
  319. sfp = open_socket(lsa);
  320. if (ftpcmd(NULL, NULL, sfp) != 220)
  321. bb_error_msg_and_die("%s", sanitize_string(G.wget_buf + 4));
  322. /*
  323. * Splitting username:password pair,
  324. * trying to log in
  325. */
  326. str = strchr(target->user, ':');
  327. if (str)
  328. *str++ = '\0';
  329. switch (ftpcmd("USER ", target->user, sfp)) {
  330. case 230:
  331. break;
  332. case 331:
  333. if (ftpcmd("PASS ", str, sfp) == 230)
  334. break;
  335. /* fall through (failed login) */
  336. default:
  337. bb_error_msg_and_die("ftp login: %s", sanitize_string(G.wget_buf + 4));
  338. }
  339. ftpcmd("TYPE I", NULL, sfp);
  340. /*
  341. * Querying file size
  342. */
  343. if (ftpcmd("SIZE ", target->path, sfp) == 213) {
  344. G.content_len = BB_STRTOOFF(G.wget_buf + 4, NULL, 10);
  345. if (G.content_len < 0 || errno) {
  346. bb_error_msg_and_die("SIZE value is garbage");
  347. }
  348. G.got_clen = 1;
  349. }
  350. /*
  351. * Entering passive mode
  352. */
  353. if (ftpcmd("PASV", NULL, sfp) != 227) {
  354. pasv_error:
  355. bb_error_msg_and_die("bad response to %s: %s", "PASV", sanitize_string(G.wget_buf));
  356. }
  357. // Response is "227 garbageN1,N2,N3,N4,P1,P2[)garbage]
  358. // Server's IP is N1.N2.N3.N4 (we ignore it)
  359. // Server's port for data connection is P1*256+P2
  360. str = strrchr(G.wget_buf, ')');
  361. if (str) str[0] = '\0';
  362. str = strrchr(G.wget_buf, ',');
  363. if (!str) goto pasv_error;
  364. port = xatou_range(str+1, 0, 255);
  365. *str = '\0';
  366. str = strrchr(G.wget_buf, ',');
  367. if (!str) goto pasv_error;
  368. port += xatou_range(str+1, 0, 255) * 256;
  369. set_nport(&lsa->u.sa, htons(port));
  370. *dfpp = open_socket(lsa);
  371. if (G.beg_range != 0) {
  372. sprintf(G.wget_buf, "REST %"OFF_FMT"u", G.beg_range);
  373. if (ftpcmd(G.wget_buf, NULL, sfp) == 350)
  374. G.content_len -= G.beg_range;
  375. else
  376. reset_beg_range_to_zero();
  377. }
  378. if (ftpcmd("RETR ", target->path, sfp) > 150)
  379. bb_error_msg_and_die("bad response to %s: %s", "RETR", sanitize_string(G.wget_buf));
  380. return sfp;
  381. }
  382. static void NOINLINE retrieve_file_data(FILE *dfp)
  383. {
  384. #if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
  385. # if ENABLE_FEATURE_WGET_TIMEOUT
  386. unsigned second_cnt = G.timeout_seconds;
  387. # endif
  388. struct pollfd polldata;
  389. polldata.fd = fileno(dfp);
  390. polldata.events = POLLIN | POLLPRI;
  391. #endif
  392. progress_meter(PROGRESS_START);
  393. if (G.chunked)
  394. goto get_clen;
  395. /* Loops only if chunked */
  396. while (1) {
  397. #if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
  398. /* Must use nonblocking I/O, otherwise fread will loop
  399. * and *block* until it reads full buffer,
  400. * which messes up progress bar and/or timeout logic.
  401. * Because of nonblocking I/O, we need to dance
  402. * very carefully around EAGAIN. See explanation at
  403. * clearerr() calls.
  404. */
  405. ndelay_on(polldata.fd);
  406. #endif
  407. while (1) {
  408. int n;
  409. unsigned rdsz;
  410. #if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
  411. /* fread internally uses read loop, which in our case
  412. * is usually exited when we get EAGAIN.
  413. * In this case, libc sets error marker on the stream.
  414. * Need to clear it before next fread to avoid possible
  415. * rare false positive ferror below. Rare because usually
  416. * fread gets more than zero bytes, and we don't fall
  417. * into if (n <= 0) ...
  418. */
  419. clearerr(dfp);
  420. #endif
  421. errno = 0;
  422. rdsz = sizeof(G.wget_buf);
  423. if (G.got_clen) {
  424. if (G.content_len < (off_t)sizeof(G.wget_buf)) {
  425. if ((int)G.content_len <= 0)
  426. break;
  427. rdsz = (unsigned)G.content_len;
  428. }
  429. }
  430. n = fread(G.wget_buf, 1, rdsz, dfp);
  431. if (n > 0) {
  432. xwrite(G.output_fd, G.wget_buf, n);
  433. #if ENABLE_FEATURE_WGET_STATUSBAR
  434. G.transferred += n;
  435. #endif
  436. if (G.got_clen) {
  437. G.content_len -= n;
  438. if (G.content_len == 0)
  439. break;
  440. }
  441. #if ENABLE_FEATURE_WGET_TIMEOUT
  442. second_cnt = G.timeout_seconds;
  443. #endif
  444. continue;
  445. }
  446. /* n <= 0.
  447. * man fread:
  448. * If error occurs, or EOF is reached, the return value
  449. * is a short item count (or zero).
  450. * fread does not distinguish between EOF and error.
  451. */
  452. if (errno != EAGAIN) {
  453. if (ferror(dfp)) {
  454. progress_meter(PROGRESS_END);
  455. bb_perror_msg_and_die(bb_msg_read_error);
  456. }
  457. break; /* EOF, not error */
  458. }
  459. #if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
  460. /* It was EAGAIN. There is no data. Wait up to one second
  461. * then abort if timed out, or update the bar and try reading again.
  462. */
  463. if (safe_poll(&polldata, 1, 1000) == 0) {
  464. # if ENABLE_FEATURE_WGET_TIMEOUT
  465. if (second_cnt != 0 && --second_cnt == 0) {
  466. progress_meter(PROGRESS_END);
  467. bb_error_msg_and_die("download timed out");
  468. }
  469. # endif
  470. /* We used to loop back to poll here,
  471. * but there is no great harm in letting fread
  472. * to try reading anyway.
  473. */
  474. }
  475. /* Need to do it _every_ second for "stalled" indicator
  476. * to be shown properly.
  477. */
  478. progress_meter(PROGRESS_BUMP);
  479. #endif
  480. } /* while (reading data) */
  481. #if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
  482. clearerr(dfp);
  483. ndelay_off(polldata.fd); /* else fgets can get very unhappy */
  484. #endif
  485. if (!G.chunked)
  486. break;
  487. fgets_and_trim(dfp); /* Eat empty line */
  488. get_clen:
  489. fgets_and_trim(dfp);
  490. G.content_len = STRTOOFF(G.wget_buf, NULL, 16);
  491. /* FIXME: error check? */
  492. if (G.content_len == 0)
  493. break; /* all done! */
  494. G.got_clen = 1;
  495. /*
  496. * Note that fgets may result in some data being buffered in dfp.
  497. * We loop back to fread, which will retrieve this data.
  498. * Also note that code has to be arranged so that fread
  499. * is done _before_ one-second poll wait - poll doesn't know
  500. * about stdio buffering and can result in spurious one second waits!
  501. */
  502. }
  503. /* If -c failed, we restart from the beginning,
  504. * but we do not truncate file then, we do it only now, at the end.
  505. * This lets user to ^C if his 99% complete 10 GB file download
  506. * failed to restart *without* losing the almost complete file.
  507. */
  508. {
  509. off_t pos = lseek(G.output_fd, 0, SEEK_CUR);
  510. if (pos != (off_t)-1)
  511. ftruncate(G.output_fd, pos);
  512. }
  513. /* Draw full bar and free its resources */
  514. G.chunked = 0; /* makes it show 100% even for chunked download */
  515. G.got_clen = 1; /* makes it show 100% even for download of (formerly) unknown size */
  516. progress_meter(PROGRESS_END);
  517. }
  518. static void download_one_url(const char *url)
  519. {
  520. bool use_proxy; /* Use proxies if env vars are set */
  521. int redir_limit;
  522. len_and_sockaddr *lsa;
  523. FILE *sfp; /* socket to web/ftp server */
  524. FILE *dfp; /* socket to ftp server (data) */
  525. char *proxy = NULL;
  526. char *fname_out_alloc;
  527. char *redirected_path = NULL;
  528. struct host_info server;
  529. struct host_info target;
  530. server.allocated = NULL;
  531. target.allocated = NULL;
  532. server.user = NULL;
  533. target.user = NULL;
  534. parse_url(url, &target);
  535. /* Use the proxy if necessary */
  536. use_proxy = (strcmp(G.proxy_flag, "off") != 0);
  537. if (use_proxy) {
  538. proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
  539. use_proxy = (proxy && proxy[0]);
  540. if (use_proxy)
  541. parse_url(proxy, &server);
  542. }
  543. if (!use_proxy) {
  544. server.port = target.port;
  545. if (ENABLE_FEATURE_IPV6) {
  546. //free(server.allocated); - can't be non-NULL
  547. server.host = server.allocated = xstrdup(target.host);
  548. } else {
  549. server.host = target.host;
  550. }
  551. }
  552. if (ENABLE_FEATURE_IPV6)
  553. strip_ipv6_scope_id(target.host);
  554. /* If there was no -O FILE, guess output filename */
  555. fname_out_alloc = NULL;
  556. if (!(option_mask32 & WGET_OPT_OUTNAME)) {
  557. G.fname_out = bb_get_last_path_component_nostrip(target.path);
  558. /* handle "wget http://kernel.org//" */
  559. if (G.fname_out[0] == '/' || !G.fname_out[0])
  560. G.fname_out = (char*)"index.html";
  561. /* -P DIR is considered only if there was no -O FILE */
  562. if (G.dir_prefix)
  563. G.fname_out = fname_out_alloc = concat_path_file(G.dir_prefix, G.fname_out);
  564. else {
  565. /* redirects may free target.path later, need to make a copy */
  566. G.fname_out = fname_out_alloc = xstrdup(G.fname_out);
  567. }
  568. }
  569. #if ENABLE_FEATURE_WGET_STATUSBAR
  570. G.curfile = bb_get_last_path_component_nostrip(G.fname_out);
  571. #endif
  572. /* Determine where to start transfer */
  573. G.beg_range = 0;
  574. if (option_mask32 & WGET_OPT_CONTINUE) {
  575. G.output_fd = open(G.fname_out, O_WRONLY);
  576. if (G.output_fd >= 0) {
  577. G.beg_range = xlseek(G.output_fd, 0, SEEK_END);
  578. }
  579. /* File doesn't exist. We do not create file here yet.
  580. * We are not sure it exists on remote side */
  581. }
  582. redir_limit = 5;
  583. resolve_lsa:
  584. lsa = xhost2sockaddr(server.host, server.port);
  585. if (!(option_mask32 & WGET_OPT_QUIET)) {
  586. char *s = xmalloc_sockaddr2dotted(&lsa->u.sa);
  587. fprintf(stderr, "Connecting to %s (%s)\n", server.host, s);
  588. free(s);
  589. }
  590. establish_session:
  591. /*G.content_len = 0; - redundant, got_clen = 0 is enough */
  592. G.got_clen = 0;
  593. G.chunked = 0;
  594. if (use_proxy || !target.is_ftp) {
  595. /*
  596. * HTTP session
  597. */
  598. char *str;
  599. int status;
  600. /* Open socket to http server */
  601. sfp = open_socket(lsa);
  602. /* Send HTTP request */
  603. if (use_proxy) {
  604. fprintf(sfp, "GET %stp://%s/%s HTTP/1.1\r\n",
  605. target.is_ftp ? "f" : "ht", target.host,
  606. target.path);
  607. } else {
  608. if (option_mask32 & WGET_OPT_POST_DATA)
  609. fprintf(sfp, "POST /%s HTTP/1.1\r\n", target.path);
  610. else
  611. fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
  612. }
  613. fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n",
  614. target.host, G.user_agent);
  615. /* Ask server to close the connection as soon as we are done
  616. * (IOW: we do not intend to send more requests)
  617. */
  618. fprintf(sfp, "Connection: close\r\n");
  619. #if ENABLE_FEATURE_WGET_AUTHENTICATION
  620. if (target.user) {
  621. fprintf(sfp, "Proxy-Authorization: Basic %s\r\n"+6,
  622. base64enc(target.user));
  623. }
  624. if (use_proxy && server.user) {
  625. fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
  626. base64enc(server.user));
  627. }
  628. #endif
  629. if (G.beg_range != 0)
  630. fprintf(sfp, "Range: bytes=%"OFF_FMT"u-\r\n", G.beg_range);
  631. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  632. if (G.extra_headers)
  633. fputs(G.extra_headers, sfp);
  634. if (option_mask32 & WGET_OPT_POST_DATA) {
  635. fprintf(sfp,
  636. "Content-Type: application/x-www-form-urlencoded\r\n"
  637. "Content-Length: %u\r\n"
  638. "\r\n"
  639. "%s",
  640. (int) strlen(G.post_data), G.post_data
  641. );
  642. } else
  643. #endif
  644. {
  645. fprintf(sfp, "\r\n");
  646. }
  647. fflush(sfp);
  648. /*
  649. * Retrieve HTTP response line and check for "200" status code.
  650. */
  651. read_response:
  652. fgets_and_trim(sfp);
  653. str = G.wget_buf;
  654. str = skip_non_whitespace(str);
  655. str = skip_whitespace(str);
  656. // FIXME: no error check
  657. // xatou wouldn't work: "200 OK"
  658. status = atoi(str);
  659. switch (status) {
  660. case 0:
  661. case 100:
  662. while (gethdr(sfp) != NULL)
  663. /* eat all remaining headers */;
  664. goto read_response;
  665. case 200:
  666. /*
  667. Response 204 doesn't say "null file", it says "metadata
  668. has changed but data didn't":
  669. "10.2.5 204 No Content
  670. The server has fulfilled the request but does not need to return
  671. an entity-body, and might want to return updated metainformation.
  672. The response MAY include new or updated metainformation in the form
  673. of entity-headers, which if present SHOULD be associated with
  674. the requested variant.
  675. If the client is a user agent, it SHOULD NOT change its document
  676. view from that which caused the request to be sent. This response
  677. is primarily intended to allow input for actions to take place
  678. without causing a change to the user agent's active document view,
  679. although any new or updated metainformation SHOULD be applied
  680. to the document currently in the user agent's active view.
  681. The 204 response MUST NOT include a message-body, and thus
  682. is always terminated by the first empty line after the header fields."
  683. However, in real world it was observed that some web servers
  684. (e.g. Boa/0.94.14rc21) simply use code 204 when file size is zero.
  685. */
  686. case 204:
  687. if (G.beg_range != 0) {
  688. /* "Range:..." was not honored by the server.
  689. * Restart download from the beginning.
  690. */
  691. reset_beg_range_to_zero();
  692. }
  693. break;
  694. case 300: /* redirection */
  695. case 301:
  696. case 302:
  697. case 303:
  698. break;
  699. case 206: /* Partial Content */
  700. if (G.beg_range != 0)
  701. /* "Range:..." worked. Good. */
  702. break;
  703. /* Partial Content even though we did not ask for it??? */
  704. /* fall through */
  705. default:
  706. bb_error_msg_and_die("server returned error: %s", sanitize_string(G.wget_buf));
  707. }
  708. /*
  709. * Retrieve HTTP headers.
  710. */
  711. while ((str = gethdr(sfp)) != NULL) {
  712. static const char keywords[] ALIGN1 =
  713. "content-length\0""transfer-encoding\0""location\0";
  714. enum {
  715. KEY_content_length = 1, KEY_transfer_encoding, KEY_location
  716. };
  717. smalluint key;
  718. /* gethdr converted "FOO:" string to lowercase */
  719. /* strip trailing whitespace */
  720. char *s = strchrnul(str, '\0') - 1;
  721. while (s >= str && (*s == ' ' || *s == '\t')) {
  722. *s = '\0';
  723. s--;
  724. }
  725. key = index_in_strings(keywords, G.wget_buf) + 1;
  726. if (key == KEY_content_length) {
  727. G.content_len = BB_STRTOOFF(str, NULL, 10);
  728. if (G.content_len < 0 || errno) {
  729. bb_error_msg_and_die("content-length %s is garbage", sanitize_string(str));
  730. }
  731. G.got_clen = 1;
  732. continue;
  733. }
  734. if (key == KEY_transfer_encoding) {
  735. if (strcmp(str_tolower(str), "chunked") != 0)
  736. bb_error_msg_and_die("transfer encoding '%s' is not supported", sanitize_string(str));
  737. G.chunked = 1;
  738. }
  739. if (key == KEY_location && status >= 300) {
  740. if (--redir_limit == 0)
  741. bb_error_msg_and_die("too many redirections");
  742. fclose(sfp);
  743. if (str[0] == '/') {
  744. free(redirected_path);
  745. target.path = redirected_path = xstrdup(str+1);
  746. /* lsa stays the same: it's on the same server */
  747. } else {
  748. parse_url(str, &target);
  749. if (!use_proxy) {
  750. free(server.allocated);
  751. server.allocated = NULL;
  752. server.host = target.host;
  753. /* strip_ipv6_scope_id(target.host); - no! */
  754. /* we assume remote never gives us IPv6 addr with scope id */
  755. server.port = target.port;
  756. free(lsa);
  757. goto resolve_lsa;
  758. } /* else: lsa stays the same: we use proxy */
  759. }
  760. goto establish_session;
  761. }
  762. }
  763. // if (status >= 300)
  764. // bb_error_msg_and_die("bad redirection (no Location: header from server)");
  765. /* For HTTP, data is pumped over the same connection */
  766. dfp = sfp;
  767. } else {
  768. /*
  769. * FTP session
  770. */
  771. sfp = prepare_ftp_session(&dfp, &target, lsa);
  772. }
  773. free(lsa);
  774. if (!(option_mask32 & WGET_OPT_SPIDER)) {
  775. if (G.output_fd < 0)
  776. G.output_fd = xopen(G.fname_out, G.o_flags);
  777. retrieve_file_data(dfp);
  778. if (!(option_mask32 & WGET_OPT_OUTNAME)) {
  779. xclose(G.output_fd);
  780. G.output_fd = -1;
  781. }
  782. }
  783. if (dfp != sfp) {
  784. /* It's ftp. Close data connection properly */
  785. fclose(dfp);
  786. if (ftpcmd(NULL, NULL, sfp) != 226)
  787. bb_error_msg_and_die("ftp error: %s", sanitize_string(G.wget_buf + 4));
  788. /* ftpcmd("QUIT", NULL, sfp); - why bother? */
  789. }
  790. fclose(sfp);
  791. free(server.allocated);
  792. free(target.allocated);
  793. free(fname_out_alloc);
  794. free(redirected_path);
  795. }
  796. int wget_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  797. int wget_main(int argc UNUSED_PARAM, char **argv)
  798. {
  799. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  800. static const char wget_longopts[] ALIGN1 =
  801. /* name, has_arg, val */
  802. "continue\0" No_argument "c"
  803. //FIXME: -s isn't --spider, it's --save-headers!
  804. "spider\0" No_argument "s"
  805. "quiet\0" No_argument "q"
  806. "output-document\0" Required_argument "O"
  807. "directory-prefix\0" Required_argument "P"
  808. "proxy\0" Required_argument "Y"
  809. "user-agent\0" Required_argument "U"
  810. #if ENABLE_FEATURE_WGET_TIMEOUT
  811. "timeout\0" Required_argument "T"
  812. #endif
  813. /* Ignored: */
  814. // "tries\0" Required_argument "t"
  815. /* Ignored (we always use PASV): */
  816. "passive-ftp\0" No_argument "\xff"
  817. "header\0" Required_argument "\xfe"
  818. "post-data\0" Required_argument "\xfd"
  819. /* Ignored (we don't do ssl) */
  820. "no-check-certificate\0" No_argument "\xfc"
  821. /* Ignored (we don't support caching) */
  822. "no-cache\0" No_argument "\xfb"
  823. ;
  824. #endif
  825. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  826. llist_t *headers_llist = NULL;
  827. #endif
  828. INIT_G();
  829. IF_FEATURE_WGET_TIMEOUT(G.timeout_seconds = 900;)
  830. G.proxy_flag = "on"; /* use proxies if env vars are set */
  831. G.user_agent = "Wget"; /* "User-Agent" header field */
  832. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  833. applet_long_options = wget_longopts;
  834. #endif
  835. opt_complementary = "-1" IF_FEATURE_WGET_TIMEOUT(":T+") IF_FEATURE_WGET_LONG_OPTIONS(":\xfe::");
  836. getopt32(argv, "csqO:P:Y:U:T:" /*ignored:*/ "t:",
  837. &G.fname_out, &G.dir_prefix,
  838. &G.proxy_flag, &G.user_agent,
  839. IF_FEATURE_WGET_TIMEOUT(&G.timeout_seconds) IF_NOT_FEATURE_WGET_TIMEOUT(NULL),
  840. NULL /* -t RETRIES */
  841. IF_FEATURE_WGET_LONG_OPTIONS(, &headers_llist)
  842. IF_FEATURE_WGET_LONG_OPTIONS(, &G.post_data)
  843. );
  844. argv += optind;
  845. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  846. if (headers_llist) {
  847. int size = 1;
  848. char *cp;
  849. llist_t *ll = headers_llist;
  850. while (ll) {
  851. size += strlen(ll->data) + 2;
  852. ll = ll->link;
  853. }
  854. G.extra_headers = cp = xmalloc(size);
  855. while (headers_llist) {
  856. cp += sprintf(cp, "%s\r\n", (char*)llist_pop(&headers_llist));
  857. }
  858. }
  859. #endif
  860. G.output_fd = -1;
  861. G.o_flags = O_WRONLY | O_CREAT | O_TRUNC | O_EXCL;
  862. if (G.fname_out) { /* -O FILE ? */
  863. if (LONE_DASH(G.fname_out)) { /* -O - ? */
  864. G.output_fd = 1;
  865. option_mask32 &= ~WGET_OPT_CONTINUE;
  866. }
  867. /* compat with wget: -O FILE can overwrite */
  868. G.o_flags = O_WRONLY | O_CREAT | O_TRUNC;
  869. }
  870. while (*argv)
  871. download_one_url(*argv++);
  872. if (G.output_fd >= 0)
  873. xclose(G.output_fd);
  874. return EXIT_SUCCESS;
  875. }