3
0

wget.c 46 KB

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