3
0

wget.c 48 KB

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