1 /* $NetBSD: ftp.c,v 1.132 2005/05/14 15:26:43 lukem Exp $ */
4 * Copyright (c) 1996-2005 The NetBSD Foundation, Inc.
7 * This code is derived from software contributed to The NetBSD Foundation
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the NetBSD
21 * Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 * contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
40 * Copyright (c) 1985, 1989, 1993, 1994
41 * The Regents of the University of California. All rights reserved.
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. Neither the name of the University nor the names of its contributors
52 * may be used to endorse or promote products derived from this software
53 * without specific prior written permission.
55 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * Copyright (C) 1997 and 1998 WIDE Project.
70 * All rights reserved.
72 * Redistribution and use in source and binary forms, with or without
73 * modification, are permitted provided that the following conditions
75 * 1. Redistributions of source code must retain the above copyright
76 * notice, this list of conditions and the following disclaimer.
77 * 2. Redistributions in binary form must reproduce the above copyright
78 * notice, this list of conditions and the following disclaimer in the
79 * documentation and/or other materials provided with the distribution.
80 * 3. Neither the name of the project nor the names of its contributors
81 * may be used to endorse or promote products derived from this software
82 * without specific prior written permission.
84 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
85 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
86 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
87 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
88 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
89 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
90 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
91 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
92 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
93 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
97 #include <sys/cdefs.h>
100 static char sccsid[] = "@(#)ftp.c 8.6 (Berkeley) 10/27/94";
102 __RCSID("$NetBSD: ftp.c,v 1.132 2005/05/14 15:26:43 lukem Exp $");
104 #endif /* not lint */
106 #include <sys/types.h>
107 #include <sys/stat.h>
108 #include <sys/socket.h>
109 #include <sys/time.h>
111 #include <netinet/in.h>
112 #include <netinet/in_systm.h>
113 #include <netinet/ip.h>
114 #include <arpa/inet.h>
115 #include <arpa/ftp.h>
116 #include <arpa/telnet.h>
132 volatile sig_atomic_t abrtflag;
133 volatile sig_atomic_t timeoutflag;
138 char pasv[BUFSIZ]; /* passive port for proxy data connection */
140 static int empty(FILE *, FILE *, int);
144 struct sockaddr_in su_sin;
146 struct sockaddr_in6 su_sin6;
149 #if !HAVE_SOCKADDR_SA_LEN
154 #if !HAVE_SOCKADDR_SA_LEN
155 # define su_len si_len
157 # define su_len si_su.su_sin.sin_len
159 #define su_family si_su.su_sin.sin_family
160 #define su_port si_su.su_sin.sin_port
162 struct sockinet myctladdr, hisctladdr, data_addr;
165 hookup(char *host, char *port)
167 int s = -1, error, portnum;
168 struct addrinfo hints, *res, *res0;
169 char hbuf[MAXHOSTNAMELEN];
170 static char hostnamebuf[MAXHOSTNAMELEN];
171 char *cause = "unknown";
175 memset((char *)&hisctladdr, 0, sizeof (hisctladdr));
176 memset((char *)&myctladdr, 0, sizeof (myctladdr));
177 memset(&hints, 0, sizeof(hints));
178 portnum = parseport(port, FTP_PORT);
179 hints.ai_flags = AI_CANONNAME;
180 hints.ai_family = family;
181 hints.ai_socktype = SOCK_STREAM;
182 hints.ai_protocol = 0;
183 error = getaddrinfo(host, NULL, &hints, &res0);
185 warnx("%s", gai_strerror(error));
190 if (res0->ai_canonname)
191 (void)strlcpy(hostnamebuf, res0->ai_canonname,
192 sizeof(hostnamebuf));
194 (void)strlcpy(hostnamebuf, host, sizeof(hostnamebuf));
195 hostname = hostnamebuf;
197 for (res = res0; res; res = res->ai_next) {
199 * make sure that ai_addr is NOT an IPv4 mapped address.
200 * IPv4 mapped address complicates too many things in FTP
201 * protocol handling, as FTP protocol is defined differently
202 * between IPv4 and IPv6.
204 * This may not be the best way to handle this situation,
205 * since the semantics of IPv4 mapped address is defined in
206 * the kernel. There are configurations where we should use
207 * IPv4 mapped address as native IPv6 address, not as
208 * "an IPv6 address that embeds IPv4 address" (namely, SIIT).
210 * More complete solution would be to have an additional
211 * getsockopt to grab "real" peername/sockname. "real"
212 * peername/sockname will be AF_INET if IPv4 mapped address
213 * is used to embed IPv4 address, and will be AF_INET6 if
214 * we use it as native. What a mess!
217 #if 0 /*old behavior*/
218 if (res != res0) /* not on the first address */
220 if (res0->ai_next) /* if we have multiple possibilities */
223 if (getnameinfo(res->ai_addr, res->ai_addrlen,
224 hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST))
225 strlcpy(hbuf, "?", sizeof(hbuf));
226 fprintf(ttyout, "Trying %s...\n", hbuf);
228 ((struct sockaddr_in *)res->ai_addr)->sin_port = htons(portnum);
229 s = socket(res->ai_family, SOCK_STREAM, res->ai_protocol);
234 error = xconnect(s, res->ai_addr, res->ai_addrlen);
236 /* this "if" clause is to prevent print warning twice */
238 if (getnameinfo(res->ai_addr, res->ai_addrlen,
239 hbuf, sizeof(hbuf), NULL, 0,
241 strlcpy(hbuf, "?", sizeof(hbuf));
242 warn("connect to address %s", hbuf);
250 /* finally we got one */
259 memcpy(&hisctladdr.si_su, res->ai_addr, res->ai_addrlen);
260 hisctladdr.su_len = res->ai_addrlen;
264 len = hisctladdr.su_len;
265 if (getsockname(s, (struct sockaddr *)&myctladdr.si_su, &len) == -1) {
270 myctladdr.su_len = len;
272 #ifdef IPTOS_LOWDELAY
273 if (hisctladdr.su_family == AF_INET) {
274 int tos = IPTOS_LOWDELAY;
275 if (setsockopt(s, IPPROTO_IP, IP_TOS,
276 (void *)&tos, sizeof(tos)) == -1) {
278 warn("setsockopt %s (ignored)",
283 cin = fdopen(s, "r");
284 cout = fdopen(s, "w");
285 if (cin == NULL || cout == NULL) {
286 warnx("fdopen failed.");
295 fprintf(ttyout, "Connected to %s.\n", hostname);
296 if (getreply(0) > 2) { /* read startup message from server */
305 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE,
306 (void *)&on, sizeof(on)) == -1) {
308 warn("setsockopt %s (ignored)", "SO_OOBINLINE");
318 cmdabort(int notused)
325 write(fileno(ttyout), "\n", 1);
328 siglongjmp(ptabort, 1);
333 cmdtimeout(int notused)
339 write(fileno(ttyout), "\n", 1);
342 siglongjmp(ptabort, 1);
348 command(const char *fmt, ...)
355 fputs("---> ", ttyout);
357 if (strncmp("PASS ", fmt, 5) == 0)
358 fputs("PASS XXXX", ttyout);
359 else if (strncmp("ACCT ", fmt, 5) == 0)
360 fputs("ACCT XXXX", ttyout);
362 vfprintf(ttyout, fmt, ap);
367 warnx("No control connection for command.");
374 oldsigint = xsignal(SIGINT, cmdabort);
377 vfprintf(cout, fmt, ap);
382 r = getreply(!strcmp(fmt, "QUIT"));
383 if (abrtflag && oldsigint != SIG_IGN)
384 (*oldsigint)(SIGINT);
385 (void)xsignal(SIGINT, oldsigint);
390 getreply(int expecteof)
392 char current_line[BUFSIZ]; /* last line of previous reply */
395 int originalcode = 0, continuation = 0;
396 sigfunc oldsigint, oldsigalrm;
398 char *cp, *pt = pasv;
403 oldsigint = xsignal(SIGINT, cmdabort);
404 oldsigalrm = xsignal(SIGALRM, cmdtimeout);
406 for (line = 0 ;; line++) {
409 while (alarmtimer(60),((c = getc(cin)) != '\n')) {
410 if (c == IAC) { /* handle telnet commands */
411 switch (c = getc(cin)) {
415 fprintf(cout, "%c%c%c", IAC, DONT, c);
421 fprintf(cout, "%c%c%c", IAC, WONT, c);
432 * these will get trashed by pswitch()
435 int reply_timeoutflag = timeoutflag;
436 int reply_abrtflag = abrtflag;
439 if (expecteof && feof(cin)) {
440 (void)xsignal(SIGINT, oldsigint);
441 (void)xsignal(SIGALRM, oldsigalrm);
448 if (reply_timeoutflag)
450 "421 Service not available, remote server timed out. Connection closed\n",
452 else if (reply_abrtflag)
454 "421 Service not available, user interrupt. Connection closed.\n",
458 "421 Service not available, remote server has closed connection.\n",
460 (void)fflush(ttyout);
463 (void)xsignal(SIGINT, oldsigint);
464 (void)xsignal(SIGALRM, oldsigalrm);
467 if (c != '\r' && (verbose > 0 ||
468 ((verbose > -1 && n == '5' && dig > 4) &&
469 (((!n && c < '5') || (n && n < '5'))
470 || !retry_connect)))) {
472 (dig == 1 || (dig == 5 && verbose == 0)))
473 fprintf(ttyout, "%s:", hostname);
474 (void)putc(c, ttyout);
476 if (dig < 4 && isdigit(c))
477 code = code * 10 + (c - '0');
478 if (!pflag && (code == 227 || code == 228))
480 else if (!pflag && code == 229)
482 if (dig > 4 && pflag == 1 && isdigit(c))
485 if (c != '\r' && c != ')') {
486 if (pt < &pasv[sizeof(pasv) - 1])
493 if (pflag == 100 && c == '(')
495 if (dig == 4 && c == '-') {
502 if (cp < ¤t_line[sizeof(current_line) - 1])
505 if (verbose > 0 || ((verbose > -1 && n == '5') &&
506 (n < '5' || !retry_connect))) {
507 (void)putc(c, ttyout);
508 (void)fflush (ttyout);
514 (void)strlcpy(reply_string, current_line,
515 sizeof(reply_string));
516 if (line > 0 && code == 0 && reply_callback != NULL)
517 (*reply_callback)(current_line);
518 if (continuation && code != originalcode) {
519 if (originalcode == 0)
526 (void)xsignal(SIGINT, oldsigint);
527 (void)xsignal(SIGALRM, oldsigalrm);
528 if (code == 421 || originalcode == 421)
530 if (abrtflag && oldsigint != cmdabort && oldsigint != SIG_IGN)
531 (*oldsigint)(SIGINT);
532 if (timeoutflag && oldsigalrm != cmdtimeout &&
533 oldsigalrm != SIG_IGN)
534 (*oldsigalrm)(SIGINT);
540 empty(FILE *cin, FILE *din, int sec)
543 struct pollfd pfd[2];
547 pfd[nfd].fd = fileno(cin);
548 pfd[nfd++].events = POLLIN;
552 pfd[nfd].fd = fileno(din);
553 pfd[nfd++].events = POLLIN;
556 if ((nr = xpoll(pfd, nfd, sec * 1000)) <= 0)
562 nr |= (pfd[nfd++].revents & POLLIN) ? 1 : 0;
564 nr |= (pfd[nfd++].revents & POLLIN) ? 2 : 0;
568 sigjmp_buf xferabort;
571 abortxfer(int notused)
580 switch (direction[0]) {
582 strlcpy(msgbuf, "\nreceive", sizeof(msgbuf));
585 strlcpy(msgbuf, "\nsend", sizeof(msgbuf));
588 errx(1, "abortxfer called with unknown direction `%s'",
591 len = strlcat(msgbuf, " aborted. Waiting for remote to finish abort.\n",
593 write(fileno(ttyout), msgbuf, len);
594 siglongjmp(xferabort, 1);
598 sendrequest(const char *cmd, const char *local, const char *remote,
604 int (*closefunc)(FILE *);
605 sigfunc oldintr, oldintp;
606 volatile off_t hashbytes;
608 static size_t bufsize;
612 #ifdef __GNUC__ /* to shut up gcc warnings */
626 oprogress = progress;
627 if (verbose && printnames) {
628 if (local && *local != '-')
629 fprintf(ttyout, "local: %s ", local);
631 fprintf(ttyout, "remote: %s\n", remote);
634 proxtrans(cmd, local, remote);
643 if (sigsetjmp(xferabort, 1)) {
649 (void)xsignal(SIGQUIT, psummary);
650 oldintr = xsignal(SIGINT, abortxfer);
651 if (strcmp(local, "-") == 0) {
654 } else if (*local == '|') {
655 oldintp = xsignal(SIGPIPE, SIG_IGN);
656 fin = popen(local + 1, "r");
658 warn("%s", local + 1);
665 fin = fopen(local, "r");
667 warn("local: %s", local);
672 if (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode)) {
673 fprintf(ttyout, "%s: not a plain file.\n", local);
677 filesize = st.st_size;
683 if (sigsetjmp(xferabort, 1))
687 (strcmp(cmd, "STOR") == 0 || strcmp(cmd, "APPE") == 0)) {
693 rc = fseeko(fin, restart_point, SEEK_SET);
697 rc = lseek(fileno(fin), restart_point, SEEK_SET);
701 warn("local: %s", local);
704 if (command("REST " LLF, (LLT)restart_point) != CONTINUE)
709 if (command("%s %s", cmd, remote) != PRELIM)
712 if (command("%s", cmd) != PRELIM)
716 dout = dataconn(lmode);
720 if (sndbuf_size > bufsize) {
723 bufsize = sndbuf_size;
724 buf = xmalloc(bufsize);
728 oldintp = xsignal(SIGPIPE, SIG_IGN);
734 if (rate_put) { /* rate limited */
736 struct timeval then, now, td;
739 (void)gettimeofday(&then, NULL);
743 if ((c = read(fileno(fin), buf,
744 MIN(bufsize, bufrem))) <= 0)
748 for (bufp = buf; c > 0;
750 if ((d = write(fileno(dout),
756 (!progress || filesize < 0) ) {
757 while (bytes >= hashbytes) {
758 (void)putc('#', ttyout);
761 (void)fflush(ttyout);
765 (void)gettimeofday(&now, NULL);
766 timersub(&now, &then, &td);
769 usleep(1000000 - td.tv_usec);
772 } else { /* simpler/faster; no rate limit */
775 if ((c = read(fileno(fin), buf, bufsize)) <= 0)
778 for (bufp = buf; c > 0; c -= d, bufp += d)
779 if ((d = write(fileno(dout), bufp, c))
784 if (hash && (!progress || filesize < 0) ) {
785 while (bytes >= hashbytes) {
786 (void)putc('#', ttyout);
789 (void)fflush(ttyout);
794 if (hash && (!progress || filesize < 0) && bytes > 0) {
796 (void)putc('#', ttyout);
797 (void)putc('\n', ttyout);
800 warn("local: %s", local);
809 while ((c = getc(fin)) != EOF) {
811 while (hash && (!progress || filesize < 0) &&
812 (bytes >= hashbytes)) {
813 (void)putc('#', ttyout);
814 (void)fflush(ttyout);
819 (void)putc('\r', dout);
824 #if 0 /* this violates RFC */
826 (void)putc('\0', dout);
831 if (hash && (!progress || filesize < 0)) {
832 if (bytes < hashbytes)
833 (void)putc('#', ttyout);
834 (void)putc('\n', ttyout);
837 warn("local: %s", local);
847 if (closefunc != NULL) {
859 (void)xsignal(SIGINT, oldintr);
880 (void)xsignal(SIGINT, oldintr);
882 (void)xsignal(SIGPIPE, oldintp);
887 if (closefunc != NULL && fin != NULL)
891 progress = oprogress;
897 recvrequest(const char *cmd, const char *local, const char *remote,
898 const char *lmode, int printnames, int ignorespecial)
901 int (*closefunc)(FILE *);
902 sigfunc oldintr, oldintp;
904 volatile int is_retr, tcrflag, bare_lfs;
905 static size_t bufsize;
907 volatile off_t hashbytes;
910 struct timeval tval[2];
914 #ifdef __GNUC__ /* to shut up gcc warnings */
926 direction = "received";
930 oprogress = progress;
931 opreserve = preserve;
932 is_retr = (strcmp(cmd, "RETR") == 0);
933 if (is_retr && verbose && printnames) {
934 if (local && (ignorespecial || *local != '-'))
935 fprintf(ttyout, "local: %s ", local);
937 fprintf(ttyout, "remote: %s\n", remote);
939 if (proxy && is_retr) {
940 proxtrans(cmd, local, remote);
946 tcrflag = !crflag && is_retr;
947 if (sigsetjmp(xferabort, 1)) {
953 (void)xsignal(SIGQUIT, psummary);
954 oldintr = xsignal(SIGINT, abortxfer);
955 if (ignorespecial || (strcmp(local, "-") && *local != '|')) {
956 if (access(local, W_OK) < 0) {
957 char *dir = strrchr(local, '/');
959 if (errno != ENOENT && errno != EACCES) {
960 warn("local: %s", local);
966 d = access(dir == local ? "/" :
967 dir ? local : ".", W_OK);
971 warn("local: %s", local);
975 if (!runique && errno == EACCES &&
976 chmod(local, (S_IRUSR|S_IWUSR)) < 0) {
977 warn("local: %s", local);
981 if (runique && errno == EACCES &&
982 (local = gunique(local)) == NULL) {
987 else if (runique && (local = gunique(local)) == NULL) {
993 if (curtype != TYPE_A)
994 changetype(TYPE_A, 0);
998 filesize = remotesize(remote, 0);
999 if (code == 421 || code == -1)
1006 if (sigsetjmp(xferabort, 1))
1008 if (is_retr && restart_point &&
1009 command("REST " LLF, (LLT) restart_point) != CONTINUE)
1011 if (! EMPTYSTRING(remote)) {
1012 if (command("%s %s", cmd, remote) != PRELIM)
1015 if (command("%s", cmd) != PRELIM)
1018 din = dataconn("r");
1021 if (!ignorespecial && strcmp(local, "-") == 0) {
1025 } else if (!ignorespecial && *local == '|') {
1026 oldintp = xsignal(SIGPIPE, SIG_IGN);
1027 fout = popen(local + 1, "w");
1029 warn("%s", local+1);
1036 fout = fopen(local, lmode);
1038 warn("local: %s", local);
1044 if (fstat(fileno(fout), &st) != -1 && !S_ISREG(st.st_mode)) {
1048 if (rcvbuf_size > bufsize) {
1051 bufsize = rcvbuf_size;
1052 buf = xmalloc(bufsize);
1061 if (is_retr && restart_point &&
1062 lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1063 warn("local: %s", local);
1066 if (rate_get) { /* rate limiting */
1068 struct timeval then, now, td;
1071 (void)gettimeofday(&then, NULL);
1073 for (bufrem = rate_get; bufrem > 0; ) {
1074 if ((c = read(fileno(din), buf,
1075 MIN(bufsize, bufrem))) <= 0)
1079 if ((d = write(fileno(fout), buf, c))
1083 (!progress || filesize < 0)) {
1084 while (bytes >= hashbytes) {
1085 (void)putc('#', ttyout);
1088 (void)fflush(ttyout);
1091 /* sleep until time is up */
1093 (void)gettimeofday(&now, NULL);
1094 timersub(&now, &then, &td);
1097 usleep(1000000 - td.tv_usec);
1100 } else { /* faster code (no limiting) */
1103 if ((c = read(fileno(din), buf, bufsize)) <= 0)
1106 if ((d = write(fileno(fout), buf, c)) != c)
1108 if (hash && (!progress || filesize < 0)) {
1109 while (bytes >= hashbytes) {
1110 (void)putc('#', ttyout);
1113 (void)fflush(ttyout);
1118 if (hash && (!progress || filesize < 0) && bytes > 0) {
1120 (void)putc('#', ttyout);
1121 (void)putc('\n', ttyout);
1130 warn("local: %s", local);
1132 warnx("%s: short write", local);
1137 if (is_retr && restart_point) {
1141 if (fseeko(fout, (off_t)0, SEEK_SET) < 0)
1143 for (i = 0; i++ < restart_point;) {
1144 if ((ch = getc(fout)) == EOF)
1149 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1151 warn("local: %s", local);
1155 while ((c = getc(din)) != EOF) {
1159 while (hash && (!progress || filesize < 0) &&
1160 (bytes >= hashbytes)) {
1161 (void)putc('#', ttyout);
1162 (void)fflush(ttyout);
1166 if ((c = getc(din)) != '\n' || tcrflag) {
1169 (void)putc('\r', fout);
1178 (void)putc(c, fout);
1183 if (hash && (!progress || filesize < 0)) {
1184 if (bytes < hashbytes)
1185 (void)putc('#', ttyout);
1186 (void)putc('\n', ttyout);
1194 warn("local: %s", local);
1199 if (closefunc != NULL) {
1208 "WARNING! %d bare linefeeds received in ASCII mode.\n",
1210 fputs("File may not have transferred correctly.\n", ttyout);
1212 if (bytes >= 0 && is_retr) {
1215 if (preserve && (closefunc == fclose)) {
1216 mtime = remotemodtime(remote, 0);
1218 (void)gettimeofday(&tval[0], NULL);
1219 tval[1].tv_sec = mtime;
1220 tval[1].tv_usec = 0;
1221 if (utimes(local, tval) == -1) {
1223 "Can't change modification time on %s to %s",
1224 local, asctime(localtime(&mtime)));
1233 * abort using RFC 959 recommended IP,SYNC sequence
1235 if (! sigsetjmp(xferabort, 1)) {
1236 /* this is the first call */
1237 (void)xsignal(SIGINT, abort_squared);
1250 (void)xsignal(SIGINT, oldintr);
1252 (void)xsignal(SIGPIPE, oldintp);
1257 if (closefunc != NULL && fout != NULL)
1261 progress = oprogress;
1262 preserve = opreserve;
1267 * Need to start a listen on the data channel before we send the command,
1268 * otherwise the server's connect may fail.
1274 int result, tmpno = 0;
1277 u_int addr[16], port[2];
1280 char *pasvcmd = NULL;
1283 if (myctladdr.su_family == AF_INET6 && debug &&
1284 (IN6_IS_ADDR_LINKLOCAL(&myctladdr.si_su.su_sin6.sin6_addr) ||
1285 IN6_IS_ADDR_SITELOCAL(&myctladdr.si_su.su_sin6.sin6_addr))) {
1286 warnx("use of scoped address can be troublesome");
1291 data_addr = myctladdr;
1292 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1297 if ((options & SO_DEBUG) &&
1298 setsockopt(data, SOL_SOCKET, SO_DEBUG,
1299 (void *)&on, sizeof(on)) == -1) {
1301 warn("setsockopt %s (ignored)", "SO_DEBUG");
1303 result = COMPLETE + 1;
1304 switch (data_addr.su_family) {
1306 if (epsv4 && !epsv4bad) {
1308 result = command("EPSV");
1312 * this code is to be friendly with broken
1315 if (code / 10 == 22 && code != 229) {
1317 "wrong server: return code must be 229\n",
1319 result = COMPLETE + 1;
1321 if (result != COMPLETE) {
1325 "disabling epsv4 for this connection\n",
1329 if (result != COMPLETE) {
1331 result = command("PASV");
1339 result = command("EPSV");
1342 /* this code is to be friendly with broken BSDI ftpd */
1343 if (code / 10 == 22 && code != 229) {
1345 "wrong server: return code must be 229\n",
1347 result = COMPLETE + 1;
1349 if (result != COMPLETE) {
1351 result = command("LPSV");
1358 result = COMPLETE + 1;
1361 if (result != COMPLETE) {
1362 if (activefallback) {
1371 fputs("Passive mode refused.\n", ttyout);
1375 #define pack2(var, off) \
1376 (((var[(off) + 0] & 0xff) << 8) | ((var[(off) + 1] & 0xff) << 0))
1377 #define pack4(var, off) \
1378 (((var[(off) + 0] & 0xff) << 24) | ((var[(off) + 1] & 0xff) << 16) | \
1379 ((var[(off) + 2] & 0xff) << 8) | ((var[(off) + 3] & 0xff) << 0))
1380 #define UC(b) (((int)b)&0xff)
1383 * What we've got at this point is a string of comma separated
1384 * one-byte unsigned integer values, separated by commas.
1386 if (strcmp(pasvcmd, "PASV") == 0) {
1387 if (data_addr.su_family != AF_INET) {
1389 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1393 if (code / 10 == 22 && code != 227) {
1394 fputs("wrong server: return code must be 227\n",
1399 error = sscanf(pasv, "%u,%u,%u,%u,%u,%u",
1400 &addr[0], &addr[1], &addr[2], &addr[3],
1401 &port[0], &port[1]);
1404 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1409 memset(&data_addr, 0, sizeof(data_addr));
1410 data_addr.su_family = AF_INET;
1411 data_addr.su_len = sizeof(struct sockaddr_in);
1412 data_addr.si_su.su_sin.sin_addr.s_addr =
1413 htonl(pack4(addr, 0));
1414 data_addr.su_port = htons(pack2(port, 0));
1415 } else if (strcmp(pasvcmd, "LPSV") == 0) {
1416 if (code / 10 == 22 && code != 228) {
1417 fputs("wrong server: return code must be 228\n",
1422 switch (data_addr.su_family) {
1424 error = sscanf(pasv,
1425 "%u,%u,%u,%u,%u,%u,%u,%u,%u",
1427 &addr[0], &addr[1], &addr[2], &addr[3],
1428 &pal, &port[0], &port[1]);
1431 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1435 if (af != 4 || hal != 4 || pal != 2) {
1437 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1443 memset(&data_addr, 0, sizeof(data_addr));
1444 data_addr.su_family = AF_INET;
1445 data_addr.su_len = sizeof(struct sockaddr_in);
1446 data_addr.si_su.su_sin.sin_addr.s_addr =
1447 htonl(pack4(addr, 0));
1448 data_addr.su_port = htons(pack2(port, 0));
1452 error = sscanf(pasv,
1453 "%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u",
1455 &addr[0], &addr[1], &addr[2], &addr[3],
1456 &addr[4], &addr[5], &addr[6], &addr[7],
1457 &addr[8], &addr[9], &addr[10],
1458 &addr[11], &addr[12], &addr[13],
1459 &addr[14], &addr[15],
1460 &pal, &port[0], &port[1]);
1463 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1467 if (af != 6 || hal != 16 || pal != 2) {
1469 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1475 memset(&data_addr, 0, sizeof(data_addr));
1476 data_addr.su_family = AF_INET6;
1477 data_addr.su_len = sizeof(struct sockaddr_in6);
1480 for (i = 0; i < sizeof(struct in6_addr); i++) {
1481 data_addr.si_su.su_sin6.sin6_addr.s6_addr[i] =
1485 data_addr.su_port = htons(pack2(port, 0));
1491 } else if (strcmp(pasvcmd, "EPSV") == 0) {
1495 if (code / 10 == 22 && code != 229) {
1496 fputs("wrong server: return code must be 229\n",
1501 if (sscanf(pasv, "%c%c%c%d%c", &delim[0],
1502 &delim[1], &delim[2], &port[1],
1504 fputs("parse error!\n", ttyout);
1508 if (delim[0] != delim[1] || delim[0] != delim[2]
1509 || delim[0] != delim[3]) {
1510 fputs("parse error!\n", ttyout);
1514 data_addr = hisctladdr;
1515 data_addr.su_port = htons(port[1]);
1519 while (xconnect(data, (struct sockaddr *)&data_addr.si_su,
1520 data_addr.su_len) < 0) {
1521 if (activefallback) {
1530 warn("connect for data channel");
1533 #ifdef IPTOS_THROUGHPUT
1534 if (data_addr.su_family == AF_INET) {
1535 on = IPTOS_THROUGHPUT;
1536 if (setsockopt(data, IPPROTO_IP, IP_TOS,
1537 (void *)&on, sizeof(on)) == -1) {
1539 warn("setsockopt %s (ignored)",
1540 "IPTOS_THROUGHPUT");
1548 data_addr = myctladdr;
1550 data_addr.su_port = 0; /* let system pick one */
1553 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1561 if (setsockopt(data, SOL_SOCKET, SO_REUSEADDR,
1562 (void *)&on, sizeof(on)) == -1) {
1563 warn("setsockopt %s", "SO_REUSEADDR");
1566 if (bind(data, (struct sockaddr *)&data_addr.si_su,
1567 data_addr.su_len) < 0) {
1571 if ((options & SO_DEBUG) &&
1572 setsockopt(data, SOL_SOCKET, SO_DEBUG,
1573 (void *)&on, sizeof(on)) == -1) {
1575 warn("setsockopt %s (ignored)", "SO_DEBUG");
1577 len = sizeof(data_addr.si_su);
1578 memset((char *)&data_addr, 0, sizeof (data_addr));
1579 if (getsockname(data, (struct sockaddr *)&data_addr.si_su, &len) == -1) {
1580 warn("getsockname");
1583 data_addr.su_len = len;
1584 if (xlisten(data, 1) < 0)
1588 char hname[NI_MAXHOST], sname[NI_MAXSERV];
1590 struct sockinet tmp;
1592 switch (data_addr.su_family) {
1594 if (!epsv4 || epsv4bad) {
1595 result = COMPLETE + 1;
1602 af = (data_addr.su_family == AF_INET) ? 1 : 2;
1605 if (tmp.su_family == AF_INET6)
1606 tmp.si_su.su_sin6.sin6_scope_id = 0;
1608 if (getnameinfo((struct sockaddr *)&tmp.si_su,
1609 tmp.su_len, hname, sizeof(hname), sname,
1610 sizeof(sname), NI_NUMERICHOST | NI_NUMERICSERV)) {
1613 result = command("EPRT |%d|%s|%s|", af, hname,
1617 if (result != COMPLETE) {
1621 "disabling epsv4 for this connection\n",
1627 result = COMPLETE + 1;
1630 if (result == COMPLETE)
1633 switch (data_addr.su_family) {
1635 a = (char *)&data_addr.si_su.su_sin.sin_addr;
1636 p = (char *)&data_addr.su_port;
1637 result = command("PORT %d,%d,%d,%d,%d,%d",
1638 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
1639 UC(p[0]), UC(p[1]));
1643 a = (char *)&data_addr.si_su.su_sin6.sin6_addr;
1644 p = (char *)&data_addr.su_port;
1646 "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
1648 UC(a[0]),UC(a[1]),UC(a[2]),UC(a[3]),
1649 UC(a[4]),UC(a[5]),UC(a[6]),UC(a[7]),
1650 UC(a[8]),UC(a[9]),UC(a[10]),UC(a[11]),
1651 UC(a[12]),UC(a[13]),UC(a[14]),UC(a[15]),
1652 2, UC(p[0]), UC(p[1]));
1656 result = COMPLETE + 1; /* xxx */
1662 if (result == ERROR && sendport == -1) {
1667 return (result != COMPLETE);
1671 #ifdef IPTOS_THROUGHPUT
1672 if (data_addr.su_family == AF_INET) {
1673 on = IPTOS_THROUGHPUT;
1674 if (setsockopt(data, IPPROTO_IP, IP_TOS,
1675 (void *)&on, sizeof(on)) == -1)
1677 warn("setsockopt %s (ignored)",
1678 "IPTOS_THROUGHPUT");
1691 dataconn(const char *lmode)
1693 struct sockinet from;
1694 int s, flags, rv, timeout;
1695 struct timeval endtime, now, td;
1696 struct pollfd pfd[1];
1699 if (passivemode) /* passive data connection */
1700 return (fdopen(data, lmode));
1702 /* active mode data connection */
1704 if ((flags = fcntl(data, F_GETFL, 0)) == -1)
1705 goto dataconn_failed; /* get current socket flags */
1706 if (fcntl(data, F_SETFL, flags | O_NONBLOCK) == -1)
1707 goto dataconn_failed; /* set non-blocking connect */
1709 /* NOTE: we now must restore socket flags on successful exit */
1711 /* limit time waiting on listening socket */
1713 pfd[0].events = POLLIN;
1714 (void)gettimeofday(&endtime, NULL); /* determine end time */
1715 endtime.tv_sec += (quit_time > 0) ? quit_time: 60;
1716 /* without -q, default to 60s */
1718 (void)gettimeofday(&now, NULL);
1719 timersub(&endtime, &now, &td);
1720 timeout = td.tv_sec * 1000 + td.tv_usec/1000;
1723 rv = xpoll(pfd, 1, timeout);
1724 } while (rv == -1 && errno == EINTR); /* loop until poll ! EINTR */
1726 warn("poll waiting before accept");
1727 goto dataconn_failed;
1730 warn("poll timeout waiting before accept");
1731 goto dataconn_failed;
1734 /* (non-blocking) accept the connection */
1735 fromlen = myctladdr.su_len;
1737 s = accept(data, (struct sockaddr *) &from.si_su, &fromlen);
1738 } while (s == -1 && errno == EINTR); /* loop until accept ! EINTR */
1741 goto dataconn_failed;
1746 if (fcntl(data, F_SETFL, flags) == -1) /* restore socket flags */
1747 goto dataconn_failed;
1749 #ifdef IPTOS_THROUGHPUT
1750 if (from.su_family == AF_INET) {
1751 int tos = IPTOS_THROUGHPUT;
1752 if (setsockopt(s, IPPROTO_IP, IP_TOS,
1753 (void *)&tos, sizeof(tos)) == -1) {
1755 warn("setsockopt %s (ignored)",
1756 "IPTOS_THROUGHPUT");
1760 return (fdopen(data, lmode));
1769 psabort(int notused)
1783 static struct comvars {
1785 char name[MAXHOSTNAMELEN];
1786 struct sockinet mctl;
1787 struct sockinet hctl;
1800 char mi[MAXPATHLEN];
1801 char mo[MAXPATHLEN];
1802 } proxstruct, tmpstruct;
1803 struct comvars *ip, *op;
1806 oldintr = xsignal(SIGINT, psabort);
1820 ip->connect = connected;
1821 connected = op->connect;
1823 (void)strlcpy(ip->name, hostname, sizeof(ip->name));
1826 hostname = op->name;
1827 ip->hctl = hisctladdr;
1828 hisctladdr = op->hctl;
1829 ip->mctl = myctladdr;
1830 myctladdr = op->mctl;
1837 ip->curtpe = curtype;
1838 curtype = op->curtpe;
1841 ip->sunqe = sunique;
1842 sunique = op->sunqe;
1843 ip->runqe = runique;
1844 runique = op->runqe;
1849 (void)strlcpy(ip->nti, ntin, sizeof(ip->nti));
1850 (void)strlcpy(ntin, op->nti, sizeof(ntin));
1851 (void)strlcpy(ip->nto, ntout, sizeof(ip->nto));
1852 (void)strlcpy(ntout, op->nto, sizeof(ntout));
1853 ip->mapflg = mapflag;
1854 mapflag = op->mapflg;
1855 (void)strlcpy(ip->mi, mapin, sizeof(ip->mi));
1856 (void)strlcpy(mapin, op->mi, sizeof(mapin));
1857 (void)strlcpy(ip->mo, mapout, sizeof(ip->mo));
1858 (void)strlcpy(mapout, op->mo, sizeof(mapout));
1859 (void)xsignal(SIGINT, oldintr);
1867 abortpt(int notused)
1873 write(fileno(ttyout), "\n", 1);
1877 siglongjmp(ptabort, 1);
1881 proxtrans(const char *cmd, const char *local, const char *remote)
1884 int prox_type, nfnd;
1885 volatile int secndflag;
1888 #ifdef __GNUC__ /* to shut up gcc warnings */
1895 if (strcmp(cmd, "RETR"))
1898 cmd2 = runique ? "STOU" : "STOR";
1899 if ((prox_type = type) == 0) {
1900 if (unix_server && unix_proxy)
1905 if (curtype != prox_type)
1906 changetype(prox_type, 1);
1907 if (command("PASV") != COMPLETE) {
1908 fputs("proxy server does not support third party transfers.\n",
1914 fputs("No primary connection.\n", ttyout);
1919 if (curtype != prox_type)
1920 changetype(prox_type, 1);
1921 if (command("PORT %s", pasv) != COMPLETE) {
1925 if (sigsetjmp(ptabort, 1))
1927 oldintr = xsignal(SIGINT, abortpt);
1928 if ((restart_point &&
1929 (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1930 || (command("%s %s", cmd, remote) != PRELIM)) {
1931 (void)xsignal(SIGINT, oldintr);
1938 if ((restart_point &&
1939 (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1940 || (command("%s %s", cmd2, local) != PRELIM))
1946 (void)xsignal(SIGINT, oldintr);
1949 fprintf(ttyout, "local: %s remote: %s\n", local, remote);
1952 if (sigsetjmp(xferabort, 1)) {
1953 (void)xsignal(SIGINT, oldintr);
1956 (void)xsignal(SIGINT, abort_squared);
1958 if (strcmp(cmd, "RETR") && !proxy)
1960 else if (!strcmp(cmd, "RETR") && proxy)
1962 if (!cpend && !secndflag) { /* only here if cmd = "STOR" (proxy=1) */
1963 if (command("%s %s", cmd2, local) != PRELIM) {
1971 (void)xsignal(SIGINT, oldintr);
1977 if (!cpend && !secndflag) { /* only if cmd = "RETR" (proxy=1) */
1978 if (command("%s %s", cmd2, local) != PRELIM) {
1985 (void)xsignal(SIGINT, oldintr);
1993 if ((nfnd = empty(cin, NULL, 10)) <= 0) {
2008 (void)xsignal(SIGINT, oldintr);
2012 reset(int argc, char *argv[])
2016 if (argc == 0 && argv != NULL) {
2017 fprintf(ttyout, "usage: %s\n", argv[0]);
2022 if ((nfnd = empty(cin, NULL, 0)) < 0) {
2032 gunique(const char *local)
2034 static char new[MAXPATHLEN];
2035 char *cp = strrchr(local, '/');
2036 int d, count=0, len;
2041 d = access(cp == local ? "/" : cp ? local : ".", W_OK);
2045 warn("local: %s", local);
2048 len = strlcpy(new, local, sizeof(new));
2052 if (++count == 100) {
2053 fputs("runique: can't find unique file name.\n",
2063 if ((d = access(new, F_OK)) < 0)
2067 else if (*(cp - 2) == '.')
2070 *(cp - 2) = *(cp - 2) + 1;
2079 * aborts abort_remote(). lostpeer() is called because if the user is
2080 * too impatient to wait or there's another problem then ftp really
2081 * needs to get back to a known state.
2084 abort_squared(int dummy)
2091 len = strlcpy(msgbuf, "\nremote abort aborted; closing connection.\n",
2093 write(fileno(ttyout), msgbuf, len);
2095 siglongjmp(xferabort, 1);
2099 abort_remote(FILE *din)
2105 warnx("Lost control connection for abort.");
2112 * send IAC in urgent mode instead of DM because 4.3BSD places oob mark
2113 * after urgent byte rather than before as is protocol now
2118 if (send(fileno(cout), buf, 3, MSG_OOB) != 3)
2120 fprintf(cout, "%cABOR\r\n", DM);
2122 if ((nfnd = empty(cin, din, 10)) <= 0) {
2129 if (din && (nfnd & 2)) {
2130 while (read(fileno(din), buf, BUFSIZ) > 0)
2133 if (getreply(0) == ERROR && code == 552) {
2134 /* 552 needed for nic style abort */
2141 ai_unmapped(struct addrinfo *ai)
2144 struct sockaddr_in6 *sin6;
2145 struct sockaddr_in sin;
2148 if (ai->ai_family != AF_INET6)
2150 if (ai->ai_addrlen != sizeof(struct sockaddr_in6) ||
2151 sizeof(sin) > ai->ai_addrlen)
2153 sin6 = (struct sockaddr_in6 *)ai->ai_addr;
2154 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
2157 memset(&sin, 0, sizeof(sin));
2158 sin.sin_family = AF_INET;
2159 len = sizeof(struct sockaddr_in);
2160 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
2161 sizeof(sin.sin_addr));
2162 sin.sin_port = sin6->sin6_port;
2164 ai->ai_family = AF_INET;
2165 #if HAVE_SOCKADDR_SA_LEN
2168 memcpy(ai->ai_addr, &sin, len);
2169 ai->ai_addrlen = len;