wget.c 45 KB

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