wget.c 44 KB

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