wget.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  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 = (1 << 0),
  364. WGET_OPT_SPIDER = (1 << 1),
  365. WGET_OPT_QUIET = (1 << 2),
  366. WGET_OPT_OUTNAME = (1 << 3),
  367. WGET_OPT_PREFIX = (1 << 4),
  368. WGET_OPT_PROXY = (1 << 5),
  369. WGET_OPT_USER_AGENT = (1 << 6),
  370. WGET_OPT_RETRIES = (1 << 7),
  371. WGET_OPT_NETWORK_READ_TIMEOUT = (1 << 8),
  372. WGET_OPT_PASSIVE = (1 << 9),
  373. WGET_OPT_HEADER = (1 << 10),
  374. };
  375. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  376. static const char wget_longopts[] ALIGN1 =
  377. /* name, has_arg, val */
  378. "continue\0" No_argument "c"
  379. "spider\0" No_argument "s"
  380. "quiet\0" No_argument "q"
  381. "output-document\0" Required_argument "O"
  382. "directory-prefix\0" Required_argument "P"
  383. "proxy\0" Required_argument "Y"
  384. "user-agent\0" Required_argument "U"
  385. /* Ignored: */
  386. // "tries\0" Required_argument "t"
  387. // "timeout\0" Required_argument "T"
  388. /* Ignored (we always use PASV): */
  389. "passive-ftp\0" No_argument "\xff"
  390. "header\0" Required_argument "\xfe"
  391. ;
  392. #endif
  393. INIT_G();
  394. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  395. applet_long_options = wget_longopts;
  396. #endif
  397. /* server.allocated = target.allocated = NULL; */
  398. opt_complementary = "-1" USE_FEATURE_WGET_LONG_OPTIONS(":\xfe::");
  399. opt = getopt32(argv, "csqO:P:Y:U:" /*ignored:*/ "t:T:",
  400. &fname_out, &dir_prefix,
  401. &proxy_flag, &user_agent,
  402. NULL, /* -t RETRIES */
  403. NULL /* -T NETWORK_READ_TIMEOUT */
  404. USE_FEATURE_WGET_LONG_OPTIONS(, &headers_llist)
  405. );
  406. if (strcmp(proxy_flag, "off") == 0) {
  407. /* Use the proxy if necessary */
  408. use_proxy = 0;
  409. }
  410. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  411. if (headers_llist) {
  412. int size = 1;
  413. char *cp;
  414. llist_t *ll = headers_llist;
  415. while (ll) {
  416. size += strlen(ll->data) + 2;
  417. ll = ll->link;
  418. }
  419. extra_headers = cp = xmalloc(size);
  420. while (headers_llist) {
  421. cp += sprintf(cp, "%s\r\n", (char*)llist_pop(&headers_llist));
  422. }
  423. }
  424. #endif
  425. parse_url(argv[optind], &target);
  426. server.host = target.host;
  427. server.port = target.port;
  428. /* Use the proxy if necessary */
  429. if (use_proxy) {
  430. proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
  431. if (proxy && *proxy) {
  432. parse_url(proxy, &server);
  433. } else {
  434. use_proxy = 0;
  435. }
  436. }
  437. /* Guess an output filename, if there was no -O FILE */
  438. if (!(opt & WGET_OPT_OUTNAME)) {
  439. fname_out = bb_get_last_path_component_nostrip(target.path);
  440. /* handle "wget http://kernel.org//" */
  441. if (fname_out[0] == '/' || !fname_out[0])
  442. fname_out = (char*)"index.html";
  443. /* -P DIR is considered only if there was no -O FILE */
  444. if (dir_prefix)
  445. fname_out = concat_path_file(dir_prefix, fname_out);
  446. } else {
  447. if (LONE_DASH(fname_out)) {
  448. /* -O - */
  449. output_fd = 1;
  450. opt &= ~WGET_OPT_CONTINUE;
  451. }
  452. }
  453. #if ENABLE_FEATURE_WGET_STATUSBAR
  454. curfile = bb_get_last_path_component_nostrip(fname_out);
  455. #endif
  456. /* Impossible?
  457. if ((opt & WGET_OPT_CONTINUE) && !fname_out)
  458. bb_error_msg_and_die("cannot specify continue (-c) without a filename (-O)"); */
  459. /* Determine where to start transfer */
  460. if (opt & WGET_OPT_CONTINUE) {
  461. output_fd = open(fname_out, O_WRONLY);
  462. if (output_fd >= 0) {
  463. beg_range = xlseek(output_fd, 0, SEEK_END);
  464. }
  465. /* File doesn't exist. We do not create file here yet.
  466. We are not sure it exists on remove side */
  467. }
  468. /* We want to do exactly _one_ DNS lookup, since some
  469. * sites (i.e. ftp.us.debian.org) use round-robin DNS
  470. * and we want to connect to only one IP... */
  471. lsa = xhost2sockaddr(server.host, server.port);
  472. if (!(opt & WGET_OPT_QUIET)) {
  473. fprintf(stderr, "Connecting to %s (%s)\n", server.host,
  474. xmalloc_sockaddr2dotted(&lsa->u.sa));
  475. /* We leak result of xmalloc_sockaddr2dotted */
  476. }
  477. if (use_proxy || !target.is_ftp) {
  478. /*
  479. * HTTP session
  480. */
  481. do {
  482. got_clen = 0;
  483. chunked = 0;
  484. if (!--try)
  485. bb_error_msg_and_die("too many redirections");
  486. /* Open socket to http server */
  487. if (sfp) fclose(sfp);
  488. sfp = open_socket(lsa);
  489. /* Send HTTP request. */
  490. if (use_proxy) {
  491. fprintf(sfp, "GET %stp://%s/%s HTTP/1.1\r\n",
  492. target.is_ftp ? "f" : "ht", target.host,
  493. target.path);
  494. } else {
  495. fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
  496. }
  497. fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n",
  498. target.host, user_agent);
  499. #if ENABLE_FEATURE_WGET_AUTHENTICATION
  500. if (target.user) {
  501. fprintf(sfp, "Proxy-Authorization: Basic %s\r\n"+6,
  502. base64enc_512(buf, target.user));
  503. }
  504. if (use_proxy && server.user) {
  505. fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
  506. base64enc_512(buf, server.user));
  507. }
  508. #endif
  509. if (beg_range)
  510. fprintf(sfp, "Range: bytes=%"OFF_FMT"d-\r\n", beg_range);
  511. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  512. if (extra_headers)
  513. fputs(extra_headers, sfp);
  514. #endif
  515. fprintf(sfp, "Connection: close\r\n\r\n");
  516. /*
  517. * Retrieve HTTP response line and check for "200" status code.
  518. */
  519. read_response:
  520. if (fgets(buf, sizeof(buf), sfp) == NULL)
  521. bb_error_msg_and_die("no response from server");
  522. str = buf;
  523. str = skip_non_whitespace(str);
  524. str = skip_whitespace(str);
  525. // FIXME: no error check
  526. // xatou wouldn't work: "200 OK"
  527. status = atoi(str);
  528. switch (status) {
  529. case 0:
  530. case 100:
  531. while (gethdr(buf, sizeof(buf), sfp /*, &n*/) != NULL)
  532. /* eat all remaining headers */;
  533. goto read_response;
  534. case 200:
  535. /*
  536. Response 204 doesn't say "null file", it says "metadata
  537. has changed but data didn't":
  538. "10.2.5 204 No Content
  539. The server has fulfilled the request but does not need to return
  540. an entity-body, and might want to return updated metainformation.
  541. The response MAY include new or updated metainformation in the form
  542. of entity-headers, which if present SHOULD be associated with
  543. the requested variant.
  544. If the client is a user agent, it SHOULD NOT change its document
  545. view from that which caused the request to be sent. This response
  546. is primarily intended to allow input for actions to take place
  547. without causing a change to the user agent's active document view,
  548. although any new or updated metainformation SHOULD be applied
  549. to the document currently in the user agent's active view.
  550. The 204 response MUST NOT include a message-body, and thus
  551. is always terminated by the first empty line after the header fields."
  552. However, in real world it was observed that some web servers
  553. (e.g. Boa/0.94.14rc21) simply use code 204 when file size is zero.
  554. */
  555. case 204:
  556. break;
  557. case 300: /* redirection */
  558. case 301:
  559. case 302:
  560. case 303:
  561. break;
  562. case 206:
  563. if (beg_range)
  564. break;
  565. /* fall through */
  566. default:
  567. /* Show first line only and kill any ESC tricks */
  568. buf[strcspn(buf, "\n\r\x1b")] = '\0';
  569. bb_error_msg_and_die("server returned error: %s", buf);
  570. }
  571. /*
  572. * Retrieve HTTP headers.
  573. */
  574. while ((str = gethdr(buf, sizeof(buf), sfp /*, &n*/)) != NULL) {
  575. /* gethdr did already convert the "FOO:" string to lowercase */
  576. smalluint key = index_in_strings(keywords, *&buf) + 1;
  577. if (key == KEY_content_length) {
  578. content_len = BB_STRTOOFF(str, NULL, 10);
  579. if (errno || content_len < 0) {
  580. bb_error_msg_and_die("content-length %s is garbage", str);
  581. }
  582. got_clen = 1;
  583. continue;
  584. }
  585. if (key == KEY_transfer_encoding) {
  586. if (index_in_strings(keywords, str_tolower(str)) + 1 != KEY_chunked)
  587. bb_error_msg_and_die("transfer encoding '%s' is not supported", str);
  588. chunked = got_clen = 1;
  589. }
  590. if (key == KEY_location) {
  591. if (str[0] == '/')
  592. /* free(target.allocated); */
  593. target.path = /* target.allocated = */ xstrdup(str+1);
  594. else {
  595. parse_url(str, &target);
  596. if (use_proxy == 0) {
  597. server.host = target.host;
  598. server.port = target.port;
  599. }
  600. free(lsa);
  601. lsa = xhost2sockaddr(server.host, server.port);
  602. break;
  603. }
  604. }
  605. }
  606. } while (status >= 300);
  607. dfp = sfp;
  608. } else {
  609. /*
  610. * FTP session
  611. */
  612. if (!target.user)
  613. target.user = xstrdup("anonymous:busybox@");
  614. sfp = open_socket(lsa);
  615. if (ftpcmd(NULL, NULL, sfp, buf) != 220)
  616. bb_error_msg_and_die("%s", buf+4);
  617. /*
  618. * Splitting username:password pair,
  619. * trying to log in
  620. */
  621. str = strchr(target.user, ':');
  622. if (str)
  623. *(str++) = '\0';
  624. switch (ftpcmd("USER ", target.user, sfp, buf)) {
  625. case 230:
  626. break;
  627. case 331:
  628. if (ftpcmd("PASS ", str, sfp, buf) == 230)
  629. break;
  630. /* fall through (failed login) */
  631. default:
  632. bb_error_msg_and_die("ftp login: %s", buf+4);
  633. }
  634. ftpcmd("TYPE I", NULL, sfp, buf);
  635. /*
  636. * Querying file size
  637. */
  638. if (ftpcmd("SIZE ", target.path, sfp, buf) == 213) {
  639. content_len = BB_STRTOOFF(buf+4, NULL, 10);
  640. if (errno || content_len < 0) {
  641. bb_error_msg_and_die("SIZE value is garbage");
  642. }
  643. got_clen = 1;
  644. }
  645. /*
  646. * Entering passive mode
  647. */
  648. if (ftpcmd("PASV", NULL, sfp, buf) != 227) {
  649. pasv_error:
  650. bb_error_msg_and_die("bad response to %s: %s", "PASV", buf);
  651. }
  652. // Response is "227 garbageN1,N2,N3,N4,P1,P2[)garbage]
  653. // Server's IP is N1.N2.N3.N4 (we ignore it)
  654. // Server's port for data connection is P1*256+P2
  655. str = strrchr(buf, ')');
  656. if (str) str[0] = '\0';
  657. str = strrchr(buf, ',');
  658. if (!str) goto pasv_error;
  659. port = xatou_range(str+1, 0, 255);
  660. *str = '\0';
  661. str = strrchr(buf, ',');
  662. if (!str) goto pasv_error;
  663. port += xatou_range(str+1, 0, 255) * 256;
  664. set_nport(lsa, htons(port));
  665. dfp = open_socket(lsa);
  666. if (beg_range) {
  667. sprintf(buf, "REST %"OFF_FMT"d", beg_range);
  668. if (ftpcmd(buf, NULL, sfp, buf) == 350)
  669. content_len -= beg_range;
  670. }
  671. if (ftpcmd("RETR ", target.path, sfp, buf) > 150)
  672. bb_error_msg_and_die("bad response to %s: %s", "RETR", buf);
  673. }
  674. if (opt & WGET_OPT_SPIDER) {
  675. if (ENABLE_FEATURE_CLEAN_UP)
  676. fclose(sfp);
  677. return EXIT_SUCCESS;
  678. }
  679. /*
  680. * Retrieve file
  681. */
  682. /* Do it before progressmeter (want to have nice error message) */
  683. if (output_fd < 0) {
  684. int o_flags = O_WRONLY | O_CREAT | O_TRUNC | O_EXCL;
  685. /* compat with wget: -O FILE can overwrite */
  686. if (opt & WGET_OPT_OUTNAME)
  687. o_flags = O_WRONLY | O_CREAT | O_TRUNC;
  688. output_fd = xopen(fname_out, o_flags);
  689. }
  690. if (!(opt & WGET_OPT_QUIET))
  691. progressmeter(-1);
  692. if (chunked)
  693. goto get_clen;
  694. /* Loops only if chunked */
  695. while (1) {
  696. while (content_len > 0 || !got_clen) {
  697. int n;
  698. unsigned rdsz = sizeof(buf);
  699. if (content_len < sizeof(buf) && (chunked || got_clen))
  700. rdsz = (unsigned)content_len;
  701. n = safe_fread(buf, rdsz, dfp);
  702. if (n <= 0) {
  703. if (ferror(dfp)) {
  704. /* perror will not work: ferror doesn't set errno */
  705. bb_error_msg_and_die(bb_msg_read_error);
  706. }
  707. break;
  708. }
  709. xwrite(output_fd, buf, n);
  710. #if ENABLE_FEATURE_WGET_STATUSBAR
  711. transferred += n;
  712. #endif
  713. if (got_clen)
  714. content_len -= n;
  715. }
  716. if (!chunked)
  717. break;
  718. safe_fgets(buf, sizeof(buf), dfp); /* This is a newline */
  719. get_clen:
  720. safe_fgets(buf, sizeof(buf), dfp);
  721. content_len = STRTOOFF(buf, NULL, 16);
  722. /* FIXME: error check? */
  723. if (content_len == 0)
  724. break; /* all done! */
  725. }
  726. if (!(opt & WGET_OPT_QUIET))
  727. progressmeter(0);
  728. if ((use_proxy == 0) && target.is_ftp) {
  729. fclose(dfp);
  730. if (ftpcmd(NULL, NULL, sfp, buf) != 226)
  731. bb_error_msg_and_die("ftp error: %s", buf+4);
  732. ftpcmd("QUIT", NULL, sfp, buf);
  733. }
  734. return EXIT_SUCCESS;
  735. }