wget.c 22 KB

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