wget.c 46 KB

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