wget.c 44 KB

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