wget.c 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536
  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 (38 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. int output_fd;
  227. int o_flags;
  228. #if ENABLE_FEATURE_WGET_TIMEOUT
  229. unsigned timeout_seconds;
  230. smallint die_if_timed_out;
  231. #endif
  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. char wget_buf[CONFIG_FEATURE_COPYBUF_KB*1024] ALIGNED(sizeof(long));
  239. } FIX_ALIASING;
  240. #define G (*ptr_to_globals)
  241. #define INIT_G() do { \
  242. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  243. } while (0)
  244. #define FINI_G() do { \
  245. FREE_PTR_TO_GLOBALS(); \
  246. } while (0)
  247. /* Must match option string! */
  248. enum {
  249. WGET_OPT_CONTINUE = (1 << 0),
  250. WGET_OPT_QUIET = (1 << 1),
  251. WGET_OPT_SERVER_RESPONSE = (1 << 2),
  252. WGET_OPT_OUTNAME = (1 << 3),
  253. WGET_OPT_PREFIX = (1 << 4),
  254. WGET_OPT_PROXY = (1 << 5),
  255. WGET_OPT_USER_AGENT = (1 << 6),
  256. WGET_OPT_NETWORK_READ_TIMEOUT = (1 << 7),
  257. WGET_OPT_RETRIES = (1 << 8),
  258. WGET_OPT_nsomething = (1 << 9),
  259. WGET_OPT_HEADER = (1 << 10) * ENABLE_FEATURE_WGET_LONG_OPTIONS,
  260. WGET_OPT_POST_DATA = (1 << 11) * ENABLE_FEATURE_WGET_LONG_OPTIONS,
  261. WGET_OPT_SPIDER = (1 << 12) * ENABLE_FEATURE_WGET_LONG_OPTIONS,
  262. WGET_OPT_NO_CHECK_CERT = (1 << 13) * ENABLE_FEATURE_WGET_LONG_OPTIONS,
  263. };
  264. enum {
  265. PROGRESS_START = -1,
  266. PROGRESS_END = 0,
  267. PROGRESS_BUMP = 1,
  268. };
  269. #if ENABLE_FEATURE_WGET_STATUSBAR
  270. static void progress_meter(int flag)
  271. {
  272. int notty;
  273. if (option_mask32 & WGET_OPT_QUIET)
  274. return;
  275. if (flag == PROGRESS_START)
  276. bb_progress_init(&G.pmt, G.curfile);
  277. notty = 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. if (notty == 0)
  285. bb_putchar_stderr('\n'); /* it's tty */
  286. G.transferred = 0;
  287. }
  288. }
  289. #else
  290. static ALWAYS_INLINE void progress_meter(int flag UNUSED_PARAM) { }
  291. #endif
  292. /* IPv6 knows scoped address types i.e. link and site local addresses. Link
  293. * local addresses can have a scope identifier to specify the
  294. * interface/link an address is valid on (e.g. fe80::1%eth0). This scope
  295. * identifier is only valid on a single node.
  296. *
  297. * RFC 4007 says that the scope identifier MUST NOT be sent across the wire,
  298. * unless all nodes agree on the semantic. Apache e.g. regards zone identifiers
  299. * in the Host header as invalid requests, see
  300. * https://issues.apache.org/bugzilla/show_bug.cgi?id=35122
  301. */
  302. static void strip_ipv6_scope_id(char *host)
  303. {
  304. char *scope, *cp;
  305. /* bbox wget actually handles IPv6 addresses without [], like
  306. * wget "http://::1/xxx", but this is not standard.
  307. * To save code, _here_ we do not support it. */
  308. if (host[0] != '[')
  309. return; /* not IPv6 */
  310. scope = strchr(host, '%');
  311. if (!scope)
  312. return;
  313. /* Remove the IPv6 zone identifier from the host address */
  314. cp = strchr(host, ']');
  315. if (!cp || (cp[1] != ':' && cp[1] != '\0')) {
  316. /* malformed address (not "[xx]:nn" or "[xx]") */
  317. return;
  318. }
  319. /* cp points to "]...", scope points to "%eth0]..." */
  320. overlapping_strcpy(scope, cp);
  321. }
  322. #if ENABLE_FEATURE_WGET_AUTHENTICATION
  323. /* Base64-encode character string. */
  324. static char *base64enc(const char *str)
  325. {
  326. /* paranoia */
  327. unsigned len = strnlen(str, 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. option_mask32 |= WGET_OPT_NO_CHECK_CERT;
  657. bb_error_msg("note: TLS certificate validation not implemented");
  658. }
  659. servername = xstrdup(host);
  660. p = strrchr(servername, ':');
  661. if (p) *p = '\0';
  662. if (socketpair(AF_UNIX, SOCK_STREAM, 0, sp) != 0)
  663. /* Kernel can have AF_UNIX support disabled */
  664. bb_perror_msg_and_die("socketpair");
  665. fflush_all();
  666. pid = BB_MMU ? xfork() : xvfork();
  667. if (pid == 0) {
  668. /* Child */
  669. close(sp[0]);
  670. xmove_fd(sp[1], 0);
  671. xdup2(0, 1);
  672. if (BB_MMU) {
  673. tls_state_t *tls = new_tls_state();
  674. tls->ifd = tls->ofd = network_fd;
  675. tls_handshake(tls, servername);
  676. tls_run_copy_loop(tls, flags);
  677. exit(0);
  678. } else {
  679. char *argv[6];
  680. xmove_fd(network_fd, 3);
  681. argv[0] = (char*)"ssl_client";
  682. argv[1] = (char*)"-s3";
  683. //TODO: if (!is_ip_address(servername))...
  684. argv[2] = (char*)"-n";
  685. argv[3] = servername;
  686. argv[4] = (flags & TLSLOOP_EXIT_ON_LOCAL_EOF ? (char*)"-e" : NULL);
  687. argv[5] = NULL;
  688. BB_EXECVP(argv[0], argv);
  689. bb_perror_msg_and_die("can't execute '%s'", argv[0]);
  690. }
  691. /* notreached */
  692. }
  693. /* Parent */
  694. free(servername);
  695. close(sp[1]);
  696. xmove_fd(sp[0], network_fd);
  697. }
  698. #endif
  699. static FILE* prepare_ftp_session(FILE **dfpp, struct host_info *target, len_and_sockaddr *lsa)
  700. {
  701. FILE *sfp;
  702. char *pass;
  703. int port;
  704. sfp = open_socket(lsa);
  705. #if ENABLE_FEATURE_WGET_HTTPS
  706. if (target->protocol == P_FTPS)
  707. spawn_ssl_client(target->host, fileno(sfp), TLSLOOP_EXIT_ON_LOCAL_EOF);
  708. #endif
  709. if (ftpcmd(NULL, NULL, sfp) != 220)
  710. bb_error_msg_and_die("%s", G.wget_buf);
  711. /* note: ftpcmd() sanitizes G.wget_buf, ok to print */
  712. /* Split username:password pair */
  713. pass = (char*)"busybox"; /* password for "anonymous" */
  714. if (target->user) {
  715. pass = strchr(target->user, ':');
  716. if (pass)
  717. *pass++ = '\0';
  718. }
  719. /* Log in */
  720. switch (ftpcmd("USER ", target->user ?: "anonymous", sfp)) {
  721. case 230:
  722. break;
  723. case 331:
  724. if (ftpcmd("PASS ", pass, sfp) == 230)
  725. break;
  726. /* fall through (failed login) */
  727. default:
  728. bb_error_msg_and_die("ftp login: %s", G.wget_buf);
  729. }
  730. ftpcmd("TYPE I", NULL, sfp);
  731. /* Query file size */
  732. if (ftpcmd("SIZE ", target->path, sfp) == 213) {
  733. G.content_len = BB_STRTOOFF(G.wget_buf + 4, NULL, 10);
  734. if (G.content_len < 0 || errno) {
  735. bb_error_msg_and_die("bad SIZE value '%s'", G.wget_buf + 4);
  736. }
  737. G.got_clen = 1;
  738. }
  739. /* Enter passive mode */
  740. if (ENABLE_FEATURE_IPV6 && ftpcmd("EPSV", NULL, sfp) == 229) {
  741. /* good */
  742. } else
  743. if (ftpcmd("PASV", NULL, sfp) != 227) {
  744. pasv_error:
  745. bb_error_msg_and_die("bad response to %s: %s", "PASV", G.wget_buf);
  746. }
  747. port = parse_pasv_epsv(G.wget_buf);
  748. if (port < 0)
  749. goto pasv_error;
  750. set_nport(&lsa->u.sa, htons(port));
  751. *dfpp = open_socket(lsa);
  752. #if ENABLE_FEATURE_WGET_HTTPS
  753. if (target->protocol == P_FTPS) {
  754. /* "PROT P" enables encryption of data stream.
  755. * Without it (or with "PROT C"), data is sent unencrypted.
  756. */
  757. if (ftpcmd("PROT P", NULL, sfp) == 200)
  758. spawn_ssl_client(target->host, fileno(*dfpp), /*flags*/ 0);
  759. }
  760. #endif
  761. if (G.beg_range != 0) {
  762. sprintf(G.wget_buf, "REST %"OFF_FMT"u", G.beg_range);
  763. if (ftpcmd(G.wget_buf, NULL, sfp) == 350)
  764. G.content_len -= G.beg_range;
  765. else
  766. reset_beg_range_to_zero();
  767. }
  768. //TODO: needs ftp-escaping 0xff and '\n' bytes here.
  769. //Or disallow '\n' altogether via sanitize_string() in parse_url().
  770. //But 0xff's are possible in valid utf8 filenames.
  771. if (ftpcmd("RETR ", target->path, sfp) > 150)
  772. bb_error_msg_and_die("bad response to %s: %s", "RETR", G.wget_buf);
  773. return sfp;
  774. }
  775. static void NOINLINE retrieve_file_data(FILE *dfp)
  776. {
  777. #if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
  778. # if ENABLE_FEATURE_WGET_TIMEOUT
  779. unsigned second_cnt = G.timeout_seconds;
  780. # endif
  781. struct pollfd polldata;
  782. polldata.fd = fileno(dfp);
  783. polldata.events = POLLIN | POLLPRI;
  784. #endif
  785. progress_meter(PROGRESS_START);
  786. if (G.chunked)
  787. goto get_clen;
  788. /* Loops only if chunked */
  789. while (1) {
  790. #if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
  791. /* Must use nonblocking I/O, otherwise fread will loop
  792. * and *block* until it reads full buffer,
  793. * which messes up progress bar and/or timeout logic.
  794. * Because of nonblocking I/O, we need to dance
  795. * very carefully around EAGAIN. See explanation at
  796. * clearerr() calls.
  797. */
  798. ndelay_on(polldata.fd);
  799. #endif
  800. while (1) {
  801. int n;
  802. unsigned rdsz;
  803. #if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
  804. /* fread internally uses read loop, which in our case
  805. * is usually exited when we get EAGAIN.
  806. * In this case, libc sets error marker on the stream.
  807. * Need to clear it before next fread to avoid possible
  808. * rare false positive ferror below. Rare because usually
  809. * fread gets more than zero bytes, and we don't fall
  810. * into if (n <= 0) ...
  811. */
  812. clearerr(dfp);
  813. #endif
  814. errno = 0;
  815. rdsz = sizeof(G.wget_buf);
  816. if (G.got_clen) {
  817. if (G.content_len < (off_t)sizeof(G.wget_buf)) {
  818. if ((int)G.content_len <= 0)
  819. break;
  820. rdsz = (unsigned)G.content_len;
  821. }
  822. }
  823. n = fread(G.wget_buf, 1, rdsz, dfp);
  824. if (n > 0) {
  825. xwrite(G.output_fd, G.wget_buf, n);
  826. #if ENABLE_FEATURE_WGET_STATUSBAR
  827. G.transferred += n;
  828. #endif
  829. if (G.got_clen) {
  830. G.content_len -= n;
  831. if (G.content_len == 0)
  832. break;
  833. }
  834. #if ENABLE_FEATURE_WGET_TIMEOUT
  835. second_cnt = G.timeout_seconds;
  836. #endif
  837. goto bump;
  838. }
  839. /* n <= 0.
  840. * man fread:
  841. * If error occurs, or EOF is reached, the return value
  842. * is a short item count (or zero).
  843. * fread does not distinguish between EOF and error.
  844. */
  845. if (errno != EAGAIN) {
  846. if (ferror(dfp)) {
  847. progress_meter(PROGRESS_END);
  848. bb_perror_msg_and_die(bb_msg_read_error);
  849. }
  850. break; /* EOF, not error */
  851. }
  852. #if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
  853. /* It was EAGAIN. There is no data. Wait up to one second
  854. * then abort if timed out, or update the bar and try reading again.
  855. */
  856. if (safe_poll(&polldata, 1, 1000) == 0) {
  857. # if ENABLE_FEATURE_WGET_TIMEOUT
  858. if (second_cnt != 0 && --second_cnt == 0) {
  859. progress_meter(PROGRESS_END);
  860. bb_error_msg_and_die("download timed out");
  861. }
  862. # endif
  863. /* We used to loop back to poll here,
  864. * but there is no great harm in letting fread
  865. * to try reading anyway.
  866. */
  867. }
  868. #endif
  869. bump:
  870. /* Need to do it _every_ second for "stalled" indicator
  871. * to be shown properly.
  872. */
  873. progress_meter(PROGRESS_BUMP);
  874. } /* while (reading data) */
  875. #if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
  876. clearerr(dfp);
  877. ndelay_off(polldata.fd); /* else fgets can get very unhappy */
  878. #endif
  879. if (!G.chunked)
  880. break;
  881. /* Each chunk ends with "\r\n" - eat it */
  882. fgets_trim_sanitize(dfp, NULL);
  883. get_clen:
  884. /* chunk size format is "HEXNUM[;name[=val]]\r\n" */
  885. fgets_trim_sanitize(dfp, NULL);
  886. errno = 0;
  887. G.content_len = STRTOOFF(G.wget_buf, NULL, 16);
  888. /*
  889. * Had a bug with inputs like "ffffffff0001f400"
  890. * smashing the heap later. Ensure >= 0.
  891. */
  892. if (G.content_len < 0 || errno)
  893. bb_error_msg_and_die("bad chunk length '%s'", G.wget_buf);
  894. if (G.content_len == 0)
  895. break; /* all done! */
  896. G.got_clen = 1;
  897. /*
  898. * Note that fgets may result in some data being buffered in dfp.
  899. * We loop back to fread, which will retrieve this data.
  900. * Also note that code has to be arranged so that fread
  901. * is done _before_ one-second poll wait - poll doesn't know
  902. * about stdio buffering and can result in spurious one second waits!
  903. */
  904. }
  905. /* If -c failed, we restart from the beginning,
  906. * but we do not truncate file then, we do it only now, at the end.
  907. * This lets user to ^C if his 99% complete 10 GB file download
  908. * failed to restart *without* losing the almost complete file.
  909. */
  910. {
  911. off_t pos = lseek(G.output_fd, 0, SEEK_CUR);
  912. if (pos != (off_t)-1)
  913. ftruncate(G.output_fd, pos);
  914. }
  915. /* Draw full bar and free its resources */
  916. G.chunked = 0; /* makes it show 100% even for chunked download */
  917. G.got_clen = 1; /* makes it show 100% even for download of (formerly) unknown size */
  918. progress_meter(PROGRESS_END);
  919. }
  920. static void download_one_url(const char *url)
  921. {
  922. bool use_proxy; /* Use proxies if env vars are set */
  923. int redir_limit;
  924. len_and_sockaddr *lsa;
  925. FILE *sfp; /* socket to web/ftp server */
  926. FILE *dfp; /* socket to ftp server (data) */
  927. char *fname_out_alloc;
  928. char *redirected_path = NULL;
  929. struct host_info server;
  930. struct host_info target;
  931. server.allocated = NULL;
  932. target.allocated = NULL;
  933. server.user = NULL;
  934. target.user = NULL;
  935. parse_url(url, &target);
  936. /* Use the proxy if necessary */
  937. use_proxy = (strcmp(G.proxy_flag, "off") != 0);
  938. if (use_proxy) {
  939. char *proxy = getenv(target.protocol[0] == 'f' ? "ftp_proxy" : "http_proxy");
  940. //FIXME: what if protocol is https? Ok to use http_proxy?
  941. use_proxy = (proxy && proxy[0]);
  942. if (use_proxy)
  943. parse_url(proxy, &server);
  944. }
  945. if (!use_proxy) {
  946. server.protocol = target.protocol;
  947. server.port = target.port;
  948. if (ENABLE_FEATURE_IPV6) {
  949. //free(server.allocated); - can't be non-NULL
  950. server.host = server.allocated = xstrdup(target.host);
  951. } else {
  952. server.host = target.host;
  953. }
  954. }
  955. if (ENABLE_FEATURE_IPV6)
  956. strip_ipv6_scope_id(target.host);
  957. /* If there was no -O FILE, guess output filename */
  958. fname_out_alloc = NULL;
  959. if (!(option_mask32 & WGET_OPT_OUTNAME)) {
  960. G.fname_out = bb_get_last_path_component_nostrip(target.path);
  961. /* handle "wget http://kernel.org//" */
  962. if (G.fname_out[0] == '/' || !G.fname_out[0])
  963. G.fname_out = (char*)"index.html";
  964. /* -P DIR is considered only if there was no -O FILE */
  965. if (G.dir_prefix)
  966. G.fname_out = fname_out_alloc = concat_path_file(G.dir_prefix, G.fname_out);
  967. else {
  968. /* redirects may free target.path later, need to make a copy */
  969. G.fname_out = fname_out_alloc = xstrdup(G.fname_out);
  970. }
  971. }
  972. #if ENABLE_FEATURE_WGET_STATUSBAR
  973. G.curfile = bb_get_last_path_component_nostrip(G.fname_out);
  974. #endif
  975. /* Determine where to start transfer */
  976. G.beg_range = 0;
  977. if (option_mask32 & WGET_OPT_CONTINUE) {
  978. G.output_fd = open(G.fname_out, O_WRONLY);
  979. if (G.output_fd >= 0) {
  980. G.beg_range = xlseek(G.output_fd, 0, SEEK_END);
  981. }
  982. /* File doesn't exist. We do not create file here yet.
  983. * We are not sure it exists on remote side */
  984. }
  985. redir_limit = 5;
  986. resolve_lsa:
  987. lsa = xhost2sockaddr(server.host, server.port);
  988. if (!(option_mask32 & WGET_OPT_QUIET)) {
  989. char *s = xmalloc_sockaddr2dotted(&lsa->u.sa);
  990. fprintf(stderr, "Connecting to %s (%s)\n", server.host, s);
  991. free(s);
  992. }
  993. establish_session:
  994. /*G.content_len = 0; - redundant, got_clen = 0 is enough */
  995. G.got_clen = 0;
  996. G.chunked = 0;
  997. if (use_proxy || target.protocol[0] != 'f' /*not ftp[s]*/) {
  998. /*
  999. * HTTP session
  1000. */
  1001. char *str;
  1002. int status;
  1003. /* Open socket to http(s) server */
  1004. #if ENABLE_FEATURE_WGET_OPENSSL
  1005. /* openssl (and maybe internal TLS) support is configured */
  1006. if (server.protocol == P_HTTPS) {
  1007. /* openssl-based helper
  1008. * Inconvenient API since we can't give it an open fd
  1009. */
  1010. int fd = spawn_https_helper_openssl(server.host, server.port);
  1011. # if ENABLE_FEATURE_WGET_HTTPS
  1012. if (fd < 0) { /* no openssl? try internal */
  1013. sfp = open_socket(lsa);
  1014. spawn_ssl_client(server.host, fileno(sfp), /*flags*/ 0);
  1015. goto socket_opened;
  1016. }
  1017. # else
  1018. /* We don't check for exec("openssl") failure in this case */
  1019. # endif
  1020. sfp = fdopen(fd, "r+");
  1021. if (!sfp)
  1022. bb_die_memory_exhausted();
  1023. goto socket_opened;
  1024. }
  1025. sfp = open_socket(lsa);
  1026. socket_opened:
  1027. #elif ENABLE_FEATURE_WGET_HTTPS
  1028. /* Only internal TLS support is configured */
  1029. sfp = open_socket(lsa);
  1030. if (server.protocol == P_HTTPS)
  1031. spawn_ssl_client(server.host, fileno(sfp), /*flags*/ 0);
  1032. #else
  1033. /* ssl (https) support is not configured */
  1034. sfp = open_socket(lsa);
  1035. #endif
  1036. /* Send HTTP request */
  1037. if (use_proxy) {
  1038. SENDFMT(sfp, "GET %s://%s/%s HTTP/1.1\r\n",
  1039. target.protocol, target.host,
  1040. target.path);
  1041. } else {
  1042. SENDFMT(sfp, "%s /%s HTTP/1.1\r\n",
  1043. (option_mask32 & WGET_OPT_POST_DATA) ? "POST" : "GET",
  1044. target.path);
  1045. }
  1046. if (!USR_HEADER_HOST)
  1047. SENDFMT(sfp, "Host: %s\r\n", target.host);
  1048. if (!USR_HEADER_USER_AGENT)
  1049. SENDFMT(sfp, "User-Agent: %s\r\n", G.user_agent);
  1050. /* Ask server to close the connection as soon as we are done
  1051. * (IOW: we do not intend to send more requests)
  1052. */
  1053. SENDFMT(sfp, "Connection: close\r\n");
  1054. #if ENABLE_FEATURE_WGET_AUTHENTICATION
  1055. if (target.user && !USR_HEADER_AUTH) {
  1056. SENDFMT(sfp, "Proxy-Authorization: Basic %s\r\n"+6,
  1057. base64enc(target.user));
  1058. }
  1059. if (use_proxy && server.user && !USR_HEADER_PROXY_AUTH) {
  1060. SENDFMT(sfp, "Proxy-Authorization: Basic %s\r\n",
  1061. base64enc(server.user));
  1062. }
  1063. #endif
  1064. if (G.beg_range != 0 && !USR_HEADER_RANGE)
  1065. SENDFMT(sfp, "Range: bytes=%"OFF_FMT"u-\r\n", G.beg_range);
  1066. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  1067. if (G.extra_headers) {
  1068. log_io(G.extra_headers);
  1069. fputs(G.extra_headers, sfp);
  1070. }
  1071. if (option_mask32 & WGET_OPT_POST_DATA) {
  1072. SENDFMT(sfp,
  1073. "Content-Type: application/x-www-form-urlencoded\r\n"
  1074. "Content-Length: %u\r\n"
  1075. "\r\n"
  1076. "%s",
  1077. (int) strlen(G.post_data), G.post_data
  1078. );
  1079. } else
  1080. #endif
  1081. {
  1082. SENDFMT(sfp, "\r\n");
  1083. }
  1084. fflush(sfp);
  1085. /* Tried doing this unconditionally.
  1086. * Cloudflare and nginx/1.11.5 are shocked to see SHUT_WR on non-HTTPS.
  1087. */
  1088. #if SSL_SUPPORTED
  1089. if (target.protocol == P_HTTPS) {
  1090. /* If we use SSL helper, keeping our end of the socket open for writing
  1091. * makes our end (i.e. the same fd!) readable (EAGAIN instead of EOF)
  1092. * even after child closes its copy of the fd.
  1093. * This helps:
  1094. */
  1095. shutdown(fileno(sfp), SHUT_WR);
  1096. }
  1097. #endif
  1098. /*
  1099. * Retrieve HTTP response line and check for "200" status code.
  1100. */
  1101. read_response:
  1102. fgets_trim_sanitize(sfp, " %s\n");
  1103. str = G.wget_buf;
  1104. str = skip_non_whitespace(str);
  1105. str = skip_whitespace(str);
  1106. // FIXME: no error check
  1107. // xatou wouldn't work: "200 OK"
  1108. status = atoi(str);
  1109. switch (status) {
  1110. case 0:
  1111. case 100:
  1112. while (get_sanitized_hdr(sfp) != NULL)
  1113. /* eat all remaining headers */;
  1114. goto read_response;
  1115. /* Success responses */
  1116. case 200:
  1117. /* fall through */
  1118. case 201: /* 201 Created */
  1119. /* "The request has been fulfilled and resulted in a new resource being created" */
  1120. /* Standard wget is reported to treat this as success */
  1121. /* fall through */
  1122. case 202: /* 202 Accepted */
  1123. /* "The request has been accepted for processing, but the processing has not been completed" */
  1124. /* Treat as success: fall through */
  1125. case 203: /* 203 Non-Authoritative Information */
  1126. /* "Use of this response code is not required and is only appropriate when the response would otherwise be 200 (OK)" */
  1127. /* fall through */
  1128. case 204: /* 204 No Content */
  1129. /*
  1130. Response 204 doesn't say "null file", it says "metadata
  1131. has changed but data didn't":
  1132. "10.2.5 204 No Content
  1133. The server has fulfilled the request but does not need to return
  1134. an entity-body, and might want to return updated metainformation.
  1135. The response MAY include new or updated metainformation in the form
  1136. of entity-headers, which if present SHOULD be associated with
  1137. the requested variant.
  1138. If the client is a user agent, it SHOULD NOT change its document
  1139. view from that which caused the request to be sent. This response
  1140. is primarily intended to allow input for actions to take place
  1141. without causing a change to the user agent's active document view,
  1142. although any new or updated metainformation SHOULD be applied
  1143. to the document currently in the user agent's active view.
  1144. The 204 response MUST NOT include a message-body, and thus
  1145. is always terminated by the first empty line after the header fields."
  1146. However, in real world it was observed that some web servers
  1147. (e.g. Boa/0.94.14rc21) simply use code 204 when file size is zero.
  1148. */
  1149. if (G.beg_range != 0) {
  1150. /* "Range:..." was not honored by the server.
  1151. * Restart download from the beginning.
  1152. */
  1153. reset_beg_range_to_zero();
  1154. }
  1155. break;
  1156. /* 205 Reset Content ?? what to do on this ?? */
  1157. case 300: /* redirection */
  1158. case 301:
  1159. case 302:
  1160. case 303:
  1161. break;
  1162. case 206: /* Partial Content */
  1163. if (G.beg_range != 0)
  1164. /* "Range:..." worked. Good. */
  1165. break;
  1166. /* Partial Content even though we did not ask for it??? */
  1167. /* fall through */
  1168. default:
  1169. bb_error_msg_and_die("server returned error: %s", G.wget_buf);
  1170. }
  1171. /*
  1172. * Retrieve HTTP headers.
  1173. */
  1174. while ((str = get_sanitized_hdr(sfp)) != NULL) {
  1175. static const char keywords[] ALIGN1 =
  1176. "content-length\0""transfer-encoding\0""location\0";
  1177. enum {
  1178. KEY_content_length = 1, KEY_transfer_encoding, KEY_location
  1179. };
  1180. smalluint key;
  1181. /* get_sanitized_hdr converted "FOO:" string to lowercase */
  1182. /* strip trailing whitespace */
  1183. char *s = strchrnul(str, '\0') - 1;
  1184. while (s >= str && (*s == ' ' || *s == '\t')) {
  1185. *s = '\0';
  1186. s--;
  1187. }
  1188. key = index_in_strings(keywords, G.wget_buf) + 1;
  1189. if (key == KEY_content_length) {
  1190. G.content_len = BB_STRTOOFF(str, NULL, 10);
  1191. if (G.content_len < 0 || errno) {
  1192. bb_error_msg_and_die("content-length %s is garbage", str);
  1193. }
  1194. G.got_clen = 1;
  1195. continue;
  1196. }
  1197. if (key == KEY_transfer_encoding) {
  1198. if (strcmp(str_tolower(str), "chunked") != 0)
  1199. bb_error_msg_and_die("transfer encoding '%s' is not supported", str);
  1200. G.chunked = 1;
  1201. }
  1202. if (key == KEY_location && status >= 300) {
  1203. if (--redir_limit == 0)
  1204. bb_error_msg_and_die("too many redirections");
  1205. fclose(sfp);
  1206. if (str[0] == '/') {
  1207. free(redirected_path);
  1208. target.path = redirected_path = xstrdup(str + 1);
  1209. /* lsa stays the same: it's on the same server */
  1210. } else {
  1211. parse_url(str, &target);
  1212. if (!use_proxy) {
  1213. /* server.user remains untouched */
  1214. free(server.allocated);
  1215. server.allocated = NULL;
  1216. server.protocol = target.protocol;
  1217. server.host = target.host;
  1218. /* strip_ipv6_scope_id(target.host); - no! */
  1219. /* we assume remote never gives us IPv6 addr with scope id */
  1220. server.port = target.port;
  1221. free(lsa);
  1222. goto resolve_lsa;
  1223. } /* else: lsa stays the same: we use proxy */
  1224. }
  1225. goto establish_session;
  1226. }
  1227. }
  1228. // if (status >= 300)
  1229. // bb_error_msg_and_die("bad redirection (no Location: header from server)");
  1230. /* For HTTP, data is pumped over the same connection */
  1231. dfp = sfp;
  1232. } else {
  1233. /*
  1234. * FTP session
  1235. */
  1236. sfp = prepare_ftp_session(&dfp, &target, lsa);
  1237. }
  1238. free(lsa);
  1239. if (!(option_mask32 & WGET_OPT_SPIDER)) {
  1240. if (G.output_fd < 0)
  1241. G.output_fd = xopen(G.fname_out, G.o_flags);
  1242. retrieve_file_data(dfp);
  1243. if (!(option_mask32 & WGET_OPT_OUTNAME)) {
  1244. xclose(G.output_fd);
  1245. G.output_fd = -1;
  1246. }
  1247. }
  1248. if (dfp != sfp) {
  1249. /* It's ftp. Close data connection properly */
  1250. fclose(dfp);
  1251. if (ftpcmd(NULL, NULL, sfp) != 226)
  1252. bb_error_msg_and_die("ftp error: %s", G.wget_buf);
  1253. /* ftpcmd("QUIT", NULL, sfp); - why bother? */
  1254. }
  1255. fclose(sfp);
  1256. free(server.allocated);
  1257. free(target.allocated);
  1258. free(server.user);
  1259. free(target.user);
  1260. free(fname_out_alloc);
  1261. free(redirected_path);
  1262. }
  1263. int wget_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1264. int wget_main(int argc UNUSED_PARAM, char **argv)
  1265. {
  1266. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  1267. static const char wget_longopts[] ALIGN1 =
  1268. /* name, has_arg, val */
  1269. "continue\0" No_argument "c"
  1270. "quiet\0" No_argument "q"
  1271. "server-response\0" No_argument "S"
  1272. "output-document\0" Required_argument "O"
  1273. "directory-prefix\0" Required_argument "P"
  1274. "proxy\0" Required_argument "Y"
  1275. "user-agent\0" Required_argument "U"
  1276. IF_FEATURE_WGET_TIMEOUT(
  1277. "timeout\0" Required_argument "T")
  1278. /* Ignored: */
  1279. IF_DESKTOP( "tries\0" Required_argument "t")
  1280. "header\0" Required_argument "\xff"
  1281. "post-data\0" Required_argument "\xfe"
  1282. "spider\0" No_argument "\xfd"
  1283. "no-check-certificate\0" No_argument "\xfc"
  1284. /* Ignored (we always use PASV): */
  1285. IF_DESKTOP( "passive-ftp\0" No_argument "\xf0")
  1286. /* Ignored (we don't support caching) */
  1287. IF_DESKTOP( "no-cache\0" No_argument "\xf0")
  1288. IF_DESKTOP( "no-verbose\0" No_argument "\xf0")
  1289. IF_DESKTOP( "no-clobber\0" No_argument "\xf0")
  1290. IF_DESKTOP( "no-host-directories\0" No_argument "\xf0")
  1291. IF_DESKTOP( "no-parent\0" No_argument "\xf0")
  1292. ;
  1293. # define GETOPT32 getopt32long
  1294. # define LONGOPTS ,wget_longopts
  1295. #else
  1296. # define GETOPT32 getopt32
  1297. # define LONGOPTS
  1298. #endif
  1299. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  1300. llist_t *headers_llist = NULL;
  1301. #endif
  1302. INIT_G();
  1303. #if ENABLE_FEATURE_WGET_TIMEOUT
  1304. G.timeout_seconds = 900;
  1305. signal(SIGALRM, alarm_handler);
  1306. #endif
  1307. G.proxy_flag = "on"; /* use proxies if env vars are set */
  1308. G.user_agent = "Wget"; /* "User-Agent" header field */
  1309. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  1310. #endif
  1311. GETOPT32(argv, "^"
  1312. "cqSO:P:Y:U:T:+"
  1313. /*ignored:*/ "t:"
  1314. /*ignored:*/ "n::"
  1315. /* wget has exactly four -n<letter> opts, all of which we can ignore:
  1316. * -nv --no-verbose: be moderately quiet (-q is full quiet)
  1317. * -nc --no-clobber: abort if exists, neither download to FILE.n nor overwrite FILE
  1318. * -nH --no-host-directories: wget -r http://host/ won't create host/
  1319. * -np --no-parent
  1320. * "n::" above says that we accept -n[ARG].
  1321. * Specifying "n:" would be a bug: "-n ARG" would eat ARG!
  1322. */
  1323. "\0"
  1324. "-1" /* at least one URL */
  1325. IF_FEATURE_WGET_LONG_OPTIONS(":\xff::") /* --header is a list */
  1326. LONGOPTS
  1327. , &G.fname_out, &G.dir_prefix,
  1328. &G.proxy_flag, &G.user_agent,
  1329. IF_FEATURE_WGET_TIMEOUT(&G.timeout_seconds) IF_NOT_FEATURE_WGET_TIMEOUT(NULL),
  1330. NULL, /* -t RETRIES */
  1331. NULL /* -n[ARG] */
  1332. IF_FEATURE_WGET_LONG_OPTIONS(, &headers_llist)
  1333. IF_FEATURE_WGET_LONG_OPTIONS(, &G.post_data)
  1334. );
  1335. #if 0 /* option bits debug */
  1336. if (option_mask32 & WGET_OPT_RETRIES) bb_error_msg("-t NUM");
  1337. if (option_mask32 & WGET_OPT_nsomething) bb_error_msg("-nsomething");
  1338. if (option_mask32 & WGET_OPT_HEADER) bb_error_msg("--header");
  1339. if (option_mask32 & WGET_OPT_POST_DATA) bb_error_msg("--post-data");
  1340. if (option_mask32 & WGET_OPT_SPIDER) bb_error_msg("--spider");
  1341. if (option_mask32 & WGET_OPT_NO_CHECK_CERT) bb_error_msg("--no-check-certificate");
  1342. exit(0);
  1343. #endif
  1344. argv += optind;
  1345. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  1346. if (headers_llist) {
  1347. int size = 0;
  1348. char *hdr;
  1349. llist_t *ll = headers_llist;
  1350. while (ll) {
  1351. size += strlen(ll->data) + 2;
  1352. ll = ll->link;
  1353. }
  1354. G.extra_headers = hdr = xmalloc(size + 1);
  1355. while (headers_llist) {
  1356. int bit;
  1357. const char *words;
  1358. size = sprintf(hdr, "%s\r\n",
  1359. (char*)llist_pop(&headers_llist));
  1360. /* a bit like index_in_substrings but don't match full key */
  1361. bit = 1;
  1362. words = wget_user_headers;
  1363. while (*words) {
  1364. if (strstr(hdr, words) == hdr) {
  1365. G.user_headers |= bit;
  1366. break;
  1367. }
  1368. bit <<= 1;
  1369. words += strlen(words) + 1;
  1370. }
  1371. hdr += size;
  1372. }
  1373. }
  1374. #endif
  1375. G.output_fd = -1;
  1376. G.o_flags = O_WRONLY | O_CREAT | O_TRUNC | O_EXCL;
  1377. if (G.fname_out) { /* -O FILE ? */
  1378. if (LONE_DASH(G.fname_out)) { /* -O - ? */
  1379. G.output_fd = 1;
  1380. option_mask32 &= ~WGET_OPT_CONTINUE;
  1381. }
  1382. /* compat with wget: -O FILE can overwrite */
  1383. G.o_flags = O_WRONLY | O_CREAT | O_TRUNC;
  1384. }
  1385. while (*argv)
  1386. download_one_url(*argv++);
  1387. if (G.output_fd >= 0)
  1388. xclose(G.output_fd);
  1389. #if ENABLE_FEATURE_CLEAN_UP && ENABLE_FEATURE_WGET_LONG_OPTIONS
  1390. free(G.extra_headers);
  1391. #endif
  1392. FINI_G();
  1393. return EXIT_SUCCESS;
  1394. }