wget.c 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656
  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 (41 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 (!ENABLE_FEATURE_WGET_FTP
  1074. || use_proxy || target.protocol[0] != 'f' /*not ftp[s]*/
  1075. ) {
  1076. /*
  1077. * HTTP session
  1078. */
  1079. char *str;
  1080. int status;
  1081. /* Open socket to http(s) server */
  1082. #if ENABLE_FEATURE_WGET_OPENSSL
  1083. /* openssl (and maybe internal TLS) support is configured */
  1084. if (server.protocol == P_HTTPS) {
  1085. /* openssl-based helper
  1086. * Inconvenient API since we can't give it an open fd
  1087. */
  1088. int fd = spawn_https_helper_openssl(server.host, server.port);
  1089. # if ENABLE_FEATURE_WGET_HTTPS
  1090. if (fd < 0) { /* no openssl? try internal */
  1091. sfp = open_socket(lsa);
  1092. spawn_ssl_client(server.host, fileno(sfp), /*flags*/ 0);
  1093. goto socket_opened;
  1094. }
  1095. # else
  1096. /* We don't check for exec("openssl") failure in this case */
  1097. # endif
  1098. sfp = fdopen(fd, "r+");
  1099. if (!sfp)
  1100. bb_die_memory_exhausted();
  1101. goto socket_opened;
  1102. }
  1103. sfp = open_socket(lsa);
  1104. socket_opened:
  1105. #elif ENABLE_FEATURE_WGET_HTTPS
  1106. /* Only internal TLS support is configured */
  1107. sfp = open_socket(lsa);
  1108. if (server.protocol == P_HTTPS)
  1109. spawn_ssl_client(server.host, fileno(sfp), /*flags*/ 0);
  1110. #else
  1111. /* ssl (https) support is not configured */
  1112. sfp = open_socket(lsa);
  1113. #endif
  1114. /* Send HTTP request */
  1115. if (use_proxy) {
  1116. SENDFMT(sfp, "GET %s://%s/%s HTTP/1.1\r\n",
  1117. target.protocol, target.host,
  1118. target.path);
  1119. } else {
  1120. SENDFMT(sfp, "%s /%s HTTP/1.1\r\n",
  1121. (option_mask32 & WGET_OPT_POST) ? "POST" : "GET",
  1122. target.path);
  1123. }
  1124. if (!USR_HEADER_HOST)
  1125. SENDFMT(sfp, "Host: %s\r\n", target.host);
  1126. if (!USR_HEADER_USER_AGENT)
  1127. SENDFMT(sfp, "User-Agent: %s\r\n", G.user_agent);
  1128. /* Ask server to close the connection as soon as we are done
  1129. * (IOW: we do not intend to send more requests)
  1130. */
  1131. SENDFMT(sfp, "Connection: close\r\n");
  1132. #if ENABLE_FEATURE_WGET_AUTHENTICATION
  1133. if (target.user && !USR_HEADER_AUTH) {
  1134. SENDFMT(sfp, "Proxy-Authorization: Basic %s\r\n"+6,
  1135. base64enc(target.user));
  1136. }
  1137. if (use_proxy && server.user && !USR_HEADER_PROXY_AUTH) {
  1138. SENDFMT(sfp, "Proxy-Authorization: Basic %s\r\n",
  1139. base64enc(server.user));
  1140. }
  1141. #endif
  1142. if (G.beg_range != 0 && !USR_HEADER_RANGE)
  1143. SENDFMT(sfp, "Range: bytes=%"OFF_FMT"u-\r\n", G.beg_range);
  1144. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  1145. if (G.extra_headers) {
  1146. log_io(G.extra_headers);
  1147. fputs(G.extra_headers, sfp);
  1148. }
  1149. if (option_mask32 & WGET_OPT_POST_FILE) {
  1150. int fd = xopen_stdin(G.post_file);
  1151. G.post_data = xmalloc_read(fd, NULL);
  1152. close(fd);
  1153. }
  1154. if (G.post_data) {
  1155. /* If user did not override it... */
  1156. if (!USR_HEADER_CONTENT_TYPE) {
  1157. SENDFMT(sfp,
  1158. "Content-Type: application/x-www-form-urlencoded\r\n"
  1159. );
  1160. }
  1161. SENDFMT(sfp,
  1162. "Content-Length: %u\r\n"
  1163. "\r\n"
  1164. "%s",
  1165. (int) strlen(G.post_data), G.post_data
  1166. );
  1167. } else
  1168. #endif
  1169. {
  1170. SENDFMT(sfp, "\r\n");
  1171. }
  1172. fflush(sfp);
  1173. /* Tried doing this unconditionally.
  1174. * Cloudflare and nginx/1.11.5 are shocked to see SHUT_WR on non-HTTPS.
  1175. */
  1176. #if SSL_SUPPORTED
  1177. if (target.protocol == P_HTTPS) {
  1178. /* If we use SSL helper, keeping our end of the socket open for writing
  1179. * makes our end (i.e. the same fd!) readable (EAGAIN instead of EOF)
  1180. * even after child closes its copy of the fd.
  1181. * This helps:
  1182. */
  1183. shutdown(fileno(sfp), SHUT_WR);
  1184. }
  1185. #endif
  1186. /*
  1187. * Retrieve HTTP response line and check for "200" status code.
  1188. */
  1189. read_response:
  1190. fgets_trim_sanitize(sfp, " %s\n");
  1191. str = G.wget_buf;
  1192. str = skip_non_whitespace(str);
  1193. str = skip_whitespace(str);
  1194. // FIXME: no error check
  1195. // xatou wouldn't work: "200 OK"
  1196. status = atoi(str);
  1197. switch (status) {
  1198. case 0:
  1199. case 100:
  1200. while (get_sanitized_hdr(sfp) != NULL)
  1201. /* eat all remaining headers */;
  1202. goto read_response;
  1203. /* Success responses */
  1204. case 200:
  1205. /* fall through */
  1206. case 201: /* 201 Created */
  1207. /* "The request has been fulfilled and resulted in a new resource being created" */
  1208. /* Standard wget is reported to treat this as success */
  1209. /* fall through */
  1210. case 202: /* 202 Accepted */
  1211. /* "The request has been accepted for processing, but the processing has not been completed" */
  1212. /* Treat as success: fall through */
  1213. case 203: /* 203 Non-Authoritative Information */
  1214. /* "Use of this response code is not required and is only appropriate when the response would otherwise be 200 (OK)" */
  1215. /* fall through */
  1216. case 204: /* 204 No Content */
  1217. /*
  1218. Response 204 doesn't say "null file", it says "metadata
  1219. has changed but data didn't":
  1220. "10.2.5 204 No Content
  1221. The server has fulfilled the request but does not need to return
  1222. an entity-body, and might want to return updated metainformation.
  1223. The response MAY include new or updated metainformation in the form
  1224. of entity-headers, which if present SHOULD be associated with
  1225. the requested variant.
  1226. If the client is a user agent, it SHOULD NOT change its document
  1227. view from that which caused the request to be sent. This response
  1228. is primarily intended to allow input for actions to take place
  1229. without causing a change to the user agent's active document view,
  1230. although any new or updated metainformation SHOULD be applied
  1231. to the document currently in the user agent's active view.
  1232. The 204 response MUST NOT include a message-body, and thus
  1233. is always terminated by the first empty line after the header fields."
  1234. However, in real world it was observed that some web servers
  1235. (e.g. Boa/0.94.14rc21) simply use code 204 when file size is zero.
  1236. */
  1237. if (G.beg_range != 0) {
  1238. /* "Range:..." was not honored by the server.
  1239. * Restart download from the beginning.
  1240. */
  1241. reset_beg_range_to_zero();
  1242. }
  1243. break;
  1244. /* 205 Reset Content ?? what to do on this ?? */
  1245. case 300: /* redirection */
  1246. case 301:
  1247. case 302:
  1248. case 303:
  1249. case 307:
  1250. case 308:
  1251. break;
  1252. case 206: /* Partial Content */
  1253. if (G.beg_range != 0)
  1254. /* "Range:..." worked. Good. */
  1255. break;
  1256. /* Partial Content even though we did not ask for it??? */
  1257. /* fall through */
  1258. default:
  1259. bb_error_msg_and_die("server returned error: %s", G.wget_buf);
  1260. }
  1261. /*
  1262. * Retrieve HTTP headers.
  1263. */
  1264. while ((str = get_sanitized_hdr(sfp)) != NULL) {
  1265. static const char keywords[] ALIGN1 =
  1266. "content-length\0""transfer-encoding\0""location\0";
  1267. enum {
  1268. KEY_content_length = 1, KEY_transfer_encoding, KEY_location
  1269. };
  1270. smalluint key;
  1271. /* get_sanitized_hdr converted "FOO:" string to lowercase */
  1272. /* strip trailing whitespace */
  1273. char *s = strchrnul(str, '\0') - 1;
  1274. while (s >= str && (*s == ' ' || *s == '\t')) {
  1275. *s = '\0';
  1276. s--;
  1277. }
  1278. key = index_in_strings(keywords, G.wget_buf) + 1;
  1279. if (key == KEY_content_length) {
  1280. G.content_len = BB_STRTOOFF(str, NULL, 10);
  1281. if (G.content_len < 0 || errno) {
  1282. bb_error_msg_and_die("content-length %s is garbage", str);
  1283. }
  1284. G.got_clen = 1;
  1285. continue;
  1286. }
  1287. if (key == KEY_transfer_encoding) {
  1288. if (strcmp(str_tolower(str), "chunked") != 0)
  1289. bb_error_msg_and_die("transfer encoding '%s' is not supported", str);
  1290. G.chunked = 1;
  1291. }
  1292. if (key == KEY_location && status >= 300) {
  1293. if (--redir_limit == 0)
  1294. bb_simple_error_msg_and_die("too many redirections");
  1295. fclose(sfp);
  1296. if (str[0] == '/') {
  1297. free(redirected_path);
  1298. target.path = redirected_path = xstrdup(str + 1);
  1299. /* lsa stays the same: it's on the same server */
  1300. } else {
  1301. parse_url(str, &target);
  1302. if (!use_proxy) {
  1303. /* server.user remains untouched */
  1304. free(server.allocated);
  1305. server.allocated = NULL;
  1306. server.protocol = target.protocol;
  1307. server.host = target.host;
  1308. /* strip_ipv6_scope_id(target.host); - no! */
  1309. /* we assume remote never gives us IPv6 addr with scope id */
  1310. server.port = target.port;
  1311. free(lsa);
  1312. goto resolve_lsa;
  1313. } /* else: lsa stays the same: we use proxy */
  1314. }
  1315. goto establish_session;
  1316. }
  1317. }
  1318. // if (status >= 300)
  1319. // bb_error_msg_and_die("bad redirection (no Location: header from server)");
  1320. /* For HTTP, data is pumped over the same connection */
  1321. dfp = sfp;
  1322. }
  1323. #if ENABLE_FEATURE_WGET_FTP
  1324. else {
  1325. /*
  1326. * FTP session
  1327. */
  1328. sfp = prepare_ftp_session(&dfp, &target, lsa);
  1329. }
  1330. #endif
  1331. free(lsa);
  1332. if (!(option_mask32 & WGET_OPT_SPIDER)) {
  1333. if (G.output_fd < 0)
  1334. G.output_fd = xopen(G.fname_out, G.o_flags);
  1335. retrieve_file_data(dfp);
  1336. if (!(option_mask32 & WGET_OPT_OUTNAME)) {
  1337. xclose(G.output_fd);
  1338. G.output_fd = -1;
  1339. }
  1340. } else {
  1341. if (!(option_mask32 & WGET_OPT_QUIET))
  1342. fprintf(stderr, "remote file exists\n");
  1343. }
  1344. #if ENABLE_FEATURE_WGET_FTP
  1345. if (dfp != sfp) {
  1346. /* It's ftp. Close data connection properly */
  1347. fclose(dfp);
  1348. if (ftpcmd(NULL, NULL, sfp) != 226)
  1349. bb_error_msg_and_die("ftp error: %s", G.wget_buf);
  1350. /* ftpcmd("QUIT", NULL, sfp); - why bother? */
  1351. }
  1352. #endif
  1353. fclose(sfp);
  1354. free(server.allocated);
  1355. free(target.allocated);
  1356. free(server.user);
  1357. free(target.user);
  1358. free(fname_out_alloc);
  1359. free(redirected_path);
  1360. }
  1361. int wget_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1362. int wget_main(int argc UNUSED_PARAM, char **argv)
  1363. {
  1364. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  1365. static const char wget_longopts[] ALIGN1 =
  1366. /* name, has_arg, val */
  1367. "continue\0" No_argument "c"
  1368. "quiet\0" No_argument "q"
  1369. "server-response\0" No_argument "S"
  1370. "output-document\0" Required_argument "O"
  1371. "output-file\0" Required_argument "o"
  1372. "directory-prefix\0" Required_argument "P"
  1373. "proxy\0" Required_argument "Y"
  1374. "user-agent\0" Required_argument "U"
  1375. IF_FEATURE_WGET_TIMEOUT(
  1376. "timeout\0" Required_argument "T")
  1377. /* Ignored: */
  1378. IF_DESKTOP( "tries\0" Required_argument "t")
  1379. "header\0" Required_argument "\xff"
  1380. "post-data\0" Required_argument "\xfe"
  1381. "spider\0" No_argument "\xfd"
  1382. "no-check-certificate\0" No_argument "\xfc"
  1383. "post-file\0" Required_argument "\xfb"
  1384. /* Ignored (we always use PASV): */
  1385. IF_DESKTOP( "passive-ftp\0" No_argument "\xf0")
  1386. /* Ignored (we don't support caching) */
  1387. IF_DESKTOP( "no-cache\0" No_argument "\xf0")
  1388. IF_DESKTOP( "no-verbose\0" No_argument "\xf0")
  1389. IF_DESKTOP( "no-clobber\0" No_argument "\xf0")
  1390. IF_DESKTOP( "no-host-directories\0" No_argument "\xf0")
  1391. IF_DESKTOP( "no-parent\0" No_argument "\xf0")
  1392. ;
  1393. # define GETOPT32 getopt32long
  1394. # define LONGOPTS ,wget_longopts
  1395. #else
  1396. # define GETOPT32 getopt32
  1397. # define LONGOPTS
  1398. #endif
  1399. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  1400. llist_t *headers_llist = NULL;
  1401. #endif
  1402. INIT_G();
  1403. #if ENABLE_FEATURE_WGET_TIMEOUT
  1404. G.timeout_seconds = 900;
  1405. signal(SIGALRM, alarm_handler);
  1406. #endif
  1407. G.proxy_flag = "on"; /* use proxies if env vars are set */
  1408. G.user_agent = "Wget"; /* "User-Agent" header field */
  1409. GETOPT32(argv, "^"
  1410. "cqSO:o:P:Y:U:T:+"
  1411. /*ignored:*/ "t:"
  1412. /*ignored:*/ "n::"
  1413. /* wget has exactly four -n<letter> opts, all of which we can ignore:
  1414. * -nv --no-verbose: be moderately quiet (-q is full quiet)
  1415. * -nc --no-clobber: abort if exists, neither download to FILE.n nor overwrite FILE
  1416. * -nH --no-host-directories: wget -r http://host/ won't create host/
  1417. * -np --no-parent
  1418. * "n::" above says that we accept -n[ARG].
  1419. * Specifying "n:" would be a bug: "-n ARG" would eat ARG!
  1420. */
  1421. "\0"
  1422. "-1" /* at least one URL */
  1423. IF_FEATURE_WGET_LONG_OPTIONS(":\xfe--\xfb")
  1424. IF_FEATURE_WGET_LONG_OPTIONS(":\xfe--\xfe")
  1425. IF_FEATURE_WGET_LONG_OPTIONS(":\xfb--\xfb")
  1426. IF_FEATURE_WGET_LONG_OPTIONS(":\xff::") /* --header is a list */
  1427. LONGOPTS
  1428. , &G.fname_out, &G.fname_log, &G.dir_prefix,
  1429. &G.proxy_flag, &G.user_agent,
  1430. IF_FEATURE_WGET_TIMEOUT(&G.timeout_seconds) IF_NOT_FEATURE_WGET_TIMEOUT(NULL),
  1431. NULL, /* -t RETRIES */
  1432. NULL /* -n[ARG] */
  1433. IF_FEATURE_WGET_LONG_OPTIONS(, &headers_llist)
  1434. IF_FEATURE_WGET_LONG_OPTIONS(, &G.post_data)
  1435. IF_FEATURE_WGET_LONG_OPTIONS(, &G.post_file)
  1436. );
  1437. #if 0 /* option bits debug */
  1438. if (option_mask32 & WGET_OPT_RETRIES) bb_error_msg("-t NUM");
  1439. if (option_mask32 & WGET_OPT_nsomething) bb_error_msg("-nsomething");
  1440. if (option_mask32 & WGET_OPT_HEADER) bb_error_msg("--header");
  1441. if (option_mask32 & WGET_OPT_POST_DATA) bb_error_msg("--post-data");
  1442. if (option_mask32 & WGET_OPT_SPIDER) bb_error_msg("--spider");
  1443. if (option_mask32 & WGET_OPT_NO_CHECK_CERT) bb_error_msg("--no-check-certificate");
  1444. if (option_mask32 & WGET_OPT_POST_FILE) bb_error_msg("--post-file");
  1445. exit(0);
  1446. #endif
  1447. argv += optind;
  1448. #if ENABLE_FEATURE_WGET_LONG_OPTIONS
  1449. if (headers_llist) {
  1450. int size = 0;
  1451. char *hdr;
  1452. llist_t *ll = headers_llist;
  1453. while (ll) {
  1454. size += strlen(ll->data) + 2;
  1455. ll = ll->link;
  1456. }
  1457. G.extra_headers = hdr = xmalloc(size + 1);
  1458. while (headers_llist) {
  1459. int bit;
  1460. const char *words;
  1461. size = sprintf(hdr, "%s\r\n",
  1462. (char*)llist_pop(&headers_llist));
  1463. /* a bit like index_in_substrings but don't match full key */
  1464. bit = 1;
  1465. words = wget_user_headers;
  1466. while (*words) {
  1467. if (strcasestr(hdr, words) == hdr) {
  1468. G.user_headers |= bit;
  1469. break;
  1470. }
  1471. bit <<= 1;
  1472. words += strlen(words) + 1;
  1473. }
  1474. hdr += size;
  1475. }
  1476. }
  1477. #endif
  1478. G.output_fd = -1;
  1479. G.o_flags = O_WRONLY | O_CREAT | O_TRUNC | O_EXCL;
  1480. if (G.fname_out) { /* -O FILE ? */
  1481. if (LONE_DASH(G.fname_out)) { /* -O - ? */
  1482. G.output_fd = 1;
  1483. option_mask32 = (option_mask32 & (~WGET_OPT_CONTINUE)) | WGET_NO_FTRUNCATE;
  1484. }
  1485. /* compat with wget: -O FILE can overwrite */
  1486. G.o_flags = O_WRONLY | O_CREAT | O_TRUNC;
  1487. }
  1488. G.log_fd = -1;
  1489. if (G.fname_log) { /* -o FILE ? */
  1490. if (!LONE_DASH(G.fname_log)) { /* not -o - ? */
  1491. /* compat with wget: -o FILE can overwrite */
  1492. G.log_fd = xopen(G.fname_log, O_WRONLY | O_CREAT | O_TRUNC);
  1493. /* Redirect only stderr to log file, so -O - will work */
  1494. xdup2(G.log_fd, STDERR_FILENO);
  1495. }
  1496. }
  1497. while (*argv)
  1498. download_one_url(*argv++);
  1499. if (G.output_fd >= 0)
  1500. xclose(G.output_fd);
  1501. if (G.log_fd >= 0)
  1502. xclose(G.log_fd);
  1503. #if ENABLE_FEATURE_CLEAN_UP && ENABLE_FEATURE_WGET_LONG_OPTIONS
  1504. free(G.extra_headers);
  1505. #endif
  1506. FINI_G();
  1507. return EXIT_SUCCESS;
  1508. }