wget.c 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  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. //config:config WGET
  12. //config: bool "wget"
  13. //config: default y
  14. //config: help
  15. //config: wget is a utility for non-interactive download of files from HTTP
  16. //config: and FTP servers.
  17. //config:
  18. //config:config FEATURE_WGET_STATUSBAR
  19. //config: bool "Enable a nifty process meter (+2k)"
  20. //config: default y
  21. //config: depends on WGET
  22. //config: help
  23. //config: Enable the transfer progress bar for wget transfers.
  24. //config:
  25. //config:config FEATURE_WGET_AUTHENTICATION
  26. //config: bool "Enable HTTP authentication"
  27. //config: default y
  28. //config: depends on WGET
  29. //config: help
  30. //config: Support authenticated HTTP transfers.
  31. //config:
  32. //config:config FEATURE_WGET_LONG_OPTIONS
  33. //config: bool "Enable long options"
  34. //config: default y
  35. //config: depends on WGET && LONG_OPTS
  36. //config: help
  37. //config: Support long options for the wget applet.
  38. //config:
  39. //config:config FEATURE_WGET_TIMEOUT
  40. //config: bool "Enable timeout option -T SEC"
  41. //config: default y
  42. //config: depends on WGET
  43. //config: help
  44. //config: Supports network read and connect timeouts for wget,
  45. //config: so that wget will give up and timeout, through the -T
  46. //config: command line option.
  47. //config:
  48. //config: Currently only connect and network data read timeout are
  49. //config: supported (i.e., timeout is not applied to the DNS query). When
  50. //config: FEATURE_WGET_LONG_OPTIONS is also enabled, the --timeout option
  51. //config: will work in addition to -T.
  52. //config:
  53. //config:config FEATURE_WGET_OPENSSL
  54. //config: bool "Try to connect to HTTPS using openssl"
  55. //config: default y
  56. //config: depends on WGET
  57. //config: help
  58. //config: Choose how wget establishes SSL connection for https:// URLs.
  59. //config:
  60. //config: Busybox itself contains no SSL code. wget will spawn
  61. //config: a helper program to talk over HTTPS.
  62. //config:
  63. //config: OpenSSL has a simple SSL client for debug purposes.
  64. //config: If you select "openssl" helper, wget will effectively call
  65. //config: "openssl s_client -quiet -connect IP:443 2>/dev/null"
  66. //config: and pipe its data through it.
  67. //config: Note inconvenient API: host resolution is done twice,
  68. //config: and there is no guarantee openssl's idea of IPv6 address
  69. //config: format is the same as ours.
  70. //config: Another problem is that s_client prints debug information
  71. //config: to stderr, and it needs to be suppressed. This means
  72. //config: all error messages get suppressed too.
  73. //config: openssl is also a big binary, often dynamically linked
  74. //config: against ~15 libraries.
  75. //config:
  76. //config:config FEATURE_WGET_SSL_HELPER
  77. //config: bool "Try to connect to HTTPS using ssl_helper"
  78. //config: default y
  79. //config: depends on WGET
  80. //config: help
  81. //config: Choose how wget establishes SSL connection for https:// URLs.
  82. //config:
  83. //config: Busybox itself contains no SSL code. wget will spawn
  84. //config: a helper program to talk over HTTPS.
  85. //config:
  86. //config: ssl_helper is a tool which can be built statically
  87. //config: from busybox sources against a small embedded SSL library.
  88. //config: Please see networking/ssl_helper/README.
  89. //config: It does not require double host resolution and emits
  90. //config: error messages to stderr.
  91. //config:
  92. //config: Precompiled static binary may be available at
  93. //config: http://busybox.net/downloads/binaries/
  94. //applet:IF_WGET(APPLET(wget, BB_DIR_USR_BIN, BB_SUID_DROP))
  95. //kbuild:lib-$(CONFIG_WGET) += wget.o
  96. //usage:#define wget_trivial_usage
  97. //usage: IF_FEATURE_WGET_LONG_OPTIONS(
  98. //usage: "[-c|--continue] [-s|--spider] [-q|--quiet] [-O|--output-document FILE]\n"
  99. //usage: " [--header 'header: value'] [-Y|--proxy on/off] [-P DIR]\n"
  100. /* Since we ignore these opts, we don't show them in --help */
  101. /* //usage: " [--no-check-certificate] [--no-cache]" */
  102. //usage: " [-U|--user-agent AGENT]" IF_FEATURE_WGET_TIMEOUT(" [-T SEC]") " URL..."
  103. //usage: )
  104. //usage: IF_NOT_FEATURE_WGET_LONG_OPTIONS(
  105. //usage: "[-csq] [-O FILE] [-Y on/off] [-P DIR] [-U AGENT]"
  106. //usage: IF_FEATURE_WGET_TIMEOUT(" [-T SEC]") " URL..."
  107. //usage: )
  108. //usage:#define wget_full_usage "\n\n"
  109. //usage: "Retrieve files via HTTP or FTP\n"
  110. //usage: "\n -s Spider mode - only check file existence"
  111. //usage: "\n -c Continue retrieval of aborted transfer"
  112. //usage: "\n -q Quiet"
  113. //usage: "\n -P DIR Save to DIR (default .)"
  114. //usage: IF_FEATURE_WGET_TIMEOUT(
  115. //usage: "\n -T SEC Network read timeout is SEC seconds"
  116. //usage: )
  117. //usage: "\n -O FILE Save to FILE ('-' for stdout)"
  118. //usage: "\n -U STR Use STR for User-Agent header"
  119. //usage: "\n -Y Use proxy ('on' or 'off')"
  120. #include "libbb.h"
  121. #if 0
  122. # define log_io(...) bb_error_msg(__VA_ARGS__)
  123. # define SENDFMT(fp, fmt, ...) \
  124. do { \
  125. log_io("> " fmt, ##__VA_ARGS__); \
  126. fprintf(fp, fmt, ##__VA_ARGS__); \
  127. } while (0);
  128. #else
  129. # define log_io(...) ((void)0)
  130. # define SENDFMT(fp, fmt, ...) fprintf(fp, fmt, ##__VA_ARGS__)
  131. #endif
  132. struct host_info {
  133. char *allocated;
  134. const char *path;
  135. char *user;
  136. const char *protocol;
  137. char *host;
  138. int port;
  139. };
  140. static const char P_FTP[] = "ftp";
  141. static const char P_HTTP[] = "http";
  142. static const char P_HTTPS[] = "https";
  143. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  144. /* User-specified headers prevent using our corresponding built-in headers. */
  145. enum {
  146. HDR_HOST = (1<<0),
  147. HDR_USER_AGENT = (1<<1),
  148. HDR_RANGE = (1<<2),
  149. HDR_AUTH = (1<<3) * ENABLE_FEATURE_WGET_AUTHENTICATION,
  150. HDR_PROXY_AUTH = (1<<4) * ENABLE_FEATURE_WGET_AUTHENTICATION,
  151. };
  152. static const char wget_user_headers[] ALIGN1 =
  153. "Host:\0"
  154. "User-Agent:\0"
  155. "Range:\0"
  156. # if ENABLE_FEATURE_WGET_AUTHENTICATION
  157. "Authorization:\0"
  158. "Proxy-Authorization:\0"
  159. # endif
  160. ;
  161. # define USR_HEADER_HOST (G.user_headers & HDR_HOST)
  162. # define USR_HEADER_USER_AGENT (G.user_headers & HDR_USER_AGENT)
  163. # define USR_HEADER_RANGE (G.user_headers & HDR_RANGE)
  164. # define USR_HEADER_AUTH (G.user_headers & HDR_AUTH)
  165. # define USR_HEADER_PROXY_AUTH (G.user_headers & HDR_PROXY_AUTH)
  166. #else /* No long options, no user-headers :( */
  167. # define USR_HEADER_HOST 0
  168. # define USR_HEADER_USER_AGENT 0
  169. # define USR_HEADER_RANGE 0
  170. # define USR_HEADER_AUTH 0
  171. # define USR_HEADER_PROXY_AUTH 0
  172. #endif
  173. /* Globals */
  174. struct globals {
  175. off_t content_len; /* Content-length of the file */
  176. off_t beg_range; /* Range at which continue begins */
  177. #if ENABLE_FEATURE_WGET_STATUSBAR
  178. off_t transferred; /* Number of bytes transferred so far */
  179. const char *curfile; /* Name of current file being transferred */
  180. bb_progress_t pmt;
  181. #endif
  182. char *dir_prefix;
  183. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  184. char *post_data;
  185. char *extra_headers;
  186. unsigned char user_headers; /* Headers mentioned by the user */
  187. #endif
  188. char *fname_out; /* where to direct output (-O) */
  189. const char *proxy_flag; /* Use proxies if env vars are set */
  190. const char *user_agent; /* "User-Agent" header field */
  191. #if ENABLE_FEATURE_WGET_TIMEOUT
  192. unsigned timeout_seconds;
  193. bool connecting;
  194. #endif
  195. int output_fd;
  196. int o_flags;
  197. smallint chunked; /* chunked transfer encoding */
  198. smallint got_clen; /* got content-length: from server */
  199. /* Local downloads do benefit from big buffer.
  200. * With 512 byte buffer, it was measured to be
  201. * an order of magnitude slower than with big one.
  202. */
  203. uint64_t just_to_align_next_member;
  204. char wget_buf[CONFIG_FEATURE_COPYBUF_KB*1024];
  205. } FIX_ALIASING;
  206. #define G (*ptr_to_globals)
  207. #define INIT_G() do { \
  208. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  209. } while (0)
  210. #define FINI_G() do { \
  211. FREE_PTR_TO_GLOBALS(); \
  212. } while (0)
  213. /* Must match option string! */
  214. enum {
  215. WGET_OPT_CONTINUE = (1 << 0),
  216. WGET_OPT_SPIDER = (1 << 1),
  217. WGET_OPT_QUIET = (1 << 2),
  218. WGET_OPT_OUTNAME = (1 << 3),
  219. WGET_OPT_PREFIX = (1 << 4),
  220. WGET_OPT_PROXY = (1 << 5),
  221. WGET_OPT_USER_AGENT = (1 << 6),
  222. WGET_OPT_NETWORK_READ_TIMEOUT = (1 << 7),
  223. WGET_OPT_RETRIES = (1 << 8),
  224. WGET_OPT_PASSIVE = (1 << 9),
  225. WGET_OPT_HEADER = (1 << 10) * ENABLE_FEATURE_WGET_LONG_OPTIONS,
  226. WGET_OPT_POST_DATA = (1 << 11) * ENABLE_FEATURE_WGET_LONG_OPTIONS,
  227. };
  228. enum {
  229. PROGRESS_START = -1,
  230. PROGRESS_END = 0,
  231. PROGRESS_BUMP = 1,
  232. };
  233. #if ENABLE_FEATURE_WGET_STATUSBAR
  234. static void progress_meter(int flag)
  235. {
  236. if (option_mask32 & WGET_OPT_QUIET)
  237. return;
  238. if (flag == PROGRESS_START)
  239. bb_progress_init(&G.pmt, G.curfile);
  240. bb_progress_update(&G.pmt,
  241. G.beg_range,
  242. G.transferred,
  243. (G.chunked || !G.got_clen) ? 0 : G.beg_range + G.transferred + G.content_len
  244. );
  245. if (flag == PROGRESS_END) {
  246. bb_progress_free(&G.pmt);
  247. bb_putchar_stderr('\n');
  248. G.transferred = 0;
  249. }
  250. }
  251. #else
  252. static ALWAYS_INLINE void progress_meter(int flag UNUSED_PARAM) { }
  253. #endif
  254. /* IPv6 knows scoped address types i.e. link and site local addresses. Link
  255. * local addresses can have a scope identifier to specify the
  256. * interface/link an address is valid on (e.g. fe80::1%eth0). This scope
  257. * identifier is only valid on a single node.
  258. *
  259. * RFC 4007 says that the scope identifier MUST NOT be sent across the wire,
  260. * unless all nodes agree on the semantic. Apache e.g. regards zone identifiers
  261. * in the Host header as invalid requests, see
  262. * https://issues.apache.org/bugzilla/show_bug.cgi?id=35122
  263. */
  264. static void strip_ipv6_scope_id(char *host)
  265. {
  266. char *scope, *cp;
  267. /* bbox wget actually handles IPv6 addresses without [], like
  268. * wget "http://::1/xxx", but this is not standard.
  269. * To save code, _here_ we do not support it. */
  270. if (host[0] != '[')
  271. return; /* not IPv6 */
  272. scope = strchr(host, '%');
  273. if (!scope)
  274. return;
  275. /* Remove the IPv6 zone identifier from the host address */
  276. cp = strchr(host, ']');
  277. if (!cp || (cp[1] != ':' && cp[1] != '\0')) {
  278. /* malformed address (not "[xx]:nn" or "[xx]") */
  279. return;
  280. }
  281. /* cp points to "]...", scope points to "%eth0]..." */
  282. overlapping_strcpy(scope, cp);
  283. }
  284. #if ENABLE_FEATURE_WGET_AUTHENTICATION
  285. /* Base64-encode character string. */
  286. static char *base64enc(const char *str)
  287. {
  288. unsigned len = strlen(str);
  289. if (len > sizeof(G.wget_buf)/4*3 - 10) /* paranoia */
  290. len = sizeof(G.wget_buf)/4*3 - 10;
  291. bb_uuencode(G.wget_buf, str, len, bb_uuenc_tbl_base64);
  292. return G.wget_buf;
  293. }
  294. #endif
  295. static char* sanitize_string(char *s)
  296. {
  297. unsigned char *p = (void *) s;
  298. while (*p >= ' ')
  299. p++;
  300. *p = '\0';
  301. return s;
  302. }
  303. #if ENABLE_FEATURE_WGET_TIMEOUT
  304. static void alarm_handler(int sig UNUSED_PARAM)
  305. {
  306. /* This is theoretically unsafe (uses stdio and malloc in signal handler) */
  307. if (G.connecting)
  308. bb_error_msg_and_die("download timed out");
  309. }
  310. #endif
  311. static FILE *open_socket(len_and_sockaddr *lsa)
  312. {
  313. int fd;
  314. FILE *fp;
  315. IF_FEATURE_WGET_TIMEOUT(alarm(G.timeout_seconds); G.connecting = 1;)
  316. fd = xconnect_stream(lsa);
  317. IF_FEATURE_WGET_TIMEOUT(G.connecting = 0;)
  318. /* glibc 2.4 seems to try seeking on it - ??! */
  319. /* hopefully it understands what ESPIPE means... */
  320. fp = fdopen(fd, "r+");
  321. if (!fp)
  322. bb_perror_msg_and_die(bb_msg_memory_exhausted);
  323. return fp;
  324. }
  325. /* Returns '\n' if it was seen, else '\0'. Trims at first '\r' or '\n' */
  326. /* FIXME: does not respect FEATURE_WGET_TIMEOUT and -T N: */
  327. static char fgets_and_trim(FILE *fp)
  328. {
  329. char c;
  330. char *buf_ptr;
  331. if (fgets(G.wget_buf, sizeof(G.wget_buf) - 1, fp) == NULL)
  332. bb_perror_msg_and_die("error getting response");
  333. buf_ptr = strchrnul(G.wget_buf, '\n');
  334. c = *buf_ptr;
  335. *buf_ptr = '\0';
  336. buf_ptr = strchrnul(G.wget_buf, '\r');
  337. *buf_ptr = '\0';
  338. log_io("< %s", G.wget_buf);
  339. return c;
  340. }
  341. static int ftpcmd(const char *s1, const char *s2, FILE *fp)
  342. {
  343. int result;
  344. if (s1) {
  345. if (!s2)
  346. s2 = "";
  347. fprintf(fp, "%s%s\r\n", s1, s2);
  348. fflush(fp);
  349. log_io("> %s%s", s1, s2);
  350. }
  351. do {
  352. fgets_and_trim(fp);
  353. } while (!isdigit(G.wget_buf[0]) || G.wget_buf[3] != ' ');
  354. G.wget_buf[3] = '\0';
  355. result = xatoi_positive(G.wget_buf);
  356. G.wget_buf[3] = ' ';
  357. return result;
  358. }
  359. static void parse_url(const char *src_url, struct host_info *h)
  360. {
  361. char *url, *p, *sp;
  362. free(h->allocated);
  363. h->allocated = url = xstrdup(src_url);
  364. h->protocol = P_FTP;
  365. p = strstr(url, "://");
  366. if (p) {
  367. *p = '\0';
  368. h->host = p + 3;
  369. if (strcmp(url, P_FTP) == 0) {
  370. h->port = bb_lookup_port(P_FTP, "tcp", 21);
  371. } else
  372. if (strcmp(url, P_HTTPS) == 0) {
  373. h->port = bb_lookup_port(P_HTTPS, "tcp", 443);
  374. h->protocol = P_HTTPS;
  375. } else
  376. if (strcmp(url, P_HTTP) == 0) {
  377. http:
  378. h->port = bb_lookup_port(P_HTTP, "tcp", 80);
  379. h->protocol = P_HTTP;
  380. } else {
  381. *p = ':';
  382. bb_error_msg_and_die("not an http or ftp url: %s", sanitize_string(url));
  383. }
  384. } else {
  385. // GNU wget is user-friendly and falls back to http://
  386. h->host = url;
  387. goto http;
  388. }
  389. // FYI:
  390. // "Real" wget 'http://busybox.net?var=a/b' sends this request:
  391. // 'GET /?var=a/b HTTP 1.0'
  392. // and saves 'index.html?var=a%2Fb' (we save 'b')
  393. // wget 'http://busybox.net?login=john@doe':
  394. // request: 'GET /?login=john@doe HTTP/1.0'
  395. // saves: 'index.html?login=john@doe' (we save '?login=john@doe')
  396. // wget 'http://busybox.net#test/test':
  397. // request: 'GET / HTTP/1.0'
  398. // saves: 'index.html' (we save 'test')
  399. //
  400. // We also don't add unique .N suffix if file exists...
  401. sp = strchr(h->host, '/');
  402. p = strchr(h->host, '?'); if (!sp || (p && sp > p)) sp = p;
  403. p = strchr(h->host, '#'); if (!sp || (p && sp > p)) sp = p;
  404. if (!sp) {
  405. h->path = "";
  406. } else if (*sp == '/') {
  407. *sp = '\0';
  408. h->path = sp + 1;
  409. } else { // '#' or '?'
  410. // http://busybox.net?login=john@doe is a valid URL
  411. // memmove converts to:
  412. // http:/busybox.nett?login=john@doe...
  413. memmove(h->host - 1, h->host, sp - h->host);
  414. h->host--;
  415. sp[-1] = '\0';
  416. h->path = sp;
  417. }
  418. sp = strrchr(h->host, '@');
  419. if (sp != NULL) {
  420. // URL-decode "user:password" string before base64-encoding:
  421. // wget http://test:my%20pass@example.com should send
  422. // Authorization: Basic dGVzdDpteSBwYXNz
  423. // which decodes to "test:my pass".
  424. // Standard wget and curl do this too.
  425. *sp = '\0';
  426. free(h->user);
  427. h->user = xstrdup(percent_decode_in_place(h->host, /*strict:*/ 0));
  428. h->host = sp + 1;
  429. }
  430. /* else: h->user remains NULL, or as set by original request
  431. * before redirect (if we are here after a redirect).
  432. */
  433. }
  434. static char *gethdr(FILE *fp)
  435. {
  436. char *s, *hdrval;
  437. int c;
  438. /* retrieve header line */
  439. c = fgets_and_trim(fp);
  440. /* end of the headers? */
  441. if (G.wget_buf[0] == '\0')
  442. return NULL;
  443. /* convert the header name to lower case */
  444. for (s = G.wget_buf; isalnum(*s) || *s == '-' || *s == '.' || *s == '_'; ++s) {
  445. /*
  446. * No-op for 20-3f and 60-7f. "0-9a-z-." are in these ranges.
  447. * 40-5f range ("@A-Z[\]^_") maps to 60-7f.
  448. * "A-Z" maps to "a-z".
  449. * "@[\]" can't occur in header names.
  450. * "^_" maps to "~,DEL" (which is wrong).
  451. * "^" was never seen yet, "_" was seen from web.archive.org
  452. * (x-archive-orig-x_commoncrawl_Signature: HEXSTRING).
  453. */
  454. *s |= 0x20;
  455. }
  456. /* verify we are at the end of the header name */
  457. if (*s != ':')
  458. bb_error_msg_and_die("bad header line: %s", sanitize_string(G.wget_buf));
  459. /* locate the start of the header value */
  460. *s++ = '\0';
  461. hdrval = skip_whitespace(s);
  462. if (c != '\n') {
  463. /* Rats! The buffer isn't big enough to hold the entire header value */
  464. while (c = getc(fp), c != EOF && c != '\n')
  465. continue;
  466. }
  467. return hdrval;
  468. }
  469. static void reset_beg_range_to_zero(void)
  470. {
  471. bb_error_msg("restart failed");
  472. G.beg_range = 0;
  473. xlseek(G.output_fd, 0, SEEK_SET);
  474. /* Done at the end instead: */
  475. /* ftruncate(G.output_fd, 0); */
  476. }
  477. static FILE* prepare_ftp_session(FILE **dfpp, struct host_info *target, len_and_sockaddr *lsa)
  478. {
  479. FILE *sfp;
  480. char *str;
  481. int port;
  482. if (!target->user)
  483. target->user = xstrdup("anonymous:busybox@");
  484. sfp = open_socket(lsa);
  485. if (ftpcmd(NULL, NULL, sfp) != 220)
  486. bb_error_msg_and_die("%s", sanitize_string(G.wget_buf + 4));
  487. /*
  488. * Splitting username:password pair,
  489. * trying to log in
  490. */
  491. str = strchr(target->user, ':');
  492. if (str)
  493. *str++ = '\0';
  494. switch (ftpcmd("USER ", target->user, sfp)) {
  495. case 230:
  496. break;
  497. case 331:
  498. if (ftpcmd("PASS ", str, sfp) == 230)
  499. break;
  500. /* fall through (failed login) */
  501. default:
  502. bb_error_msg_and_die("ftp login: %s", sanitize_string(G.wget_buf + 4));
  503. }
  504. ftpcmd("TYPE I", NULL, sfp);
  505. /*
  506. * Querying file size
  507. */
  508. if (ftpcmd("SIZE ", target->path, sfp) == 213) {
  509. G.content_len = BB_STRTOOFF(G.wget_buf + 4, NULL, 10);
  510. if (G.content_len < 0 || errno) {
  511. bb_error_msg_and_die("SIZE value is garbage");
  512. }
  513. G.got_clen = 1;
  514. }
  515. /*
  516. * Entering passive mode
  517. */
  518. if (ftpcmd("PASV", NULL, sfp) != 227) {
  519. pasv_error:
  520. bb_error_msg_and_die("bad response to %s: %s", "PASV", sanitize_string(G.wget_buf));
  521. }
  522. // Response is "227 garbageN1,N2,N3,N4,P1,P2[)garbage]
  523. // Server's IP is N1.N2.N3.N4 (we ignore it)
  524. // Server's port for data connection is P1*256+P2
  525. str = strrchr(G.wget_buf, ')');
  526. if (str) str[0] = '\0';
  527. str = strrchr(G.wget_buf, ',');
  528. if (!str) goto pasv_error;
  529. port = xatou_range(str+1, 0, 255);
  530. *str = '\0';
  531. str = strrchr(G.wget_buf, ',');
  532. if (!str) goto pasv_error;
  533. port += xatou_range(str+1, 0, 255) * 256;
  534. set_nport(&lsa->u.sa, htons(port));
  535. *dfpp = open_socket(lsa);
  536. if (G.beg_range != 0) {
  537. sprintf(G.wget_buf, "REST %"OFF_FMT"u", G.beg_range);
  538. if (ftpcmd(G.wget_buf, NULL, sfp) == 350)
  539. G.content_len -= G.beg_range;
  540. else
  541. reset_beg_range_to_zero();
  542. }
  543. if (ftpcmd("RETR ", target->path, sfp) > 150)
  544. bb_error_msg_and_die("bad response to %s: %s", "RETR", sanitize_string(G.wget_buf));
  545. return sfp;
  546. }
  547. #if ENABLE_FEATURE_WGET_OPENSSL
  548. static int spawn_https_helper_openssl(const char *host, unsigned port)
  549. {
  550. char *allocated = NULL;
  551. int sp[2];
  552. int pid;
  553. IF_FEATURE_WGET_SSL_HELPER(volatile int child_failed = 0;)
  554. if (socketpair(AF_UNIX, SOCK_STREAM, 0, sp) != 0)
  555. /* Kernel can have AF_UNIX support disabled */
  556. bb_perror_msg_and_die("socketpair");
  557. if (!strchr(host, ':'))
  558. host = allocated = xasprintf("%s:%u", host, port);
  559. fflush_all();
  560. pid = xvfork();
  561. if (pid == 0) {
  562. /* Child */
  563. char *argv[6];
  564. close(sp[0]);
  565. xmove_fd(sp[1], 0);
  566. xdup2(0, 1);
  567. /*
  568. * openssl s_client -quiet -connect www.kernel.org:443 2>/dev/null
  569. * It prints some debug stuff on stderr, don't know how to suppress it.
  570. * Work around by dev-nulling stderr. We lose all error messages :(
  571. */
  572. xmove_fd(2, 3);
  573. xopen("/dev/null", O_RDWR);
  574. argv[0] = (char*)"openssl";
  575. argv[1] = (char*)"s_client";
  576. argv[2] = (char*)"-quiet";
  577. argv[3] = (char*)"-connect";
  578. argv[4] = (char*)host;
  579. argv[5] = NULL;
  580. BB_EXECVP(argv[0], argv);
  581. xmove_fd(3, 2);
  582. # if ENABLE_FEATURE_WGET_SSL_HELPER
  583. child_failed = 1;
  584. xfunc_die();
  585. # else
  586. bb_perror_msg_and_die("can't execute '%s'", argv[0]);
  587. # endif
  588. /* notreached */
  589. }
  590. /* Parent */
  591. free(allocated);
  592. close(sp[1]);
  593. # if ENABLE_FEATURE_WGET_SSL_HELPER
  594. if (child_failed) {
  595. close(sp[0]);
  596. return -1;
  597. }
  598. # endif
  599. return sp[0];
  600. }
  601. #endif
  602. /* See networking/ssl_helper/README how to build one */
  603. #if ENABLE_FEATURE_WGET_SSL_HELPER
  604. static void spawn_https_helper_small(int network_fd)
  605. {
  606. int sp[2];
  607. int pid;
  608. if (socketpair(AF_UNIX, SOCK_STREAM, 0, sp) != 0)
  609. /* Kernel can have AF_UNIX support disabled */
  610. bb_perror_msg_and_die("socketpair");
  611. pid = BB_MMU ? xfork() : xvfork();
  612. if (pid == 0) {
  613. /* Child */
  614. char *argv[3];
  615. close(sp[0]);
  616. xmove_fd(sp[1], 0);
  617. xdup2(0, 1);
  618. xmove_fd(network_fd, 3);
  619. /*
  620. * A simple ssl/tls helper
  621. */
  622. argv[0] = (char*)"ssl_helper";
  623. argv[1] = (char*)"-d3";
  624. argv[2] = NULL;
  625. BB_EXECVP(argv[0], argv);
  626. bb_perror_msg_and_die("can't execute '%s'", argv[0]);
  627. /* notreached */
  628. }
  629. /* Parent */
  630. close(sp[1]);
  631. xmove_fd(sp[0], network_fd);
  632. }
  633. #endif
  634. static void NOINLINE retrieve_file_data(FILE *dfp)
  635. {
  636. #if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
  637. # if ENABLE_FEATURE_WGET_TIMEOUT
  638. unsigned second_cnt = G.timeout_seconds;
  639. # endif
  640. struct pollfd polldata;
  641. polldata.fd = fileno(dfp);
  642. polldata.events = POLLIN | POLLPRI;
  643. #endif
  644. progress_meter(PROGRESS_START);
  645. if (G.chunked)
  646. goto get_clen;
  647. /* Loops only if chunked */
  648. while (1) {
  649. #if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
  650. /* Must use nonblocking I/O, otherwise fread will loop
  651. * and *block* until it reads full buffer,
  652. * which messes up progress bar and/or timeout logic.
  653. * Because of nonblocking I/O, we need to dance
  654. * very carefully around EAGAIN. See explanation at
  655. * clearerr() calls.
  656. */
  657. ndelay_on(polldata.fd);
  658. #endif
  659. while (1) {
  660. int n;
  661. unsigned rdsz;
  662. #if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
  663. /* fread internally uses read loop, which in our case
  664. * is usually exited when we get EAGAIN.
  665. * In this case, libc sets error marker on the stream.
  666. * Need to clear it before next fread to avoid possible
  667. * rare false positive ferror below. Rare because usually
  668. * fread gets more than zero bytes, and we don't fall
  669. * into if (n <= 0) ...
  670. */
  671. clearerr(dfp);
  672. #endif
  673. errno = 0;
  674. rdsz = sizeof(G.wget_buf);
  675. if (G.got_clen) {
  676. if (G.content_len < (off_t)sizeof(G.wget_buf)) {
  677. if ((int)G.content_len <= 0)
  678. break;
  679. rdsz = (unsigned)G.content_len;
  680. }
  681. }
  682. n = fread(G.wget_buf, 1, rdsz, dfp);
  683. if (n > 0) {
  684. xwrite(G.output_fd, G.wget_buf, n);
  685. #if ENABLE_FEATURE_WGET_STATUSBAR
  686. G.transferred += n;
  687. #endif
  688. if (G.got_clen) {
  689. G.content_len -= n;
  690. if (G.content_len == 0)
  691. break;
  692. }
  693. #if ENABLE_FEATURE_WGET_TIMEOUT
  694. second_cnt = G.timeout_seconds;
  695. #endif
  696. goto bump;
  697. }
  698. /* n <= 0.
  699. * man fread:
  700. * If error occurs, or EOF is reached, the return value
  701. * is a short item count (or zero).
  702. * fread does not distinguish between EOF and error.
  703. */
  704. if (errno != EAGAIN) {
  705. if (ferror(dfp)) {
  706. progress_meter(PROGRESS_END);
  707. bb_perror_msg_and_die(bb_msg_read_error);
  708. }
  709. break; /* EOF, not error */
  710. }
  711. #if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
  712. /* It was EAGAIN. There is no data. Wait up to one second
  713. * then abort if timed out, or update the bar and try reading again.
  714. */
  715. if (safe_poll(&polldata, 1, 1000) == 0) {
  716. # if ENABLE_FEATURE_WGET_TIMEOUT
  717. if (second_cnt != 0 && --second_cnt == 0) {
  718. progress_meter(PROGRESS_END);
  719. bb_error_msg_and_die("download timed out");
  720. }
  721. # endif
  722. /* We used to loop back to poll here,
  723. * but there is no great harm in letting fread
  724. * to try reading anyway.
  725. */
  726. }
  727. #endif
  728. bump:
  729. /* Need to do it _every_ second for "stalled" indicator
  730. * to be shown properly.
  731. */
  732. progress_meter(PROGRESS_BUMP);
  733. } /* while (reading data) */
  734. #if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
  735. clearerr(dfp);
  736. ndelay_off(polldata.fd); /* else fgets can get very unhappy */
  737. #endif
  738. if (!G.chunked)
  739. break;
  740. fgets_and_trim(dfp); /* Eat empty line */
  741. get_clen:
  742. fgets_and_trim(dfp);
  743. G.content_len = STRTOOFF(G.wget_buf, NULL, 16);
  744. /* FIXME: error check? */
  745. if (G.content_len == 0)
  746. break; /* all done! */
  747. G.got_clen = 1;
  748. /*
  749. * Note that fgets may result in some data being buffered in dfp.
  750. * We loop back to fread, which will retrieve this data.
  751. * Also note that code has to be arranged so that fread
  752. * is done _before_ one-second poll wait - poll doesn't know
  753. * about stdio buffering and can result in spurious one second waits!
  754. */
  755. }
  756. /* If -c failed, we restart from the beginning,
  757. * but we do not truncate file then, we do it only now, at the end.
  758. * This lets user to ^C if his 99% complete 10 GB file download
  759. * failed to restart *without* losing the almost complete file.
  760. */
  761. {
  762. off_t pos = lseek(G.output_fd, 0, SEEK_CUR);
  763. if (pos != (off_t)-1)
  764. ftruncate(G.output_fd, pos);
  765. }
  766. /* Draw full bar and free its resources */
  767. G.chunked = 0; /* makes it show 100% even for chunked download */
  768. G.got_clen = 1; /* makes it show 100% even for download of (formerly) unknown size */
  769. progress_meter(PROGRESS_END);
  770. }
  771. static void download_one_url(const char *url)
  772. {
  773. bool use_proxy; /* Use proxies if env vars are set */
  774. int redir_limit;
  775. len_and_sockaddr *lsa;
  776. FILE *sfp; /* socket to web/ftp server */
  777. FILE *dfp; /* socket to ftp server (data) */
  778. char *proxy = NULL;
  779. char *fname_out_alloc;
  780. char *redirected_path = NULL;
  781. struct host_info server;
  782. struct host_info target;
  783. server.allocated = NULL;
  784. target.allocated = NULL;
  785. server.user = NULL;
  786. target.user = NULL;
  787. parse_url(url, &target);
  788. /* Use the proxy if necessary */
  789. use_proxy = (strcmp(G.proxy_flag, "off") != 0);
  790. if (use_proxy) {
  791. proxy = getenv(target.protocol == P_FTP ? "ftp_proxy" : "http_proxy");
  792. //FIXME: what if protocol is https? Ok to use http_proxy?
  793. use_proxy = (proxy && proxy[0]);
  794. if (use_proxy)
  795. parse_url(proxy, &server);
  796. }
  797. if (!use_proxy) {
  798. server.port = target.port;
  799. if (ENABLE_FEATURE_IPV6) {
  800. //free(server.allocated); - can't be non-NULL
  801. server.host = server.allocated = xstrdup(target.host);
  802. } else {
  803. server.host = target.host;
  804. }
  805. }
  806. if (ENABLE_FEATURE_IPV6)
  807. strip_ipv6_scope_id(target.host);
  808. /* If there was no -O FILE, guess output filename */
  809. fname_out_alloc = NULL;
  810. if (!(option_mask32 & WGET_OPT_OUTNAME)) {
  811. G.fname_out = bb_get_last_path_component_nostrip(target.path);
  812. /* handle "wget http://kernel.org//" */
  813. if (G.fname_out[0] == '/' || !G.fname_out[0])
  814. G.fname_out = (char*)"index.html";
  815. /* -P DIR is considered only if there was no -O FILE */
  816. if (G.dir_prefix)
  817. G.fname_out = fname_out_alloc = concat_path_file(G.dir_prefix, G.fname_out);
  818. else {
  819. /* redirects may free target.path later, need to make a copy */
  820. G.fname_out = fname_out_alloc = xstrdup(G.fname_out);
  821. }
  822. }
  823. #if ENABLE_FEATURE_WGET_STATUSBAR
  824. G.curfile = bb_get_last_path_component_nostrip(G.fname_out);
  825. #endif
  826. /* Determine where to start transfer */
  827. G.beg_range = 0;
  828. if (option_mask32 & WGET_OPT_CONTINUE) {
  829. G.output_fd = open(G.fname_out, O_WRONLY);
  830. if (G.output_fd >= 0) {
  831. G.beg_range = xlseek(G.output_fd, 0, SEEK_END);
  832. }
  833. /* File doesn't exist. We do not create file here yet.
  834. * We are not sure it exists on remote side */
  835. }
  836. redir_limit = 5;
  837. resolve_lsa:
  838. lsa = xhost2sockaddr(server.host, server.port);
  839. if (!(option_mask32 & WGET_OPT_QUIET)) {
  840. char *s = xmalloc_sockaddr2dotted(&lsa->u.sa);
  841. fprintf(stderr, "Connecting to %s (%s)\n", server.host, s);
  842. free(s);
  843. }
  844. establish_session:
  845. /*G.content_len = 0; - redundant, got_clen = 0 is enough */
  846. G.got_clen = 0;
  847. G.chunked = 0;
  848. if (use_proxy || target.protocol != P_FTP) {
  849. /*
  850. * HTTP session
  851. */
  852. char *str;
  853. int status;
  854. /* Open socket to http(s) server */
  855. #if ENABLE_FEATURE_WGET_OPENSSL
  856. /* openssl (and maybe ssl_helper) support is configured */
  857. if (target.protocol == P_HTTPS) {
  858. /* openssl-based helper
  859. * Inconvenient API since we can't give it an open fd
  860. */
  861. int fd = spawn_https_helper_openssl(server.host, server.port);
  862. # if ENABLE_FEATURE_WGET_SSL_HELPER
  863. if (fd < 0) { /* no openssl? try ssl_helper */
  864. sfp = open_socket(lsa);
  865. spawn_https_helper_small(fileno(sfp));
  866. goto socket_opened;
  867. }
  868. # else
  869. /* We don't check for exec("openssl") failure in this case */
  870. # endif
  871. sfp = fdopen(fd, "r+");
  872. if (!sfp)
  873. bb_perror_msg_and_die(bb_msg_memory_exhausted);
  874. goto socket_opened;
  875. }
  876. sfp = open_socket(lsa);
  877. socket_opened:
  878. #elif ENABLE_FEATURE_WGET_SSL_HELPER
  879. /* Only ssl_helper support is configured */
  880. sfp = open_socket(lsa);
  881. if (target.protocol == P_HTTPS)
  882. spawn_https_helper_small(fileno(sfp));
  883. #else
  884. /* ssl (https) support is not configured */
  885. sfp = open_socket(lsa);
  886. #endif
  887. /* Send HTTP request */
  888. if (use_proxy) {
  889. SENDFMT(sfp, "GET %s://%s/%s HTTP/1.1\r\n",
  890. target.protocol, target.host,
  891. target.path);
  892. } else {
  893. SENDFMT(sfp, "%s /%s HTTP/1.1\r\n",
  894. (option_mask32 & WGET_OPT_POST_DATA) ? "POST" : "GET",
  895. target.path);
  896. }
  897. if (!USR_HEADER_HOST)
  898. SENDFMT(sfp, "Host: %s\r\n", target.host);
  899. if (!USR_HEADER_USER_AGENT)
  900. SENDFMT(sfp, "User-Agent: %s\r\n", G.user_agent);
  901. /* Ask server to close the connection as soon as we are done
  902. * (IOW: we do not intend to send more requests)
  903. */
  904. SENDFMT(sfp, "Connection: close\r\n");
  905. #if ENABLE_FEATURE_WGET_AUTHENTICATION
  906. if (target.user && !USR_HEADER_AUTH) {
  907. SENDFMT(sfp, "Proxy-Authorization: Basic %s\r\n"+6,
  908. base64enc(target.user));
  909. }
  910. if (use_proxy && server.user && !USR_HEADER_PROXY_AUTH) {
  911. SENDFMT(sfp, "Proxy-Authorization: Basic %s\r\n",
  912. base64enc(server.user));
  913. }
  914. #endif
  915. if (G.beg_range != 0 && !USR_HEADER_RANGE)
  916. SENDFMT(sfp, "Range: bytes=%"OFF_FMT"u-\r\n", G.beg_range);
  917. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  918. if (G.extra_headers) {
  919. log_io(G.extra_headers);
  920. fputs(G.extra_headers, sfp);
  921. }
  922. if (option_mask32 & WGET_OPT_POST_DATA) {
  923. SENDFMT(sfp,
  924. "Content-Type: application/x-www-form-urlencoded\r\n"
  925. "Content-Length: %u\r\n"
  926. "\r\n"
  927. "%s",
  928. (int) strlen(G.post_data), G.post_data
  929. );
  930. } else
  931. #endif
  932. {
  933. SENDFMT(sfp, "\r\n");
  934. }
  935. fflush(sfp);
  936. /*
  937. * Retrieve HTTP response line and check for "200" status code.
  938. */
  939. read_response:
  940. fgets_and_trim(sfp);
  941. str = G.wget_buf;
  942. str = skip_non_whitespace(str);
  943. str = skip_whitespace(str);
  944. // FIXME: no error check
  945. // xatou wouldn't work: "200 OK"
  946. status = atoi(str);
  947. switch (status) {
  948. case 0:
  949. case 100:
  950. while (gethdr(sfp) != NULL)
  951. /* eat all remaining headers */;
  952. goto read_response;
  953. case 200:
  954. /*
  955. Response 204 doesn't say "null file", it says "metadata
  956. has changed but data didn't":
  957. "10.2.5 204 No Content
  958. The server has fulfilled the request but does not need to return
  959. an entity-body, and might want to return updated metainformation.
  960. The response MAY include new or updated metainformation in the form
  961. of entity-headers, which if present SHOULD be associated with
  962. the requested variant.
  963. If the client is a user agent, it SHOULD NOT change its document
  964. view from that which caused the request to be sent. This response
  965. is primarily intended to allow input for actions to take place
  966. without causing a change to the user agent's active document view,
  967. although any new or updated metainformation SHOULD be applied
  968. to the document currently in the user agent's active view.
  969. The 204 response MUST NOT include a message-body, and thus
  970. is always terminated by the first empty line after the header fields."
  971. However, in real world it was observed that some web servers
  972. (e.g. Boa/0.94.14rc21) simply use code 204 when file size is zero.
  973. */
  974. case 204:
  975. if (G.beg_range != 0) {
  976. /* "Range:..." was not honored by the server.
  977. * Restart download from the beginning.
  978. */
  979. reset_beg_range_to_zero();
  980. }
  981. break;
  982. case 300: /* redirection */
  983. case 301:
  984. case 302:
  985. case 303:
  986. break;
  987. case 206: /* Partial Content */
  988. if (G.beg_range != 0)
  989. /* "Range:..." worked. Good. */
  990. break;
  991. /* Partial Content even though we did not ask for it??? */
  992. /* fall through */
  993. default:
  994. bb_error_msg_and_die("server returned error: %s", sanitize_string(G.wget_buf));
  995. }
  996. /*
  997. * Retrieve HTTP headers.
  998. */
  999. while ((str = gethdr(sfp)) != NULL) {
  1000. static const char keywords[] ALIGN1 =
  1001. "content-length\0""transfer-encoding\0""location\0";
  1002. enum {
  1003. KEY_content_length = 1, KEY_transfer_encoding, KEY_location
  1004. };
  1005. smalluint key;
  1006. /* gethdr converted "FOO:" string to lowercase */
  1007. /* strip trailing whitespace */
  1008. char *s = strchrnul(str, '\0') - 1;
  1009. while (s >= str && (*s == ' ' || *s == '\t')) {
  1010. *s = '\0';
  1011. s--;
  1012. }
  1013. key = index_in_strings(keywords, G.wget_buf) + 1;
  1014. if (key == KEY_content_length) {
  1015. G.content_len = BB_STRTOOFF(str, NULL, 10);
  1016. if (G.content_len < 0 || errno) {
  1017. bb_error_msg_and_die("content-length %s is garbage", sanitize_string(str));
  1018. }
  1019. G.got_clen = 1;
  1020. continue;
  1021. }
  1022. if (key == KEY_transfer_encoding) {
  1023. if (strcmp(str_tolower(str), "chunked") != 0)
  1024. bb_error_msg_and_die("transfer encoding '%s' is not supported", sanitize_string(str));
  1025. G.chunked = 1;
  1026. }
  1027. if (key == KEY_location && status >= 300) {
  1028. if (--redir_limit == 0)
  1029. bb_error_msg_and_die("too many redirections");
  1030. fclose(sfp);
  1031. if (str[0] == '/') {
  1032. free(redirected_path);
  1033. target.path = redirected_path = xstrdup(str+1);
  1034. /* lsa stays the same: it's on the same server */
  1035. } else {
  1036. parse_url(str, &target);
  1037. if (!use_proxy) {
  1038. /* server.user remains untouched */
  1039. free(server.allocated);
  1040. server.allocated = NULL;
  1041. server.host = target.host;
  1042. /* strip_ipv6_scope_id(target.host); - no! */
  1043. /* we assume remote never gives us IPv6 addr with scope id */
  1044. server.port = target.port;
  1045. free(lsa);
  1046. goto resolve_lsa;
  1047. } /* else: lsa stays the same: we use proxy */
  1048. }
  1049. goto establish_session;
  1050. }
  1051. }
  1052. // if (status >= 300)
  1053. // bb_error_msg_and_die("bad redirection (no Location: header from server)");
  1054. /* For HTTP, data is pumped over the same connection */
  1055. dfp = sfp;
  1056. } else {
  1057. /*
  1058. * FTP session
  1059. */
  1060. sfp = prepare_ftp_session(&dfp, &target, lsa);
  1061. }
  1062. free(lsa);
  1063. if (!(option_mask32 & WGET_OPT_SPIDER)) {
  1064. if (G.output_fd < 0)
  1065. G.output_fd = xopen(G.fname_out, G.o_flags);
  1066. retrieve_file_data(dfp);
  1067. if (!(option_mask32 & WGET_OPT_OUTNAME)) {
  1068. xclose(G.output_fd);
  1069. G.output_fd = -1;
  1070. }
  1071. }
  1072. if (dfp != sfp) {
  1073. /* It's ftp. Close data connection properly */
  1074. fclose(dfp);
  1075. if (ftpcmd(NULL, NULL, sfp) != 226)
  1076. bb_error_msg_and_die("ftp error: %s", sanitize_string(G.wget_buf + 4));
  1077. /* ftpcmd("QUIT", NULL, sfp); - why bother? */
  1078. }
  1079. fclose(sfp);
  1080. free(server.allocated);
  1081. free(target.allocated);
  1082. free(server.user);
  1083. free(target.user);
  1084. free(fname_out_alloc);
  1085. free(redirected_path);
  1086. }
  1087. int wget_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1088. int wget_main(int argc UNUSED_PARAM, char **argv)
  1089. {
  1090. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  1091. static const char wget_longopts[] ALIGN1 =
  1092. /* name, has_arg, val */
  1093. "continue\0" No_argument "c"
  1094. //FIXME: -s isn't --spider, it's --save-headers!
  1095. "spider\0" No_argument "s"
  1096. "quiet\0" No_argument "q"
  1097. "output-document\0" Required_argument "O"
  1098. "directory-prefix\0" Required_argument "P"
  1099. "proxy\0" Required_argument "Y"
  1100. "user-agent\0" Required_argument "U"
  1101. #if ENABLE_FEATURE_WGET_TIMEOUT
  1102. "timeout\0" Required_argument "T"
  1103. #endif
  1104. /* Ignored: */
  1105. // "tries\0" Required_argument "t"
  1106. /* Ignored (we always use PASV): */
  1107. "passive-ftp\0" No_argument "\xff"
  1108. "header\0" Required_argument "\xfe"
  1109. "post-data\0" Required_argument "\xfd"
  1110. /* Ignored (we don't do ssl) */
  1111. "no-check-certificate\0" No_argument "\xfc"
  1112. /* Ignored (we don't support caching) */
  1113. "no-cache\0" No_argument "\xfb"
  1114. ;
  1115. #endif
  1116. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  1117. llist_t *headers_llist = NULL;
  1118. #endif
  1119. INIT_G();
  1120. #if ENABLE_FEATURE_WGET_TIMEOUT
  1121. G.timeout_seconds = 900;
  1122. signal(SIGALRM, alarm_handler);
  1123. #endif
  1124. G.proxy_flag = "on"; /* use proxies if env vars are set */
  1125. G.user_agent = "Wget"; /* "User-Agent" header field */
  1126. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  1127. applet_long_options = wget_longopts;
  1128. #endif
  1129. opt_complementary = "-1"
  1130. IF_FEATURE_WGET_TIMEOUT(":T+")
  1131. IF_FEATURE_WGET_LONG_OPTIONS(":\xfe::");
  1132. getopt32(argv, "csqO:P:Y:U:T:" /*ignored:*/ "t:",
  1133. &G.fname_out, &G.dir_prefix,
  1134. &G.proxy_flag, &G.user_agent,
  1135. IF_FEATURE_WGET_TIMEOUT(&G.timeout_seconds) IF_NOT_FEATURE_WGET_TIMEOUT(NULL),
  1136. NULL /* -t RETRIES */
  1137. IF_FEATURE_WGET_LONG_OPTIONS(, &headers_llist)
  1138. IF_FEATURE_WGET_LONG_OPTIONS(, &G.post_data)
  1139. );
  1140. argv += optind;
  1141. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  1142. if (headers_llist) {
  1143. int size = 0;
  1144. char *hdr;
  1145. llist_t *ll = headers_llist;
  1146. while (ll) {
  1147. size += strlen(ll->data) + 2;
  1148. ll = ll->link;
  1149. }
  1150. G.extra_headers = hdr = xmalloc(size + 1);
  1151. while (headers_llist) {
  1152. int bit;
  1153. const char *words;
  1154. size = sprintf(hdr, "%s\r\n",
  1155. (char*)llist_pop(&headers_llist));
  1156. /* a bit like index_in_substrings but don't match full key */
  1157. bit = 1;
  1158. words = wget_user_headers;
  1159. while (*words) {
  1160. if (strstr(hdr, words) == hdr) {
  1161. G.user_headers |= bit;
  1162. break;
  1163. }
  1164. bit <<= 1;
  1165. words += strlen(words) + 1;
  1166. }
  1167. hdr += size;
  1168. }
  1169. }
  1170. #endif
  1171. G.output_fd = -1;
  1172. G.o_flags = O_WRONLY | O_CREAT | O_TRUNC | O_EXCL;
  1173. if (G.fname_out) { /* -O FILE ? */
  1174. if (LONE_DASH(G.fname_out)) { /* -O - ? */
  1175. G.output_fd = 1;
  1176. option_mask32 &= ~WGET_OPT_CONTINUE;
  1177. }
  1178. /* compat with wget: -O FILE can overwrite */
  1179. G.o_flags = O_WRONLY | O_CREAT | O_TRUNC;
  1180. }
  1181. while (*argv)
  1182. download_one_url(*argv++);
  1183. if (G.output_fd >= 0)
  1184. xclose(G.output_fd);
  1185. #if ENABLE_FEATURE_CLEAN_UP && ENABLE_FEATURE_WGET_LONG_OPTIONS
  1186. free(G.extra_headers);
  1187. #endif
  1188. FINI_G();
  1189. return EXIT_SUCCESS;
  1190. }