3
0

wget.c 42 KB

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