wget.c 37 KB

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