PageRenderTime 41ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/commands/fetch/fetch.c

http://www.minix3.org/
C | 1145 lines | 908 code | 98 blank | 139 comment | 359 complexity | ef4537e95a72f0e2d071e49c0afefc83 MD5 | raw file
Possible License(s): MIT, WTFPL, AGPL-1.0, BSD-3-Clause, GPL-3.0, LGPL-2.0, JSON, 0BSD
  1. /*-
  2. * Copyright (c) 2000-2004 Dag-Erling Co?dan Sm?rgrav
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer
  10. * in this position and unchanged.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. The name of the author may not be used to endorse or promote products
  15. * derived from this software without specific prior written permission
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  18. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  19. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  20. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  21. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  22. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  23. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  24. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  26. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. */
  28. #if HAVE_CONFIG_H
  29. #include "config.h"
  30. #endif
  31. #if !defined(NETBSD) && !defined(__minix)
  32. #include <nbcompat.h>
  33. #endif
  34. #if HAVE_SYS_PARAM_H
  35. #include <sys/param.h>
  36. #endif
  37. #if HAVE_SYS_IOCTL_H
  38. #include <sys/ioctl.h>
  39. #endif
  40. #if HAVE_SYS_SOCKET_H
  41. #include <sys/socket.h>
  42. #endif
  43. #if HAVE_SYS_STAT_H
  44. #include <sys/stat.h>
  45. #endif
  46. #if HAVE_SYS_TIME_H
  47. #include <sys/time.h>
  48. #endif
  49. #if HAVE_UTIME_H
  50. #include <utime.h>
  51. #endif
  52. #include <ctype.h>
  53. #if HAVE_ERR_H
  54. #include <err.h>
  55. #endif
  56. #include <errno.h>
  57. #include <signal.h>
  58. #if HAVE_STDINT_H
  59. #include <stdint.h>
  60. #endif
  61. #include <stdio.h>
  62. #include <stdlib.h>
  63. #include <string.h>
  64. #if HAVE_TERMIOS_H
  65. #include <termios.h>
  66. #endif
  67. #include <unistd.h>
  68. #include <fetch.h>
  69. #if HAVE_SYSEXITS_H
  70. #include <sysexits.h>
  71. #endif
  72. #ifndef EX_USAGE
  73. #define EX_USAGE 64
  74. #endif
  75. #ifndef EX_IOERR
  76. #define EX_IOERR 74
  77. #endif
  78. #define MINBUFSIZE 4096
  79. /* Option flags */
  80. int A_flag; /* -A: do not follow 302 redirects */
  81. int a_flag; /* -a: auto retry */
  82. off_t B_size; /* -B: buffer size */
  83. int d_flag; /* -d: direct connection */
  84. int F_flag; /* -F: restart without checking mtime */
  85. int i_flag; /* -i: fetch file if modified */
  86. int l_flag; /* -l: link rather than copy file: URLs */
  87. int m_flag; /* -[Mm]: mirror mode */
  88. char *N_filename; /* -N: netrc file name */
  89. int n_flag; /* -n: do not preserve modification time */
  90. int o_flag; /* -o: specify output file */
  91. int o_directory; /* output file is a directory */
  92. char *o_filename; /* name of output file */
  93. int o_stdout; /* output file is stdout */
  94. int once_flag; /* -1: stop at first successful file */
  95. int R_flag; /* -R: don't delete partially transferred files */
  96. int r_flag; /* -r: restart previously interrupted transfer */
  97. off_t S_size; /* -S: require size to match */
  98. int s_flag; /* -s: show size, don't fetch */
  99. long T_secs = 120; /* -T: transfer timeout in seconds */
  100. int U_flag; /* -U: do not use high ports */
  101. int v_level = 1; /* -v: verbosity level */
  102. int v_tty; /* stdout is a tty */
  103. pid_t pgrp; /* our process group */
  104. long w_secs; /* -w: retry delay */
  105. int family = PF_UNSPEC; /* -[46]: address family to use */
  106. volatile int sigalrm; /* SIGALRM received */
  107. #ifdef SIGINFO
  108. volatile int siginfo; /* SIGINFO received */
  109. #endif
  110. volatile int sigint; /* SIGINT received */
  111. long ftp_timeout; /* default timeout for FTP transfers */
  112. long http_timeout; /* default timeout for HTTP transfers */
  113. char *buf; /* transfer buffer */
  114. /*
  115. * Signal handler
  116. */
  117. static void
  118. sig_handler(int sig)
  119. {
  120. switch (sig) {
  121. case SIGALRM:
  122. fetchRestartCalls = 0;
  123. sigalrm = 1;
  124. break;
  125. #ifdef SIGINFO
  126. case SIGINFO:
  127. siginfo = 1;
  128. break;
  129. #endif
  130. case SIGINT:
  131. fetchRestartCalls = 0;
  132. sigint = 1;
  133. break;
  134. }
  135. }
  136. struct xferstat {
  137. char name[64];
  138. struct timeval start;
  139. struct timeval last;
  140. off_t size;
  141. off_t offset;
  142. off_t rcvd;
  143. };
  144. /*
  145. * Compute and display ETA
  146. */
  147. static const char *
  148. stat_eta(struct xferstat *xs)
  149. {
  150. static char str[16];
  151. long elapsed, eta;
  152. off_t received, expected;
  153. elapsed = xs->last.tv_sec - xs->start.tv_sec;
  154. received = xs->rcvd - xs->offset;
  155. expected = xs->size - xs->rcvd;
  156. eta = (long)((double)elapsed * expected / received);
  157. if (eta > 3600)
  158. snprintf(str, sizeof str, "%02ldh%02ldm",
  159. eta / 3600, (eta % 3600) / 60);
  160. else
  161. snprintf(str, sizeof str, "%02ldm%02lds",
  162. eta / 60, eta % 60);
  163. return (str);
  164. }
  165. /*
  166. * Format a number as "xxxx YB" where Y is ' ', 'k', 'M'...
  167. */
  168. static const char *prefixes = " kMGTP";
  169. static const char *
  170. stat_bytes(off_t bytes)
  171. {
  172. static char str[16];
  173. const char *prefix = prefixes;
  174. while (bytes > 9999 && prefix[1] != '\0') {
  175. bytes /= 1024;
  176. prefix++;
  177. }
  178. snprintf(str, sizeof str, "%4jd %cB", (intmax_t)bytes, *prefix);
  179. return (str);
  180. }
  181. /*
  182. * Compute and display transfer rate
  183. */
  184. static const char *
  185. stat_bps(struct xferstat *xs)
  186. {
  187. static char str[16];
  188. double delta, bps;
  189. delta = (xs->last.tv_sec + (xs->last.tv_usec / 1.e6))
  190. - (xs->start.tv_sec + (xs->start.tv_usec / 1.e6));
  191. if (delta == 0.0) {
  192. snprintf(str, sizeof str, "?? Bps");
  193. } else {
  194. bps = (xs->rcvd - xs->offset) / delta;
  195. snprintf(str, sizeof str, "%sps", stat_bytes((off_t)bps));
  196. }
  197. return (str);
  198. }
  199. /*
  200. * Update the stats display
  201. */
  202. static void
  203. stat_display(struct xferstat *xs, int force)
  204. {
  205. struct timeval now;
  206. #if !defined(__minix)
  207. int ctty_pgrp;
  208. #endif /* !defined(__minix) */
  209. /* Minix returns "Not a typewriter error" */
  210. #if defined(TIOCGPGRP) && !defined(__minix)
  211. /* check if we're the foreground process */
  212. if (ioctl(STDERR_FILENO, TIOCGPGRP, &ctty_pgrp) == -1 ||
  213. (pid_t)ctty_pgrp != pgrp)
  214. return;
  215. #endif
  216. gettimeofday(&now, NULL);
  217. if (!force && now.tv_sec <= xs->last.tv_sec)
  218. return;
  219. xs->last = now;
  220. fprintf(stderr, "\r%-46.46s", xs->name);
  221. if (xs->size <= 0) {
  222. #if HAVE_SETPROCTITLE
  223. setproctitle("%s [%s]", xs->name, stat_bytes(xs->rcvd));
  224. #endif
  225. fprintf(stderr, " %s", stat_bytes(xs->rcvd));
  226. } else {
  227. #if HAVE_SETPROCTITLE
  228. setproctitle("%s [%d%% of %s]", xs->name,
  229. (int)((100.0 * xs->rcvd) / xs->size),
  230. stat_bytes(xs->size));
  231. #endif
  232. fprintf(stderr, "%3d%% of %s",
  233. (int)((100.0 * xs->rcvd) / xs->size),
  234. stat_bytes(xs->size));
  235. }
  236. fprintf(stderr, " %s", stat_bps(xs));
  237. if (xs->size > 0 && xs->rcvd > 0 &&
  238. xs->last.tv_sec >= xs->start.tv_sec + 10)
  239. fprintf(stderr, " %s", stat_eta(xs));
  240. fflush(stderr);
  241. }
  242. /*
  243. * Initialize the transfer statistics
  244. */
  245. static void
  246. stat_start(struct xferstat *xs, const char *name, off_t size, off_t offset)
  247. {
  248. snprintf(xs->name, sizeof xs->name, "%s", name);
  249. gettimeofday(&xs->start, NULL);
  250. xs->last.tv_sec = xs->last.tv_usec = 0;
  251. xs->size = size;
  252. xs->offset = offset;
  253. xs->rcvd = offset;
  254. if (v_tty && v_level > 0)
  255. stat_display(xs, 1);
  256. else if (v_level > 0)
  257. fprintf(stderr, "%-46s", xs->name);
  258. }
  259. /*
  260. * Update the transfer statistics
  261. */
  262. static void
  263. stat_update(struct xferstat *xs, off_t rcvd)
  264. {
  265. xs->rcvd = rcvd;
  266. if (v_tty && v_level > 0)
  267. stat_display(xs, 0);
  268. }
  269. /*
  270. * Finalize the transfer statistics
  271. */
  272. static void
  273. stat_end(struct xferstat *xs)
  274. {
  275. gettimeofday(&xs->last, NULL);
  276. if (v_tty && v_level > 0) {
  277. stat_display(xs, 1);
  278. putc('\n', stderr);
  279. } else if (v_level > 0) {
  280. fprintf(stderr, " %s %s\n",
  281. stat_bytes(xs->size), stat_bps(xs));
  282. }
  283. }
  284. #if HAVE_TERMIOS_H && !defined(PREFER_GETPASS)
  285. static int
  286. read_password(const char *prompt, char *pwbuf, size_t pwbuf_len)
  287. {
  288. struct termios tios;
  289. tcflag_t saved_flags;
  290. int nopwd;
  291. fprintf(stderr, prompt);
  292. if (tcgetattr(STDIN_FILENO, &tios) != 0)
  293. return (fgets(pwbuf, pwbuf_len, stdin) == NULL);
  294. saved_flags = tios.c_lflag;
  295. tios.c_lflag &= ~ECHO;
  296. tios.c_lflag |= ECHONL|ICANON;
  297. #ifndef __minix
  298. tcsetattr(STDIN_FILENO, TCSAFLUSH|TCSASOFT, &tios);
  299. #else
  300. tcsetattr(STDIN_FILENO, TCSAFLUSH, &tios);
  301. #endif
  302. nopwd = (fgets(pwbuf, pwbuf_len, stdin) == NULL);
  303. tios.c_lflag = saved_flags;
  304. #ifndef __minix
  305. tcsetattr(STDIN_FILENO, TCSANOW|TCSASOFT, &tios);
  306. #else
  307. tcsetattr(STDIN_FILENO, TCSANOW, &tios);
  308. #endif
  309. return nopwd;
  310. }
  311. #elif HAVE_GETPASSPHRASE || HAVE_GETPASS
  312. static int
  313. read_password(const char *prompt, char *pwbuf, size_t pwbuf_len)
  314. {
  315. char *pass;
  316. #if HAVE_GETPASSPHRASE && !defined(PREFER_GETPASS)
  317. pass = getpassphrase(prompt);
  318. #else
  319. pass = getpass(prompt);
  320. #endif
  321. if (pass == NULL || strlen(pass) >= pwbuf_len)
  322. return 1;
  323. strcpy(pwbuf, pass);
  324. return 0;
  325. }
  326. #else
  327. static int
  328. read_password(const char *prompt, char *pwbuf, size_t pwbuf_len)
  329. {
  330. fprintf(stderr, prompt);
  331. return (fgets(pwbuf, pwbuf_len, stdin) == NULL);
  332. }
  333. #endif
  334. /*
  335. * Ask the user for authentication details
  336. */
  337. static int
  338. query_auth(struct url *URL)
  339. {
  340. int i, nopwd;
  341. fprintf(stderr, "Authentication required for <%s://%s:%d/>!\n",
  342. URL->scheme, URL->host, URL->port);
  343. fprintf(stderr, "Login: ");
  344. if (fgets(URL->user, sizeof URL->user, stdin) == NULL)
  345. return (-1);
  346. for (i = strlen(URL->user); i >= 0; --i)
  347. if (URL->user[i] == '\r' || URL->user[i] == '\n')
  348. URL->user[i] = '\0';
  349. nopwd = read_password("Password: ", URL->pwd, sizeof(URL->pwd));
  350. if (nopwd)
  351. return (-1);
  352. for (i = strlen(URL->pwd); i >= 0; --i)
  353. if (URL->pwd[i] == '\r' || URL->pwd[i] == '\n')
  354. URL->pwd[i] = '\0';
  355. return (0);
  356. }
  357. /*
  358. * Fetch a file
  359. */
  360. static int
  361. fetch(char *URL, const char *path)
  362. {
  363. struct url *url;
  364. struct url_stat us;
  365. struct stat sb, nsb;
  366. struct xferstat xs;
  367. FILE *of;
  368. fetchIO *f;
  369. size_t size, wr;
  370. ssize_t ssize;
  371. off_t count;
  372. char flags[8];
  373. char *tmppath;
  374. int r;
  375. unsigned timeout;
  376. char *ptr;
  377. f = NULL;
  378. of = NULL;
  379. tmppath = NULL;
  380. timeout = 0;
  381. *flags = 0;
  382. count = 0;
  383. /* set verbosity level */
  384. if (v_level > 1)
  385. strcat(flags, "v");
  386. if (v_level > 2)
  387. fetchDebug = 1;
  388. /* parse URL */
  389. if ((url = fetchParseURL(URL)) == NULL) {
  390. warnx("%s: parse error", URL);
  391. goto failure;
  392. }
  393. /* if no scheme was specified, take a guess */
  394. if (!*url->scheme) {
  395. if (!*url->host)
  396. strcpy(url->scheme, SCHEME_FILE);
  397. else if (strncasecmp(url->host, "ftp.", 4) == 0)
  398. strcpy(url->scheme, SCHEME_FTP);
  399. else if (strncasecmp(url->host, "www.", 4) == 0)
  400. strcpy(url->scheme, SCHEME_HTTP);
  401. }
  402. /* common flags */
  403. switch (family) {
  404. case PF_INET:
  405. strcat(flags, "4");
  406. break;
  407. #ifndef __minix
  408. case PF_INET6:
  409. strcat(flags, "6");
  410. break;
  411. #endif
  412. }
  413. /* Protocol independent flags */
  414. if (i_flag) {
  415. if (stat(path, &sb) == 0) {
  416. url->last_modified = sb.st_mtime;
  417. strcat(flags, "i");
  418. } else if (errno != ENOENT) {
  419. warn("%s: stat()", path);
  420. goto failure;
  421. }
  422. }
  423. /* FTP specific flags */
  424. if (strcmp(url->scheme, SCHEME_FTP) == 0) {
  425. if (d_flag)
  426. strcat(flags, "d");
  427. if (U_flag)
  428. strcat(flags, "l");
  429. timeout = T_secs ? T_secs : ftp_timeout;
  430. }
  431. /* HTTP specific flags */
  432. if (strcmp(url->scheme, SCHEME_HTTP) == 0) {
  433. if (d_flag)
  434. strcat(flags, "d");
  435. if (A_flag)
  436. strcat(flags, "A");
  437. timeout = T_secs ? T_secs : http_timeout;
  438. }
  439. /* set the protocol timeout. */
  440. fetchTimeout = timeout;
  441. /* just print size */
  442. if (s_flag) {
  443. if (timeout)
  444. alarm(timeout);
  445. r = fetchStat(url, &us, flags);
  446. if (timeout)
  447. alarm(0);
  448. if (sigalrm || sigint)
  449. goto signal;
  450. if (r == -1) {
  451. warnx("%s", fetchLastErrString);
  452. goto failure;
  453. }
  454. if (us.size == -1)
  455. printf("Unknown\n");
  456. else
  457. printf("%jd\n", (intmax_t)us.size);
  458. goto success;
  459. }
  460. /*
  461. * If the -r flag was specified, we have to compare the local
  462. * and remote files, so we should really do a fetchStat()
  463. * first, but I know of at least one HTTP server that only
  464. * sends the content size in response to GET requests, and
  465. * leaves it out of replies to HEAD requests. Also, in the
  466. * (frequent) case that the local and remote files match but
  467. * the local file is truncated, we have sufficient information
  468. * before the compare to issue a correct request. Therefore,
  469. * we always issue a GET request as if we were sure the local
  470. * file was a truncated copy of the remote file; we can drop
  471. * the connection later if we change our minds.
  472. */
  473. sb.st_size = -1;
  474. if (!o_stdout) {
  475. r = stat(path, &sb);
  476. if (r == 0 && r_flag && S_ISREG(sb.st_mode)) {
  477. url->offset = sb.st_size;
  478. } else if (r == -1 || !S_ISREG(sb.st_mode)) {
  479. /*
  480. * Whatever value sb.st_size has now is either
  481. * wrong (if stat(2) failed) or irrelevant (if the
  482. * path does not refer to a regular file)
  483. */
  484. sb.st_size = -1;
  485. }
  486. if (r == -1 && errno != ENOENT) {
  487. warnx("%s: stat()", path);
  488. goto failure;
  489. }
  490. }
  491. /* start the transfer */
  492. if (timeout)
  493. alarm(timeout);
  494. f = fetchXGet(url, &us, flags);
  495. if (timeout)
  496. alarm(0);
  497. if (sigalrm || sigint)
  498. goto signal;
  499. if (f == NULL && i_flag && fetchLastErrCode == FETCH_UNCHANGED) {
  500. /* URL was not modified, return OK. */
  501. printf("%s: not modified\n", URL);
  502. r = 0;
  503. goto done;
  504. }
  505. if (f == NULL) {
  506. warnx("%s: %s", URL, fetchLastErrString);
  507. goto failure;
  508. }
  509. if (sigint)
  510. goto signal;
  511. /* check that size is as expected */
  512. if (S_size) {
  513. if (us.size == -1) {
  514. warnx("%s: size unknown", URL);
  515. } else if (us.size != S_size) {
  516. warnx("%s: size mismatch: expected %jd, actual %jd",
  517. URL, (intmax_t)S_size, (intmax_t)us.size);
  518. goto failure;
  519. }
  520. }
  521. /* symlink instead of copy */
  522. if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
  523. char *name = fetchUnquotePath(url);
  524. if (name == NULL) {
  525. warnx("Can't unquote URL");
  526. goto failure;
  527. }
  528. if (symlink(name, path) == -1) {
  529. warn("%s: symlink()", path);
  530. free(name);
  531. goto failure;
  532. }
  533. free(name);
  534. goto success;
  535. }
  536. if (us.size == -1 && !o_stdout && v_level > 0)
  537. warnx("%s: size of remote file is not known", URL);
  538. if (v_level > 1) {
  539. if (sb.st_size != -1)
  540. fprintf(stderr, "local size / mtime: %jd / %ld\n",
  541. (intmax_t)sb.st_size, (long)sb.st_mtime);
  542. if (us.size != -1)
  543. fprintf(stderr, "remote size / mtime: %jd / %ld\n",
  544. (intmax_t)us.size, (long)us.mtime);
  545. }
  546. /* open output file */
  547. if (o_stdout) {
  548. /* output to stdout */
  549. of = stdout;
  550. } else if (r_flag && sb.st_size != -1) {
  551. /* resume mode, local file exists */
  552. if (!F_flag && us.mtime && sb.st_mtime != us.mtime) {
  553. /* no match! have to refetch */
  554. fetchIO_close(f);
  555. /* if precious, warn the user and give up */
  556. if (R_flag) {
  557. warnx("%s: local modification time "
  558. "does not match remote", path);
  559. goto failure_keep;
  560. }
  561. } else if (us.size != -1) {
  562. if (us.size == sb.st_size)
  563. /* nothing to do */
  564. goto success;
  565. if (sb.st_size > us.size) {
  566. /* local file too long! */
  567. warnx("%s: local file (%jd bytes) is longer "
  568. "than remote file (%jd bytes)", path,
  569. (intmax_t)sb.st_size, (intmax_t)us.size);
  570. goto failure;
  571. }
  572. /* we got it, open local file */
  573. if ((of = fopen(path, "a")) == NULL) {
  574. warn("%s: fopen()", path);
  575. goto failure;
  576. }
  577. /* check that it didn't move under our feet */
  578. if (fstat(fileno(of), &nsb) == -1) {
  579. /* can't happen! */
  580. warn("%s: fstat()", path);
  581. goto failure;
  582. }
  583. if (nsb.st_dev != sb.st_dev ||
  584. nsb.st_ino != nsb.st_ino ||
  585. nsb.st_size != sb.st_size) {
  586. warnx("%s: file has changed", URL);
  587. fclose(of);
  588. of = NULL;
  589. sb = nsb;
  590. }
  591. }
  592. } else if (m_flag && sb.st_size != -1) {
  593. /* mirror mode, local file exists */
  594. if (sb.st_size == us.size && sb.st_mtime == us.mtime)
  595. goto success;
  596. }
  597. if (of == NULL) {
  598. /*
  599. * We don't yet have an output file; either this is a
  600. * vanilla run with no special flags, or the local and
  601. * remote files didn't match.
  602. */
  603. if (url->offset > 0) {
  604. /*
  605. * We tried to restart a transfer, but for
  606. * some reason gave up - so we have to restart
  607. * from scratch if we want the whole file
  608. */
  609. url->offset = 0;
  610. if ((f = fetchXGet(url, &us, flags)) == NULL) {
  611. warnx("%s: %s", URL, fetchLastErrString);
  612. goto failure;
  613. }
  614. if (sigint)
  615. goto signal;
  616. }
  617. /* construct a temp file name */
  618. if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
  619. #ifndef __minix
  620. asprintf(&tmppath, "%s.fetch.XXXXXX", path);
  621. #else
  622. {
  623. int len;
  624. if((tmppath = malloc(sizeof(char)*MINBUFSIZE)) != NULL) {
  625. len = snprintf(tmppath, MINBUFSIZE, "%s.fetch.XXXXXX", path);
  626. if(len >= MINBUFSIZE) {
  627. free(tmppath);
  628. tmppath = NULL;
  629. }
  630. }
  631. }
  632. #endif
  633. if (tmppath != NULL) {
  634. int fd;
  635. fd = mkstemp(tmppath);
  636. if (fd == -1) {
  637. warn("%s: mkstemp failed", tmppath);
  638. goto failure;
  639. }
  640. fchown(fd, sb.st_uid, sb.st_gid);
  641. fchmod(fd, sb.st_mode & ALLPERMS);
  642. of = fdopen(fd, "w");
  643. if (of == NULL) {
  644. close(fd);
  645. unlink(tmppath);
  646. free(tmppath);
  647. tmppath = NULL;
  648. }
  649. }
  650. }
  651. if (of == NULL)
  652. of = fopen(path, "w");
  653. if (of == NULL) {
  654. warn("%s: open()", path);
  655. goto failure;
  656. }
  657. }
  658. count = url->offset;
  659. /* start the counter */
  660. stat_start(&xs, path, us.size, count);
  661. sigalrm = sigint = 0;
  662. /* suck in the data */
  663. #ifdef SIGINFO
  664. siginfo = 0;
  665. signal(SIGINFO, sig_handler);
  666. #endif
  667. while (!sigint) {
  668. if (us.size != -1 && us.size - count < B_size &&
  669. us.size - count >= 0)
  670. size = us.size - count;
  671. else
  672. size = B_size;
  673. #ifdef SIGINFO
  674. if (siginfo) {
  675. stat_display(&xs, 1);
  676. siginfo = 0;
  677. }
  678. #else
  679. /* Constant info is better than none. */
  680. if (v_level) {
  681. stat_display(&xs, 1);
  682. }
  683. #endif
  684. if ((ssize = fetchIO_read(f, buf, B_size)) == 0)
  685. break;
  686. if (ssize == -1 && errno == EINTR)
  687. continue;
  688. if (ssize == -1)
  689. break;
  690. size = ssize;
  691. stat_update(&xs, count += size);
  692. for (ptr = buf; size > 0; ptr += wr, size -= wr) {
  693. if ((wr = fwrite(ptr, 1, size, of)) < size) {
  694. if (ferror(of) && errno == EINTR && !sigint)
  695. clearerr(of);
  696. else
  697. break;
  698. }
  699. }
  700. if (size != 0)
  701. break;
  702. }
  703. if (!sigalrm)
  704. sigalrm = 0;
  705. #ifdef SIGINFO
  706. signal(SIGINFO, SIG_DFL);
  707. #endif
  708. stat_end(&xs);
  709. /*
  710. * If the transfer timed out or was interrupted, we still want to
  711. * set the mtime in case the file is not removed (-r or -R) and
  712. * the user later restarts the transfer.
  713. */
  714. signal:
  715. /* set mtime of local file */
  716. #ifndef __minix
  717. if (!n_flag && us.mtime && !o_stdout && of != NULL &&
  718. (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
  719. struct timeval tv[2];
  720. fflush(of);
  721. tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
  722. tv[1].tv_sec = (long)us.mtime;
  723. tv[0].tv_usec = tv[1].tv_usec = 0;
  724. if (utimes(tmppath ? tmppath : path, tv))
  725. warn("%s: utimes()", tmppath ? tmppath : path);
  726. }
  727. #else
  728. if (!n_flag && us.mtime && !o_stdout && of != NULL &&
  729. (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
  730. struct utimbuf ut;
  731. fflush(of);
  732. ut.actime = (us.atime ? us.atime : us.mtime);
  733. ut.modtime = us.mtime;
  734. if (utime(tmppath ? tmppath : path, &ut))
  735. warn("%s: utime()", tmppath ? tmppath : path);
  736. }
  737. #endif
  738. /* timed out or interrupted? */
  739. if (fetchLastErrCode == FETCH_TIMEOUT)
  740. sigalrm = 1;
  741. if (sigalrm)
  742. warnx("transfer timed out");
  743. if (sigint) {
  744. warnx("transfer interrupted");
  745. goto failure;
  746. }
  747. /* timeout / interrupt before connection completley established? */
  748. if (f == NULL)
  749. goto failure;
  750. if (!sigalrm && ferror(of)) {
  751. /* check the status of our files */
  752. warn("writing to %s failed", path);
  753. goto failure;
  754. }
  755. /* did the transfer complete normally? */
  756. if (us.size != -1 && count < us.size) {
  757. warnx("%s appears to be truncated: %jd/%jd bytes",
  758. path, (intmax_t)count, (intmax_t)us.size);
  759. goto failure_keep;
  760. }
  761. /*
  762. * If the transfer timed out and we didn't know how much to
  763. * expect, assume the worst (i.e. we didn't get all of it)
  764. */
  765. if (sigalrm && us.size == -1) {
  766. warnx("%s may be truncated", path);
  767. goto failure_keep;
  768. }
  769. success:
  770. r = 0;
  771. if (tmppath != NULL && rename(tmppath, path) == -1) {
  772. warn("%s: rename()", path);
  773. goto failure_keep;
  774. }
  775. goto done;
  776. failure:
  777. if (of && of != stdout && !R_flag && !r_flag)
  778. if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
  779. unlink(tmppath ? tmppath : path);
  780. if (R_flag && tmppath != NULL && sb.st_size == -1)
  781. rename(tmppath, path); /* ignore errors here */
  782. failure_keep:
  783. r = -1;
  784. goto done;
  785. done:
  786. if (f)
  787. fetchIO_close(f);
  788. if (of && of != stdout)
  789. fclose(of);
  790. if (url)
  791. fetchFreeURL(url);
  792. if (tmppath != NULL)
  793. free(tmppath);
  794. return (r);
  795. }
  796. static void
  797. usage(void)
  798. {
  799. #ifndef __minix
  800. fprintf(stderr, "%s\n%s\n%s\n",
  801. "usage: fetch [-146AFMPRUadilmnpqrsv] [-N netrc] [-o outputfile]",
  802. " [-S bytes] [-B bytes] [-T seconds] [-w seconds]",
  803. " [-h host -f file [-c dir] | URL ...]");
  804. #else
  805. fprintf(stderr, "%s\n%s\n%s\n",
  806. "usage: fetch [-146AFMPRUadilmnpqrsv] [-N netrc] [-o outputfile]",
  807. " [-S bytes] [-B bytes] [-T seconds] [-w seconds]",
  808. " [-h host -f file [-c dir] | URL ...]");
  809. #endif
  810. }
  811. /*
  812. * Entry point
  813. */
  814. int
  815. main(int argc, char *argv[])
  816. {
  817. struct stat sb;
  818. struct sigaction sa;
  819. const char *p, *s;
  820. char *end, *q;
  821. int c, e, r;
  822. #ifndef __minix
  823. while ((c = getopt(argc, argv,
  824. "14AaB:dFilMmN:no:qRrS:sT:Uvw:")) != -1)
  825. #else
  826. while ((c = getopt(argc, argv,
  827. "146AaB:dFilMmN:no:qRrS:sT:Uvw:")) != -1)
  828. #endif
  829. switch (c) {
  830. case '1':
  831. once_flag = 1;
  832. break;
  833. case '4':
  834. family = PF_INET;
  835. break;
  836. #ifndef __minix
  837. case '6':
  838. family = PF_INET6;
  839. break;
  840. #endif
  841. case 'A':
  842. A_flag = 1;
  843. break;
  844. case 'a':
  845. a_flag = 1;
  846. break;
  847. case 'B':
  848. B_size = (off_t)strtol(optarg, &end, 10);
  849. if (*optarg == '\0' || *end != '\0')
  850. errx(1, "invalid buffer size (%s)", optarg);
  851. break;
  852. case 'd':
  853. d_flag = 1;
  854. break;
  855. case 'F':
  856. F_flag = 1;
  857. break;
  858. case 'i':
  859. i_flag = 1;
  860. break;
  861. case 'l':
  862. l_flag = 1;
  863. break;
  864. case 'o':
  865. o_flag = 1;
  866. o_filename = optarg;
  867. break;
  868. case 'M':
  869. case 'm':
  870. if (r_flag)
  871. errx(1, "the -m and -r flags "
  872. "are mutually exclusive");
  873. m_flag = 1;
  874. break;
  875. case 'N':
  876. N_filename = optarg;
  877. break;
  878. case 'n':
  879. n_flag = 1;
  880. break;
  881. case 'q':
  882. v_level = 0;
  883. break;
  884. case 'R':
  885. R_flag = 1;
  886. break;
  887. case 'r':
  888. if (m_flag)
  889. errx(1, "the -m and -r flags "
  890. "are mutually exclusive");
  891. r_flag = 1;
  892. break;
  893. case 'S':
  894. S_size = (off_t)strtol(optarg, &end, 10);
  895. if (*optarg == '\0' || *end != '\0')
  896. errx(1, "invalid size (%s)", optarg);
  897. break;
  898. case 's':
  899. s_flag = 1;
  900. break;
  901. case 'T':
  902. T_secs = strtol(optarg, &end, 10);
  903. if (*optarg == '\0' || *end != '\0')
  904. errx(1, "invalid timeout (%s)", optarg);
  905. break;
  906. case 'U':
  907. U_flag = 1;
  908. break;
  909. case 'v':
  910. v_level++;
  911. break;
  912. case 'w':
  913. a_flag = 1;
  914. w_secs = strtol(optarg, &end, 10);
  915. if (*optarg == '\0' || *end != '\0')
  916. errx(1, "invalid delay (%s)", optarg);
  917. break;
  918. default:
  919. usage();
  920. exit(EX_USAGE);
  921. }
  922. argc -= optind;
  923. argv += optind;
  924. if (!argc) {
  925. usage();
  926. exit(EX_USAGE);
  927. }
  928. fetchConnectionCacheInit(10, 1);
  929. /* allocate buffer */
  930. if (B_size < MINBUFSIZE)
  931. B_size = MINBUFSIZE;
  932. if ((buf = malloc(B_size)) == NULL)
  933. errx(1, "%s", strerror(ENOMEM));
  934. /* timeouts */
  935. if ((s = getenv("FTP_TIMEOUT")) != NULL) {
  936. ftp_timeout = strtol(s, &end, 10);
  937. if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
  938. warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
  939. ftp_timeout = 0;
  940. }
  941. }
  942. if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
  943. http_timeout = strtol(s, &end, 10);
  944. if (*s == '\0' || *end != '\0' || http_timeout < 0) {
  945. warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
  946. http_timeout = 0;
  947. }
  948. }
  949. /* signal handling */
  950. sa.sa_flags = 0;
  951. sa.sa_handler = sig_handler;
  952. sigemptyset(&sa.sa_mask);
  953. sigaction(SIGALRM, &sa, NULL);
  954. sa.sa_flags = SA_RESETHAND;
  955. sigaction(SIGINT, &sa, NULL);
  956. /* output file */
  957. if (o_flag) {
  958. if (strcmp(o_filename, "-") == 0) {
  959. o_stdout = 1;
  960. if (i_flag) {
  961. warnx("-i and -o - are incompatible, dropping -i");
  962. i_flag = 0;
  963. }
  964. } else if (stat(o_filename, &sb) == -1) {
  965. if (errno == ENOENT) {
  966. if (argc > 1)
  967. errx(EX_USAGE, "%s is not a directory",
  968. o_filename);
  969. } else {
  970. err(EX_IOERR, "%s", o_filename);
  971. }
  972. } else {
  973. if (sb.st_mode & S_IFDIR)
  974. o_directory = 1;
  975. }
  976. }
  977. /* check if output is to a tty (for progress report) */
  978. v_tty = isatty(STDERR_FILENO);
  979. if (v_tty)
  980. pgrp = getpgrp();
  981. r = 0;
  982. /* authentication */
  983. if (v_tty)
  984. fetchAuthMethod = query_auth;
  985. if (N_filename != NULL)
  986. setenv("NETRC", N_filename, 1);
  987. while (argc) {
  988. if ((p = strrchr(*argv, '/')) == NULL)
  989. p = *argv;
  990. else
  991. p++;
  992. if (!*p)
  993. p = "fetch.out";
  994. fetchLastErrCode = 0;
  995. if (o_flag) {
  996. if (o_stdout) {
  997. e = fetch(*argv, "-");
  998. } else if (o_directory) {
  999. #ifndef __minix
  1000. asprintf(&q, "%s/%s", o_filename, p);
  1001. #else
  1002. {
  1003. int len;
  1004. if ((q = malloc(sizeof(char)*MINBUFSIZE)) != NULL) {
  1005. len = snprintf(q, MINBUFSIZE, "%s/%s", o_filename, p);
  1006. if (len >= MINBUFSIZE) {
  1007. free(q);
  1008. q = NULL;
  1009. }
  1010. }else{
  1011. err(1, "Unable to allocate memory");
  1012. }
  1013. }
  1014. #endif
  1015. e = fetch(*argv, q);
  1016. free(q);
  1017. } else {
  1018. e = fetch(*argv, o_filename);
  1019. }
  1020. } else {
  1021. e = fetch(*argv, p);
  1022. }
  1023. if (sigint)
  1024. kill(getpid(), SIGINT);
  1025. if (e == 0 && once_flag)
  1026. exit(0);
  1027. if (e) {
  1028. r = 1;
  1029. if ((fetchLastErrCode
  1030. && fetchLastErrCode != FETCH_UNAVAIL
  1031. && fetchLastErrCode != FETCH_MOVED
  1032. && fetchLastErrCode != FETCH_URL
  1033. && fetchLastErrCode != FETCH_RESOLV
  1034. && fetchLastErrCode != FETCH_UNKNOWN)) {
  1035. if (w_secs && v_level)
  1036. fprintf(stderr, "Waiting %ld seconds "
  1037. "before retrying\n", w_secs);
  1038. if (w_secs)
  1039. sleep(w_secs);
  1040. if (a_flag)
  1041. continue;
  1042. }
  1043. }
  1044. argc--, argv++;
  1045. }
  1046. exit(r);
  1047. }