1 /* $NetBSD: ftp.c,v 1.142 2006/10/23 19:53:24 christos 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.142 2006/10/23 19:53:24 christos 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: %s", host, 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 (verbose && res0->ai_next) {
218 /* if we have multiple possibilities */
219 if (getnameinfo(res->ai_addr, res->ai_addrlen,
220 hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST))
221 strlcpy(hbuf, "?", sizeof(hbuf));
222 fprintf(ttyout, "Trying %s...\n", hbuf);
224 ((struct sockaddr_in *)res->ai_addr)->sin_port = htons(portnum);
225 s = socket(res->ai_family, SOCK_STREAM, res->ai_protocol);
230 error = ftp_connect(s, res->ai_addr, res->ai_addrlen);
232 /* this "if" clause is to prevent print warning twice */
234 if (getnameinfo(res->ai_addr, res->ai_addrlen,
235 hbuf, sizeof(hbuf), NULL, 0,
237 strlcpy(hbuf, "?", sizeof(hbuf));
238 warn("connect to address %s", hbuf);
246 /* finally we got one */
255 memcpy(&hisctladdr.si_su, res->ai_addr, res->ai_addrlen);
256 hisctladdr.su_len = res->ai_addrlen;
260 len = hisctladdr.su_len;
261 if (getsockname(s, (struct sockaddr *)&myctladdr.si_su, &len) == -1) {
266 myctladdr.su_len = len;
268 #ifdef IPTOS_LOWDELAY
269 if (hisctladdr.su_family == AF_INET) {
270 int tos = IPTOS_LOWDELAY;
271 if (setsockopt(s, IPPROTO_IP, IP_TOS,
272 (void *)&tos, sizeof(tos)) == -1) {
273 DWARN("setsockopt %s (ignored)",
278 cin = fdopen(s, "r");
279 cout = fdopen(s, "w");
280 if (cin == NULL || cout == NULL) {
281 warnx("fdopen failed.");
290 fprintf(ttyout, "Connected to %s.\n", hostname);
291 if (getreply(0) > 2) { /* read startup message from server */
300 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE,
301 (void *)&on, sizeof(on)) == -1) {
302 DWARN("setsockopt %s (ignored)", "SO_OOBINLINE");
312 cmdabort(int notused)
319 write(fileno(ttyout), "\n", 1);
322 siglongjmp(ptabort, 1);
327 cmdtimeout(int notused)
333 write(fileno(ttyout), "\n", 1);
336 siglongjmp(ptabort, 1);
342 command(const char *fmt, ...)
350 fputs("---> ", ttyout);
352 if (strncmp("PASS ", fmt, 5) == 0)
353 fputs("PASS XXXX", ttyout);
354 else if (strncmp("ACCT ", fmt, 5) == 0)
355 fputs("ACCT XXXX", ttyout);
357 vfprintf(ttyout, fmt, ap);
363 warnx("No control connection for command.");
370 oldsigint = xsignal(SIGINT, cmdabort);
373 vfprintf(cout, fmt, ap);
378 r = getreply(!strcmp(fmt, "QUIT"));
379 if (abrtflag && oldsigint != SIG_IGN)
380 (*oldsigint)(SIGINT);
381 (void)xsignal(SIGINT, oldsigint);
385 static const char *m421[] = {
386 "remote server timed out. Connection closed",
387 "user interrupt. Connection closed",
388 "remote server has closed connection",
392 getreply(int expecteof)
394 char current_line[BUFSIZ]; /* last line of previous reply */
397 int originalcode = 0, continuation = 0;
398 sigfunc oldsigint, oldsigalrm;
400 char *cp, *pt = pasv;
405 oldsigint = xsignal(SIGINT, cmdabort);
406 oldsigalrm = xsignal(SIGALRM, cmdtimeout);
408 for (line = 0 ;; line++) {
411 while (alarmtimer(quit_time ? quit_time : 60),
412 ((c = getc(cin)) != '\n')) {
413 if (c == IAC) { /* handle telnet commands */
414 switch (c = getc(cin)) {
418 fprintf(cout, "%c%c%c", IAC, DONT, c);
424 fprintf(cout, "%c%c%c", IAC, WONT, c);
435 * these will get trashed by pswitch()
438 int reply_timeoutflag = timeoutflag;
439 int reply_abrtflag = abrtflag;
442 if (expecteof && feof(cin)) {
443 (void)xsignal(SIGINT, oldsigint);
444 (void)xsignal(SIGALRM, oldsigalrm);
452 if (reply_timeoutflag)
454 else if (reply_abrtflag)
458 (void)fprintf(ttyout,
459 "421 Service not available, %s.\n", m421[midx]);
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 = ftp_poll(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 */
619 fin = NULL; /* XXX gcc4 */
627 oprogress = progress;
628 if (verbose && printnames) {
630 fprintf(ttyout, "local: %s ", local);
632 fprintf(ttyout, "remote: %s\n", remote);
635 proxtrans(cmd, local, remote);
644 if (sigsetjmp(xferabort, 1)) {
650 (void)xsignal(SIGQUIT, psummary);
651 oldintr = xsignal(SIGINT, abortxfer);
652 if (strcmp(local, "-") == 0) {
655 } else if (*local == '|') {
656 oldintp = xsignal(SIGPIPE, SIG_IGN);
657 fin = popen(local + 1, "r");
659 warn("%s", local + 1);
666 fin = fopen(local, "r");
668 warn("local: %s", local);
673 if (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode)) {
674 fprintf(ttyout, "%s: not a plain file.\n", local);
678 filesize = st.st_size;
684 if (sigsetjmp(xferabort, 1))
688 (strcmp(cmd, "STOR") == 0 || strcmp(cmd, "APPE") == 0)) {
694 rc = fseeko(fin, restart_point, SEEK_SET);
698 rc = lseek(fileno(fin), restart_point, SEEK_SET);
702 warn("local: %s", local);
705 if (command("REST " LLF, (LLT)restart_point) != CONTINUE)
710 if (command("%s %s", cmd, remote) != PRELIM)
713 if (command("%s", cmd) != PRELIM)
717 dout = dataconn(lmode);
721 if (sndbuf_size > bufsize) {
724 bufsize = sndbuf_size;
725 buf = ftp_malloc(bufsize);
729 oldintp = xsignal(SIGPIPE, SIG_IGN);
735 if (rate_put) { /* rate limited */
737 struct timeval then, now, td;
740 (void)gettimeofday(&then, NULL);
744 if ((c = read(fileno(fin), buf,
745 MIN(bufsize, bufrem))) <= 0)
749 for (bufp = buf; c > 0;
751 if ((d = write(fileno(dout),
757 (!progress || filesize < 0) ) {
758 while (bytes >= hashbytes) {
759 (void)putc('#', ttyout);
762 (void)fflush(ttyout);
766 (void)gettimeofday(&now, NULL);
767 timersub(&now, &then, &td);
770 usleep(1000000 - td.tv_usec);
773 } else { /* simpler/faster; no rate limit */
776 if ((c = read(fileno(fin), buf, bufsize)) <= 0)
779 for (bufp = buf; c > 0; c -= d, bufp += d)
780 if ((d = write(fileno(dout), bufp, c))
785 if (hash && (!progress || filesize < 0) ) {
786 while (bytes >= hashbytes) {
787 (void)putc('#', ttyout);
790 (void)fflush(ttyout);
795 if (hash && (!progress || filesize < 0) && bytes > 0) {
797 (void)putc('#', ttyout);
798 (void)putc('\n', ttyout);
801 warn("local: %s", local);
810 while ((c = getc(fin)) != EOF) {
812 while (hash && (!progress || filesize < 0) &&
813 (bytes >= hashbytes)) {
814 (void)putc('#', ttyout);
815 (void)fflush(ttyout);
820 (void)putc('\r', dout);
825 #if 0 /* this violates RFC */
827 (void)putc('\0', dout);
832 if (hash && (!progress || filesize < 0)) {
833 if (bytes < hashbytes)
834 (void)putc('#', ttyout);
835 (void)putc('\n', ttyout);
838 warn("local: %s", local);
848 if (closefunc != NULL) {
860 (void)xsignal(SIGINT, oldintr);
881 (void)xsignal(SIGINT, oldintr);
883 (void)xsignal(SIGPIPE, oldintp);
888 if (closefunc != NULL && fin != NULL)
892 progress = oprogress;
898 recvrequest(const char *cmd, const char *local, const char *remote,
899 const char *lmode, int printnames, int ignorespecial)
902 int (*closefunc)(FILE *);
903 sigfunc oldintr, oldintp;
905 volatile int is_retr, tcrflag, bare_lfs;
906 static size_t bufsize;
908 volatile off_t hashbytes;
911 struct timeval tval[2];
915 #ifdef __GNUC__ /* to shut up gcc warnings */
927 direction = "received";
931 oprogress = progress;
932 opreserve = preserve;
933 is_retr = (strcmp(cmd, "RETR") == 0);
934 if (is_retr && verbose && printnames) {
935 if (ignorespecial || *local != '-')
936 fprintf(ttyout, "local: %s ", local);
938 fprintf(ttyout, "remote: %s\n", remote);
940 if (proxy && is_retr) {
941 proxtrans(cmd, local, remote);
947 tcrflag = !crflag && is_retr;
948 if (sigsetjmp(xferabort, 1)) {
954 (void)xsignal(SIGQUIT, psummary);
955 oldintr = xsignal(SIGINT, abortxfer);
956 if (ignorespecial || (strcmp(local, "-") && *local != '|')) {
957 if (access(local, W_OK) < 0) {
958 char *dir = strrchr(local, '/');
960 if (errno != ENOENT && errno != EACCES) {
961 warn("local: %s", local);
967 d = access(dir == local ? "/" :
968 dir ? local : ".", W_OK);
972 warn("local: %s", local);
976 if (!runique && errno == EACCES &&
977 chmod(local, (S_IRUSR|S_IWUSR)) < 0) {
978 warn("local: %s", local);
982 if (runique && errno == EACCES &&
983 (local = gunique(local)) == NULL) {
988 else if (runique && (local = gunique(local)) == NULL) {
994 if (curtype != TYPE_A)
995 changetype(TYPE_A, 0);
999 filesize = remotesize(remote, 0);
1000 if (code == 421 || code == -1)
1007 if (sigsetjmp(xferabort, 1))
1009 if (is_retr && restart_point &&
1010 command("REST " LLF, (LLT) restart_point) != CONTINUE)
1012 if (! EMPTYSTRING(remote)) {
1013 if (command("%s %s", cmd, remote) != PRELIM)
1016 if (command("%s", cmd) != PRELIM)
1019 din = dataconn("r");
1022 if (!ignorespecial && strcmp(local, "-") == 0) {
1026 } else if (!ignorespecial && *local == '|') {
1027 oldintp = xsignal(SIGPIPE, SIG_IGN);
1028 fout = popen(local + 1, "w");
1030 warn("%s", local+1);
1037 fout = fopen(local, lmode);
1039 warn("local: %s", local);
1045 if (fstat(fileno(fout), &st) != -1 && !S_ISREG(st.st_mode)) {
1049 if (rcvbuf_size > bufsize) {
1052 bufsize = rcvbuf_size;
1053 buf = ftp_malloc(bufsize);
1062 if (is_retr && restart_point &&
1063 lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1064 warn("local: %s", local);
1067 if (rate_get) { /* rate limiting */
1069 struct timeval then, now, td;
1072 (void)gettimeofday(&then, NULL);
1074 for (bufrem = rate_get; bufrem > 0; ) {
1075 if ((c = read(fileno(din), buf,
1076 MIN(bufsize, bufrem))) <= 0)
1080 if ((d = write(fileno(fout), buf, c))
1084 (!progress || filesize < 0)) {
1085 while (bytes >= hashbytes) {
1086 (void)putc('#', ttyout);
1089 (void)fflush(ttyout);
1092 /* sleep until time is up */
1094 (void)gettimeofday(&now, NULL);
1095 timersub(&now, &then, &td);
1098 usleep(1000000 - td.tv_usec);
1101 } else { /* faster code (no limiting) */
1104 if ((c = read(fileno(din), buf, bufsize)) <= 0)
1107 if ((d = write(fileno(fout), buf, c)) != c)
1109 if (hash && (!progress || filesize < 0)) {
1110 while (bytes >= hashbytes) {
1111 (void)putc('#', ttyout);
1114 (void)fflush(ttyout);
1119 if (hash && (!progress || filesize < 0) && bytes > 0) {
1121 (void)putc('#', ttyout);
1122 (void)putc('\n', ttyout);
1131 warn("local: %s", local);
1133 warnx("%s: short write", local);
1138 if (is_retr && restart_point) {
1142 if (fseeko(fout, (off_t)0, SEEK_SET) < 0)
1144 for (i = 0; i++ < restart_point;) {
1145 if ((ch = getc(fout)) == EOF)
1150 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1152 warn("local: %s", local);
1156 while ((c = getc(din)) != EOF) {
1160 while (hash && (!progress || filesize < 0) &&
1161 (bytes >= hashbytes)) {
1162 (void)putc('#', ttyout);
1163 (void)fflush(ttyout);
1167 if ((c = getc(din)) != '\n' || tcrflag) {
1170 (void)putc('\r', fout);
1179 (void)putc(c, fout);
1184 if (hash && (!progress || filesize < 0)) {
1185 if (bytes < hashbytes)
1186 (void)putc('#', ttyout);
1187 (void)putc('\n', ttyout);
1195 warn("local: %s", local);
1200 if (closefunc != NULL) {
1209 "WARNING! %d bare linefeeds received in ASCII mode.\n",
1211 fputs("File may not have transferred correctly.\n", ttyout);
1213 if (bytes >= 0 && is_retr) {
1216 if (preserve && (closefunc == fclose)) {
1217 mtime = remotemodtime(remote, 0);
1219 (void)gettimeofday(&tval[0], NULL);
1220 tval[1].tv_sec = mtime;
1221 tval[1].tv_usec = 0;
1222 if (utimes(local, tval) == -1) {
1224 "Can't change modification time on %s to %s",
1225 local, asctime(localtime(&mtime)));
1234 * abort using RFC 959 recommended IP,SYNC sequence
1236 if (! sigsetjmp(xferabort, 1)) {
1237 /* this is the first call */
1238 (void)xsignal(SIGINT, abort_squared);
1251 (void)xsignal(SIGINT, oldintr);
1253 (void)xsignal(SIGPIPE, oldintp);
1258 if (closefunc != NULL && fout != NULL)
1262 progress = oprogress;
1263 preserve = opreserve;
1268 * Need to start a listen on the data channel before we send the command,
1269 * otherwise the server's connect may fail.
1275 int result, tmpno = 0;
1278 unsigned int addr[16], port[2];
1279 unsigned int af, hal, pal;
1281 char *pasvcmd = NULL;
1285 if (myctladdr.su_family == AF_INET6 && ftp_debug &&
1286 (IN6_IS_ADDR_LINKLOCAL(&myctladdr.si_su.su_sin6.sin6_addr) ||
1287 IN6_IS_ADDR_SITELOCAL(&myctladdr.si_su.su_sin6.sin6_addr))) {
1288 warnx("use of scoped address can be troublesome");
1294 data_addr = myctladdr;
1295 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1300 if ((options & SO_DEBUG) &&
1301 setsockopt(data, SOL_SOCKET, SO_DEBUG,
1302 (void *)&on, sizeof(on)) == -1) {
1303 DWARN("setsockopt %s (ignored)", "SO_DEBUG");
1305 result = COMPLETE + 1;
1306 switch (data_addr.su_family) {
1308 if (epsv4 && !epsv4bad) {
1310 result = command("EPSV");
1314 * this code is to be friendly with broken
1317 if (code / 10 == 22 && code != 229) {
1319 "wrong server: return code must be 229\n",
1321 result = COMPLETE + 1;
1323 if (result != COMPLETE) {
1325 DPRINTF("disabling epsv4 for this "
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 (ftp_connect(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) {
1538 DWARN("setsockopt %s (ignored)",
1539 "IPTOS_THROUGHPUT");
1547 data_addr = myctladdr;
1549 data_addr.su_port = 0; /* let system pick one */
1552 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1560 if (setsockopt(data, SOL_SOCKET, SO_REUSEADDR,
1561 (void *)&on, sizeof(on)) == -1) {
1562 warn("setsockopt %s", "SO_REUSEADDR");
1565 if (bind(data, (struct sockaddr *)&data_addr.si_su,
1566 data_addr.su_len) < 0) {
1570 if ((options & SO_DEBUG) &&
1571 setsockopt(data, SOL_SOCKET, SO_DEBUG,
1572 (void *)&on, sizeof(on)) == -1) {
1573 DWARN("setsockopt %s (ignored)", "SO_DEBUG");
1575 len = sizeof(data_addr.si_su);
1576 memset((char *)&data_addr, 0, sizeof (data_addr));
1577 if (getsockname(data, (struct sockaddr *)&data_addr.si_su, &len) == -1) {
1578 warn("getsockname");
1581 data_addr.su_len = len;
1582 if (ftp_listen(data, 1) < 0)
1586 char hname[NI_MAXHOST], sname[NI_MAXSERV];
1588 struct sockinet tmp;
1590 switch (data_addr.su_family) {
1592 if (!epsv4 || epsv4bad) {
1593 result = COMPLETE + 1;
1600 af = (data_addr.su_family == AF_INET) ? 1 : 2;
1603 if (tmp.su_family == AF_INET6)
1604 tmp.si_su.su_sin6.sin6_scope_id = 0;
1606 if (getnameinfo((struct sockaddr *)&tmp.si_su,
1607 tmp.su_len, hname, sizeof(hname), sname,
1608 sizeof(sname), NI_NUMERICHOST | NI_NUMERICSERV)) {
1611 result = command("EPRT |%d|%s|%s|", af, hname,
1615 if (result != COMPLETE) {
1617 DPRINTF("disabling epsv4 for this "
1623 result = COMPLETE + 1;
1626 if (result == COMPLETE)
1629 switch (data_addr.su_family) {
1631 a = (char *)&data_addr.si_su.su_sin.sin_addr;
1632 p = (char *)&data_addr.su_port;
1633 result = command("PORT %d,%d,%d,%d,%d,%d",
1634 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
1635 UC(p[0]), UC(p[1]));
1639 a = (char *)&data_addr.si_su.su_sin6.sin6_addr;
1640 p = (char *)&data_addr.su_port;
1642 "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
1644 UC(a[0]),UC(a[1]),UC(a[2]),UC(a[3]),
1645 UC(a[4]),UC(a[5]),UC(a[6]),UC(a[7]),
1646 UC(a[8]),UC(a[9]),UC(a[10]),UC(a[11]),
1647 UC(a[12]),UC(a[13]),UC(a[14]),UC(a[15]),
1648 2, UC(p[0]), UC(p[1]));
1652 result = COMPLETE + 1; /* xxx */
1658 if (result == ERROR && sendport == -1) {
1663 return (result != COMPLETE);
1667 #ifdef IPTOS_THROUGHPUT
1668 if (data_addr.su_family == AF_INET) {
1669 on = IPTOS_THROUGHPUT;
1670 if (setsockopt(data, IPPROTO_IP, IP_TOS,
1671 (void *)&on, sizeof(on)) == -1)
1672 DWARN("setsockopt %s (ignored)", "IPTOS_THROUGHPUT");
1685 dataconn(const char *lmode)
1687 struct sockinet from;
1688 int s, flags, rv, timeout;
1689 struct timeval endtime, now, td;
1690 struct pollfd pfd[1];
1693 if (passivemode) /* passive data connection */
1694 return (fdopen(data, lmode));
1696 /* active mode data connection */
1698 if ((flags = fcntl(data, F_GETFL, 0)) == -1)
1699 goto dataconn_failed; /* get current socket flags */
1700 if (fcntl(data, F_SETFL, flags | O_NONBLOCK) == -1)
1701 goto dataconn_failed; /* set non-blocking connect */
1703 /* NOTE: we now must restore socket flags on successful exit */
1705 /* limit time waiting on listening socket */
1707 pfd[0].events = POLLIN;
1708 (void)gettimeofday(&endtime, NULL); /* determine end time */
1709 endtime.tv_sec += (quit_time > 0) ? quit_time: 60;
1710 /* without -q, default to 60s */
1712 (void)gettimeofday(&now, NULL);
1713 timersub(&endtime, &now, &td);
1714 timeout = td.tv_sec * 1000 + td.tv_usec/1000;
1717 rv = ftp_poll(pfd, 1, timeout);
1718 } while (rv == -1 && errno == EINTR); /* loop until poll ! EINTR */
1720 warn("poll waiting before accept");
1721 goto dataconn_failed;
1724 warn("poll timeout waiting before accept");
1725 goto dataconn_failed;
1728 /* (non-blocking) accept the connection */
1729 fromlen = myctladdr.su_len;
1731 s = accept(data, (struct sockaddr *) &from.si_su, &fromlen);
1732 } while (s == -1 && errno == EINTR); /* loop until accept ! EINTR */
1735 goto dataconn_failed;
1740 if (fcntl(data, F_SETFL, flags) == -1) /* restore socket flags */
1741 goto dataconn_failed;
1743 #ifdef IPTOS_THROUGHPUT
1744 if (from.su_family == AF_INET) {
1745 int tos = IPTOS_THROUGHPUT;
1746 if (setsockopt(s, IPPROTO_IP, IP_TOS,
1747 (void *)&tos, sizeof(tos)) == -1) {
1748 DWARN("setsockopt %s (ignored)", "IPTOS_THROUGHPUT");
1752 return (fdopen(data, lmode));
1761 psabort(int notused)
1775 static struct comvars {
1777 char name[MAXHOSTNAMELEN];
1778 struct sockinet mctl;
1779 struct sockinet hctl;
1792 char mi[MAXPATHLEN];
1793 char mo[MAXPATHLEN];
1794 } proxstruct, tmpstruct;
1795 struct comvars *ip, *op;
1798 oldintr = xsignal(SIGINT, psabort);
1812 ip->connect = connected;
1813 connected = op->connect;
1815 (void)strlcpy(ip->name, hostname, sizeof(ip->name));
1818 hostname = op->name;
1819 ip->hctl = hisctladdr;
1820 hisctladdr = op->hctl;
1821 ip->mctl = myctladdr;
1822 myctladdr = op->mctl;
1829 ip->curtpe = curtype;
1830 curtype = op->curtpe;
1833 ip->sunqe = sunique;
1834 sunique = op->sunqe;
1835 ip->runqe = runique;
1836 runique = op->runqe;
1841 (void)strlcpy(ip->nti, ntin, sizeof(ip->nti));
1842 (void)strlcpy(ntin, op->nti, sizeof(ntin));
1843 (void)strlcpy(ip->nto, ntout, sizeof(ip->nto));
1844 (void)strlcpy(ntout, op->nto, sizeof(ntout));
1845 ip->mapflg = mapflag;
1846 mapflag = op->mapflg;
1847 (void)strlcpy(ip->mi, mapin, sizeof(ip->mi));
1848 (void)strlcpy(mapin, op->mi, sizeof(mapin));
1849 (void)strlcpy(ip->mo, mapout, sizeof(ip->mo));
1850 (void)strlcpy(mapout, op->mo, sizeof(mapout));
1851 (void)xsignal(SIGINT, oldintr);
1859 abortpt(int notused)
1865 write(fileno(ttyout), "\n", 1);
1869 siglongjmp(ptabort, 1);
1873 proxtrans(const char *cmd, const char *local, const char *remote)
1876 int prox_type, nfnd;
1877 volatile int secndflag;
1880 #ifdef __GNUC__ /* to shut up gcc warnings */
1887 if (strcmp(cmd, "RETR"))
1890 cmd2 = runique ? "STOU" : "STOR";
1891 if ((prox_type = type) == 0) {
1892 if (unix_server && unix_proxy)
1897 if (curtype != prox_type)
1898 changetype(prox_type, 1);
1899 if (command("PASV") != COMPLETE) {
1900 fputs("proxy server does not support third party transfers.\n",
1906 fputs("No primary connection.\n", ttyout);
1911 if (curtype != prox_type)
1912 changetype(prox_type, 1);
1913 if (command("PORT %s", pasv) != COMPLETE) {
1917 if (sigsetjmp(ptabort, 1))
1919 oldintr = xsignal(SIGINT, abortpt);
1920 if ((restart_point &&
1921 (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1922 || (command("%s %s", cmd, remote) != PRELIM)) {
1923 (void)xsignal(SIGINT, oldintr);
1930 if ((restart_point &&
1931 (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1932 || (command("%s %s", cmd2, local) != PRELIM))
1938 (void)xsignal(SIGINT, oldintr);
1941 fprintf(ttyout, "local: %s remote: %s\n", local, remote);
1944 if (sigsetjmp(xferabort, 1)) {
1945 (void)xsignal(SIGINT, oldintr);
1948 (void)xsignal(SIGINT, abort_squared);
1950 if (strcmp(cmd, "RETR") && !proxy)
1952 else if (!strcmp(cmd, "RETR") && proxy)
1954 if (!cpend && !secndflag) { /* only here if cmd = "STOR" (proxy=1) */
1955 if (command("%s %s", cmd2, local) != PRELIM) {
1963 (void)xsignal(SIGINT, oldintr);
1969 if (!cpend && !secndflag) { /* only if cmd = "RETR" (proxy=1) */
1970 if (command("%s %s", cmd2, local) != PRELIM) {
1977 (void)xsignal(SIGINT, oldintr);
1985 if ((nfnd = empty(cin, NULL, 10)) <= 0) {
2000 (void)xsignal(SIGINT, oldintr);
2004 reset(int argc, char *argv[])
2008 if (argc == 0 && argv != NULL) {
2009 UPRINTF("usage: %s\n", argv[0]);
2014 if ((nfnd = empty(cin, NULL, 0)) < 0) {
2024 gunique(const char *local)
2026 static char new[MAXPATHLEN];
2027 char *cp = strrchr(local, '/');
2028 int d, count=0, len;
2033 d = access(cp == local ? "/" : cp ? local : ".", W_OK);
2037 warn("local: %s", local);
2040 len = strlcpy(new, local, sizeof(new));
2044 if (++count == 100) {
2045 fputs("runique: can't find unique file name.\n",
2055 if ((d = access(new, F_OK)) < 0)
2059 else if (*(cp - 2) == '.')
2062 *(cp - 2) = *(cp - 2) + 1;
2071 * aborts abort_remote(). lostpeer() is called because if the user is
2072 * too impatient to wait or there's another problem then ftp really
2073 * needs to get back to a known state.
2076 abort_squared(int dummy)
2083 len = strlcpy(msgbuf, "\nremote abort aborted; closing connection.\n",
2085 write(fileno(ttyout), msgbuf, len);
2087 siglongjmp(xferabort, 1);
2091 abort_remote(FILE *din)
2097 warnx("Lost control connection for abort.");
2104 * send IAC in urgent mode instead of DM because 4.3BSD places oob mark
2105 * after urgent byte rather than before as is protocol now
2110 if (send(fileno(cout), buf, 3, MSG_OOB) != 3)
2112 fprintf(cout, "%cABOR\r\n", DM);
2114 if ((nfnd = empty(cin, din, 10)) <= 0) {
2121 if (din && (nfnd & 2)) {
2122 while (read(fileno(din), buf, BUFSIZ) > 0)
2125 if (getreply(0) == ERROR && code == 552) {
2126 /* 552 needed for nic style abort */
2133 ai_unmapped(struct addrinfo *ai)
2136 struct sockaddr_in6 *sin6;
2137 struct sockaddr_in sin;
2140 if (ai->ai_family != AF_INET6)
2142 if (ai->ai_addrlen != sizeof(struct sockaddr_in6) ||
2143 sizeof(sin) > ai->ai_addrlen)
2145 sin6 = (struct sockaddr_in6 *)ai->ai_addr;
2146 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
2149 memset(&sin, 0, sizeof(sin));
2150 sin.sin_family = AF_INET;
2151 len = sizeof(struct sockaddr_in);
2152 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
2153 sizeof(sin.sin_addr));
2154 sin.sin_port = sin6->sin6_port;
2156 ai->ai_family = AF_INET;
2157 #if HAVE_SOCKADDR_SA_LEN
2160 memcpy(ai->ai_addr, &sin, len);
2161 ai->ai_addrlen = len;
2169 fputs("Usage error\n", ttyout);