1 /* $NetBSD: ftp.c,v 1.135 2005/06/29 02:31:19 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.135 2005/06/29 02:31:19 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 = xconnect(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);
386 getreply(int expecteof)
388 char current_line[BUFSIZ]; /* last line of previous reply */
391 int originalcode = 0, continuation = 0;
392 sigfunc oldsigint, oldsigalrm;
394 char *cp, *pt = pasv;
399 oldsigint = xsignal(SIGINT, cmdabort);
400 oldsigalrm = xsignal(SIGALRM, cmdtimeout);
402 for (line = 0 ;; line++) {
405 while (alarmtimer(60),((c = getc(cin)) != '\n')) {
406 if (c == IAC) { /* handle telnet commands */
407 switch (c = getc(cin)) {
411 fprintf(cout, "%c%c%c", IAC, DONT, c);
417 fprintf(cout, "%c%c%c", IAC, WONT, c);
428 * these will get trashed by pswitch()
431 int reply_timeoutflag = timeoutflag;
432 int reply_abrtflag = abrtflag;
435 if (expecteof && feof(cin)) {
436 (void)xsignal(SIGINT, oldsigint);
437 (void)xsignal(SIGALRM, oldsigalrm);
444 if (reply_timeoutflag)
446 "421 Service not available, remote server timed out. Connection closed\n",
448 else if (reply_abrtflag)
450 "421 Service not available, user interrupt. Connection closed.\n",
454 "421 Service not available, remote server has closed connection.\n",
456 (void)fflush(ttyout);
459 (void)xsignal(SIGINT, oldsigint);
460 (void)xsignal(SIGALRM, oldsigalrm);
463 if (c != '\r' && (verbose > 0 ||
464 ((verbose > -1 && n == '5' && dig > 4) &&
465 (((!n && c < '5') || (n && n < '5'))
466 || !retry_connect)))) {
468 (dig == 1 || (dig == 5 && verbose == 0)))
469 fprintf(ttyout, "%s:", hostname);
470 (void)putc(c, ttyout);
472 if (dig < 4 && isdigit(c))
473 code = code * 10 + (c - '0');
474 if (!pflag && (code == 227 || code == 228))
476 else if (!pflag && code == 229)
478 if (dig > 4 && pflag == 1 && isdigit(c))
481 if (c != '\r' && c != ')') {
482 if (pt < &pasv[sizeof(pasv) - 1])
489 if (pflag == 100 && c == '(')
491 if (dig == 4 && c == '-') {
498 if (cp < ¤t_line[sizeof(current_line) - 1])
501 if (verbose > 0 || ((verbose > -1 && n == '5') &&
502 (n < '5' || !retry_connect))) {
503 (void)putc(c, ttyout);
504 (void)fflush (ttyout);
510 (void)strlcpy(reply_string, current_line,
511 sizeof(reply_string));
512 if (line > 0 && code == 0 && reply_callback != NULL)
513 (*reply_callback)(current_line);
514 if (continuation && code != originalcode) {
515 if (originalcode == 0)
522 (void)xsignal(SIGINT, oldsigint);
523 (void)xsignal(SIGALRM, oldsigalrm);
524 if (code == 421 || originalcode == 421)
526 if (abrtflag && oldsigint != cmdabort && oldsigint != SIG_IGN)
527 (*oldsigint)(SIGINT);
528 if (timeoutflag && oldsigalrm != cmdtimeout &&
529 oldsigalrm != SIG_IGN)
530 (*oldsigalrm)(SIGINT);
536 empty(FILE *cin, FILE *din, int sec)
539 struct pollfd pfd[2];
543 pfd[nfd].fd = fileno(cin);
544 pfd[nfd++].events = POLLIN;
548 pfd[nfd].fd = fileno(din);
549 pfd[nfd++].events = POLLIN;
552 if ((nr = xpoll(pfd, nfd, sec * 1000)) <= 0)
558 nr |= (pfd[nfd++].revents & POLLIN) ? 1 : 0;
560 nr |= (pfd[nfd++].revents & POLLIN) ? 2 : 0;
564 sigjmp_buf xferabort;
567 abortxfer(int notused)
576 switch (direction[0]) {
578 strlcpy(msgbuf, "\nreceive", sizeof(msgbuf));
581 strlcpy(msgbuf, "\nsend", sizeof(msgbuf));
584 errx(1, "abortxfer called with unknown direction `%s'",
587 len = strlcat(msgbuf, " aborted. Waiting for remote to finish abort.\n",
589 write(fileno(ttyout), msgbuf, len);
590 siglongjmp(xferabort, 1);
594 sendrequest(const char *cmd, const char *local, const char *remote,
600 int (*closefunc)(FILE *);
601 sigfunc oldintr, oldintp;
602 volatile off_t hashbytes;
604 static size_t bufsize;
608 #ifdef __GNUC__ /* to shut up gcc warnings */
622 oprogress = progress;
623 if (verbose && printnames) {
624 if (local && *local != '-')
625 fprintf(ttyout, "local: %s ", local);
627 fprintf(ttyout, "remote: %s\n", remote);
630 proxtrans(cmd, local, remote);
639 if (sigsetjmp(xferabort, 1)) {
645 (void)xsignal(SIGQUIT, psummary);
646 oldintr = xsignal(SIGINT, abortxfer);
647 if (strcmp(local, "-") == 0) {
650 } else if (*local == '|') {
651 oldintp = xsignal(SIGPIPE, SIG_IGN);
652 fin = popen(local + 1, "r");
654 warn("%s", local + 1);
661 fin = fopen(local, "r");
663 warn("local: %s", local);
668 if (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode)) {
669 fprintf(ttyout, "%s: not a plain file.\n", local);
673 filesize = st.st_size;
679 if (sigsetjmp(xferabort, 1))
683 (strcmp(cmd, "STOR") == 0 || strcmp(cmd, "APPE") == 0)) {
689 rc = fseeko(fin, restart_point, SEEK_SET);
693 rc = lseek(fileno(fin), restart_point, SEEK_SET);
697 warn("local: %s", local);
700 if (command("REST " LLF, (LLT)restart_point) != CONTINUE)
705 if (command("%s %s", cmd, remote) != PRELIM)
708 if (command("%s", cmd) != PRELIM)
712 dout = dataconn(lmode);
716 if (sndbuf_size > bufsize) {
719 bufsize = sndbuf_size;
720 buf = xmalloc(bufsize);
724 oldintp = xsignal(SIGPIPE, SIG_IGN);
730 if (rate_put) { /* rate limited */
732 struct timeval then, now, td;
735 (void)gettimeofday(&then, NULL);
739 if ((c = read(fileno(fin), buf,
740 MIN(bufsize, bufrem))) <= 0)
744 for (bufp = buf; c > 0;
746 if ((d = write(fileno(dout),
752 (!progress || filesize < 0) ) {
753 while (bytes >= hashbytes) {
754 (void)putc('#', ttyout);
757 (void)fflush(ttyout);
761 (void)gettimeofday(&now, NULL);
762 timersub(&now, &then, &td);
765 usleep(1000000 - td.tv_usec);
768 } else { /* simpler/faster; no rate limit */
771 if ((c = read(fileno(fin), buf, bufsize)) <= 0)
774 for (bufp = buf; c > 0; c -= d, bufp += d)
775 if ((d = write(fileno(dout), bufp, c))
780 if (hash && (!progress || filesize < 0) ) {
781 while (bytes >= hashbytes) {
782 (void)putc('#', ttyout);
785 (void)fflush(ttyout);
790 if (hash && (!progress || filesize < 0) && bytes > 0) {
792 (void)putc('#', ttyout);
793 (void)putc('\n', ttyout);
796 warn("local: %s", local);
805 while ((c = getc(fin)) != EOF) {
807 while (hash && (!progress || filesize < 0) &&
808 (bytes >= hashbytes)) {
809 (void)putc('#', ttyout);
810 (void)fflush(ttyout);
815 (void)putc('\r', dout);
820 #if 0 /* this violates RFC */
822 (void)putc('\0', dout);
827 if (hash && (!progress || filesize < 0)) {
828 if (bytes < hashbytes)
829 (void)putc('#', ttyout);
830 (void)putc('\n', ttyout);
833 warn("local: %s", local);
843 if (closefunc != NULL) {
855 (void)xsignal(SIGINT, oldintr);
876 (void)xsignal(SIGINT, oldintr);
878 (void)xsignal(SIGPIPE, oldintp);
883 if (closefunc != NULL && fin != NULL)
887 progress = oprogress;
893 recvrequest(const char *cmd, const char *local, const char *remote,
894 const char *lmode, int printnames, int ignorespecial)
897 int (*closefunc)(FILE *);
898 sigfunc oldintr, oldintp;
900 volatile int is_retr, tcrflag, bare_lfs;
901 static size_t bufsize;
903 volatile off_t hashbytes;
906 struct timeval tval[2];
910 #ifdef __GNUC__ /* to shut up gcc warnings */
922 direction = "received";
926 oprogress = progress;
927 opreserve = preserve;
928 is_retr = (strcmp(cmd, "RETR") == 0);
929 if (is_retr && verbose && printnames) {
930 if (local && (ignorespecial || *local != '-'))
931 fprintf(ttyout, "local: %s ", local);
933 fprintf(ttyout, "remote: %s\n", remote);
935 if (proxy && is_retr) {
936 proxtrans(cmd, local, remote);
942 tcrflag = !crflag && is_retr;
943 if (sigsetjmp(xferabort, 1)) {
949 (void)xsignal(SIGQUIT, psummary);
950 oldintr = xsignal(SIGINT, abortxfer);
951 if (ignorespecial || (strcmp(local, "-") && *local != '|')) {
952 if (access(local, W_OK) < 0) {
953 char *dir = strrchr(local, '/');
955 if (errno != ENOENT && errno != EACCES) {
956 warn("local: %s", local);
962 d = access(dir == local ? "/" :
963 dir ? local : ".", W_OK);
967 warn("local: %s", local);
971 if (!runique && errno == EACCES &&
972 chmod(local, (S_IRUSR|S_IWUSR)) < 0) {
973 warn("local: %s", local);
977 if (runique && errno == EACCES &&
978 (local = gunique(local)) == NULL) {
983 else if (runique && (local = gunique(local)) == NULL) {
989 if (curtype != TYPE_A)
990 changetype(TYPE_A, 0);
994 filesize = remotesize(remote, 0);
995 if (code == 421 || code == -1)
1002 if (sigsetjmp(xferabort, 1))
1004 if (is_retr && restart_point &&
1005 command("REST " LLF, (LLT) restart_point) != CONTINUE)
1007 if (! EMPTYSTRING(remote)) {
1008 if (command("%s %s", cmd, remote) != PRELIM)
1011 if (command("%s", cmd) != PRELIM)
1014 din = dataconn("r");
1017 if (!ignorespecial && strcmp(local, "-") == 0) {
1021 } else if (!ignorespecial && *local == '|') {
1022 oldintp = xsignal(SIGPIPE, SIG_IGN);
1023 fout = popen(local + 1, "w");
1025 warn("%s", local+1);
1032 fout = fopen(local, lmode);
1034 warn("local: %s", local);
1040 if (fstat(fileno(fout), &st) != -1 && !S_ISREG(st.st_mode)) {
1044 if (rcvbuf_size > bufsize) {
1047 bufsize = rcvbuf_size;
1048 buf = xmalloc(bufsize);
1057 if (is_retr && restart_point &&
1058 lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1059 warn("local: %s", local);
1062 if (rate_get) { /* rate limiting */
1064 struct timeval then, now, td;
1067 (void)gettimeofday(&then, NULL);
1069 for (bufrem = rate_get; bufrem > 0; ) {
1070 if ((c = read(fileno(din), buf,
1071 MIN(bufsize, bufrem))) <= 0)
1075 if ((d = write(fileno(fout), buf, c))
1079 (!progress || filesize < 0)) {
1080 while (bytes >= hashbytes) {
1081 (void)putc('#', ttyout);
1084 (void)fflush(ttyout);
1087 /* sleep until time is up */
1089 (void)gettimeofday(&now, NULL);
1090 timersub(&now, &then, &td);
1093 usleep(1000000 - td.tv_usec);
1096 } else { /* faster code (no limiting) */
1099 if ((c = read(fileno(din), buf, bufsize)) <= 0)
1102 if ((d = write(fileno(fout), buf, c)) != c)
1104 if (hash && (!progress || filesize < 0)) {
1105 while (bytes >= hashbytes) {
1106 (void)putc('#', ttyout);
1109 (void)fflush(ttyout);
1114 if (hash && (!progress || filesize < 0) && bytes > 0) {
1116 (void)putc('#', ttyout);
1117 (void)putc('\n', ttyout);
1126 warn("local: %s", local);
1128 warnx("%s: short write", local);
1133 if (is_retr && restart_point) {
1137 if (fseeko(fout, (off_t)0, SEEK_SET) < 0)
1139 for (i = 0; i++ < restart_point;) {
1140 if ((ch = getc(fout)) == EOF)
1145 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1147 warn("local: %s", local);
1151 while ((c = getc(din)) != EOF) {
1155 while (hash && (!progress || filesize < 0) &&
1156 (bytes >= hashbytes)) {
1157 (void)putc('#', ttyout);
1158 (void)fflush(ttyout);
1162 if ((c = getc(din)) != '\n' || tcrflag) {
1165 (void)putc('\r', fout);
1174 (void)putc(c, fout);
1179 if (hash && (!progress || filesize < 0)) {
1180 if (bytes < hashbytes)
1181 (void)putc('#', ttyout);
1182 (void)putc('\n', ttyout);
1190 warn("local: %s", local);
1195 if (closefunc != NULL) {
1204 "WARNING! %d bare linefeeds received in ASCII mode.\n",
1206 fputs("File may not have transferred correctly.\n", ttyout);
1208 if (bytes >= 0 && is_retr) {
1211 if (preserve && (closefunc == fclose)) {
1212 mtime = remotemodtime(remote, 0);
1214 (void)gettimeofday(&tval[0], NULL);
1215 tval[1].tv_sec = mtime;
1216 tval[1].tv_usec = 0;
1217 if (utimes(local, tval) == -1) {
1219 "Can't change modification time on %s to %s",
1220 local, asctime(localtime(&mtime)));
1229 * abort using RFC 959 recommended IP,SYNC sequence
1231 if (! sigsetjmp(xferabort, 1)) {
1232 /* this is the first call */
1233 (void)xsignal(SIGINT, abort_squared);
1246 (void)xsignal(SIGINT, oldintr);
1248 (void)xsignal(SIGPIPE, oldintp);
1253 if (closefunc != NULL && fout != NULL)
1257 progress = oprogress;
1258 preserve = opreserve;
1263 * Need to start a listen on the data channel before we send the command,
1264 * otherwise the server's connect may fail.
1270 int result, tmpno = 0;
1273 unsigned int addr[16], port[2];
1274 unsigned int af, hal, pal;
1276 char *pasvcmd = NULL;
1280 if (myctladdr.su_family == AF_INET6 && debug &&
1281 (IN6_IS_ADDR_LINKLOCAL(&myctladdr.si_su.su_sin6.sin6_addr) ||
1282 IN6_IS_ADDR_SITELOCAL(&myctladdr.si_su.su_sin6.sin6_addr))) {
1283 warnx("use of scoped address can be troublesome");
1289 data_addr = myctladdr;
1290 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1295 if ((options & SO_DEBUG) &&
1296 setsockopt(data, SOL_SOCKET, SO_DEBUG,
1297 (void *)&on, sizeof(on)) == -1) {
1298 DWARN("setsockopt %s (ignored)", "SO_DEBUG");
1300 result = COMPLETE + 1;
1301 switch (data_addr.su_family) {
1303 if (epsv4 && !epsv4bad) {
1305 result = command("EPSV");
1309 * this code is to be friendly with broken
1312 if (code / 10 == 22 && code != 229) {
1314 "wrong server: return code must be 229\n",
1316 result = COMPLETE + 1;
1318 if (result != COMPLETE) {
1320 DPRINTF("disabling epsv4 for this "
1324 if (result != COMPLETE) {
1326 result = command("PASV");
1334 result = command("EPSV");
1337 /* this code is to be friendly with broken BSDI ftpd */
1338 if (code / 10 == 22 && code != 229) {
1340 "wrong server: return code must be 229\n",
1342 result = COMPLETE + 1;
1344 if (result != COMPLETE) {
1346 result = command("LPSV");
1353 result = COMPLETE + 1;
1356 if (result != COMPLETE) {
1357 if (activefallback) {
1366 fputs("Passive mode refused.\n", ttyout);
1370 #define pack2(var, off) \
1371 (((var[(off) + 0] & 0xff) << 8) | ((var[(off) + 1] & 0xff) << 0))
1372 #define pack4(var, off) \
1373 (((var[(off) + 0] & 0xff) << 24) | ((var[(off) + 1] & 0xff) << 16) | \
1374 ((var[(off) + 2] & 0xff) << 8) | ((var[(off) + 3] & 0xff) << 0))
1375 #define UC(b) (((int)b)&0xff)
1378 * What we've got at this point is a string of comma separated
1379 * one-byte unsigned integer values, separated by commas.
1381 if (strcmp(pasvcmd, "PASV") == 0) {
1382 if (data_addr.su_family != AF_INET) {
1384 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1388 if (code / 10 == 22 && code != 227) {
1389 fputs("wrong server: return code must be 227\n",
1394 error = sscanf(pasv, "%u,%u,%u,%u,%u,%u",
1395 &addr[0], &addr[1], &addr[2], &addr[3],
1396 &port[0], &port[1]);
1399 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1404 memset(&data_addr, 0, sizeof(data_addr));
1405 data_addr.su_family = AF_INET;
1406 data_addr.su_len = sizeof(struct sockaddr_in);
1407 data_addr.si_su.su_sin.sin_addr.s_addr =
1408 htonl(pack4(addr, 0));
1409 data_addr.su_port = htons(pack2(port, 0));
1410 } else if (strcmp(pasvcmd, "LPSV") == 0) {
1411 if (code / 10 == 22 && code != 228) {
1412 fputs("wrong server: return code must be 228\n",
1417 switch (data_addr.su_family) {
1419 error = sscanf(pasv,
1420 "%u,%u,%u,%u,%u,%u,%u,%u,%u",
1422 &addr[0], &addr[1], &addr[2], &addr[3],
1423 &pal, &port[0], &port[1]);
1426 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1430 if (af != 4 || hal != 4 || pal != 2) {
1432 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1438 memset(&data_addr, 0, sizeof(data_addr));
1439 data_addr.su_family = AF_INET;
1440 data_addr.su_len = sizeof(struct sockaddr_in);
1441 data_addr.si_su.su_sin.sin_addr.s_addr =
1442 htonl(pack4(addr, 0));
1443 data_addr.su_port = htons(pack2(port, 0));
1447 error = sscanf(pasv,
1448 "%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u",
1450 &addr[0], &addr[1], &addr[2], &addr[3],
1451 &addr[4], &addr[5], &addr[6], &addr[7],
1452 &addr[8], &addr[9], &addr[10],
1453 &addr[11], &addr[12], &addr[13],
1454 &addr[14], &addr[15],
1455 &pal, &port[0], &port[1]);
1458 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1462 if (af != 6 || hal != 16 || pal != 2) {
1464 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1470 memset(&data_addr, 0, sizeof(data_addr));
1471 data_addr.su_family = AF_INET6;
1472 data_addr.su_len = sizeof(struct sockaddr_in6);
1475 for (i = 0; i < sizeof(struct in6_addr); i++) {
1476 data_addr.si_su.su_sin6.sin6_addr.s6_addr[i] =
1480 data_addr.su_port = htons(pack2(port, 0));
1486 } else if (strcmp(pasvcmd, "EPSV") == 0) {
1490 if (code / 10 == 22 && code != 229) {
1491 fputs("wrong server: return code must be 229\n",
1496 if (sscanf(pasv, "%c%c%c%d%c", &delim[0],
1497 &delim[1], &delim[2], &port[1],
1499 fputs("parse error!\n", ttyout);
1503 if (delim[0] != delim[1] || delim[0] != delim[2]
1504 || delim[0] != delim[3]) {
1505 fputs("parse error!\n", ttyout);
1509 data_addr = hisctladdr;
1510 data_addr.su_port = htons(port[1]);
1514 while (xconnect(data, (struct sockaddr *)&data_addr.si_su,
1515 data_addr.su_len) < 0) {
1516 if (activefallback) {
1525 warn("connect for data channel");
1528 #ifdef IPTOS_THROUGHPUT
1529 if (data_addr.su_family == AF_INET) {
1530 on = IPTOS_THROUGHPUT;
1531 if (setsockopt(data, IPPROTO_IP, IP_TOS,
1532 (void *)&on, sizeof(on)) == -1) {
1533 DWARN("setsockopt %s (ignored)",
1534 "IPTOS_THROUGHPUT");
1542 data_addr = myctladdr;
1544 data_addr.su_port = 0; /* let system pick one */
1547 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1555 if (setsockopt(data, SOL_SOCKET, SO_REUSEADDR,
1556 (void *)&on, sizeof(on)) == -1) {
1557 warn("setsockopt %s", "SO_REUSEADDR");
1560 if (bind(data, (struct sockaddr *)&data_addr.si_su,
1561 data_addr.su_len) < 0) {
1565 if ((options & SO_DEBUG) &&
1566 setsockopt(data, SOL_SOCKET, SO_DEBUG,
1567 (void *)&on, sizeof(on)) == -1) {
1568 DWARN("setsockopt %s (ignored)", "SO_DEBUG");
1570 len = sizeof(data_addr.si_su);
1571 memset((char *)&data_addr, 0, sizeof (data_addr));
1572 if (getsockname(data, (struct sockaddr *)&data_addr.si_su, &len) == -1) {
1573 warn("getsockname");
1576 data_addr.su_len = len;
1577 if (xlisten(data, 1) < 0)
1581 char hname[NI_MAXHOST], sname[NI_MAXSERV];
1583 struct sockinet tmp;
1585 switch (data_addr.su_family) {
1587 if (!epsv4 || epsv4bad) {
1588 result = COMPLETE + 1;
1595 af = (data_addr.su_family == AF_INET) ? 1 : 2;
1598 if (tmp.su_family == AF_INET6)
1599 tmp.si_su.su_sin6.sin6_scope_id = 0;
1601 if (getnameinfo((struct sockaddr *)&tmp.si_su,
1602 tmp.su_len, hname, sizeof(hname), sname,
1603 sizeof(sname), NI_NUMERICHOST | NI_NUMERICSERV)) {
1606 result = command("EPRT |%d|%s|%s|", af, hname,
1610 if (result != COMPLETE) {
1612 DPRINTF("disabling epsv4 for this "
1618 result = COMPLETE + 1;
1621 if (result == COMPLETE)
1624 switch (data_addr.su_family) {
1626 a = (char *)&data_addr.si_su.su_sin.sin_addr;
1627 p = (char *)&data_addr.su_port;
1628 result = command("PORT %d,%d,%d,%d,%d,%d",
1629 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
1630 UC(p[0]), UC(p[1]));
1634 a = (char *)&data_addr.si_su.su_sin6.sin6_addr;
1635 p = (char *)&data_addr.su_port;
1637 "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
1639 UC(a[0]),UC(a[1]),UC(a[2]),UC(a[3]),
1640 UC(a[4]),UC(a[5]),UC(a[6]),UC(a[7]),
1641 UC(a[8]),UC(a[9]),UC(a[10]),UC(a[11]),
1642 UC(a[12]),UC(a[13]),UC(a[14]),UC(a[15]),
1643 2, UC(p[0]), UC(p[1]));
1647 result = COMPLETE + 1; /* xxx */
1653 if (result == ERROR && sendport == -1) {
1658 return (result != COMPLETE);
1662 #ifdef IPTOS_THROUGHPUT
1663 if (data_addr.su_family == AF_INET) {
1664 on = IPTOS_THROUGHPUT;
1665 if (setsockopt(data, IPPROTO_IP, IP_TOS,
1666 (void *)&on, sizeof(on)) == -1)
1667 DWARN("setsockopt %s (ignored)", "IPTOS_THROUGHPUT");
1680 dataconn(const char *lmode)
1682 struct sockinet from;
1683 int s, flags, rv, timeout;
1684 struct timeval endtime, now, td;
1685 struct pollfd pfd[1];
1688 if (passivemode) /* passive data connection */
1689 return (fdopen(data, lmode));
1691 /* active mode data connection */
1693 if ((flags = fcntl(data, F_GETFL, 0)) == -1)
1694 goto dataconn_failed; /* get current socket flags */
1695 if (fcntl(data, F_SETFL, flags | O_NONBLOCK) == -1)
1696 goto dataconn_failed; /* set non-blocking connect */
1698 /* NOTE: we now must restore socket flags on successful exit */
1700 /* limit time waiting on listening socket */
1702 pfd[0].events = POLLIN;
1703 (void)gettimeofday(&endtime, NULL); /* determine end time */
1704 endtime.tv_sec += (quit_time > 0) ? quit_time: 60;
1705 /* without -q, default to 60s */
1707 (void)gettimeofday(&now, NULL);
1708 timersub(&endtime, &now, &td);
1709 timeout = td.tv_sec * 1000 + td.tv_usec/1000;
1712 rv = xpoll(pfd, 1, timeout);
1713 } while (rv == -1 && errno == EINTR); /* loop until poll ! EINTR */
1715 warn("poll waiting before accept");
1716 goto dataconn_failed;
1719 warn("poll timeout waiting before accept");
1720 goto dataconn_failed;
1723 /* (non-blocking) accept the connection */
1724 fromlen = myctladdr.su_len;
1726 s = accept(data, (struct sockaddr *) &from.si_su, &fromlen);
1727 } while (s == -1 && errno == EINTR); /* loop until accept ! EINTR */
1730 goto dataconn_failed;
1735 if (fcntl(data, F_SETFL, flags) == -1) /* restore socket flags */
1736 goto dataconn_failed;
1738 #ifdef IPTOS_THROUGHPUT
1739 if (from.su_family == AF_INET) {
1740 int tos = IPTOS_THROUGHPUT;
1741 if (setsockopt(s, IPPROTO_IP, IP_TOS,
1742 (void *)&tos, sizeof(tos)) == -1) {
1743 DWARN("setsockopt %s (ignored)", "IPTOS_THROUGHPUT");
1747 return (fdopen(data, lmode));
1756 psabort(int notused)
1770 static struct comvars {
1772 char name[MAXHOSTNAMELEN];
1773 struct sockinet mctl;
1774 struct sockinet hctl;
1787 char mi[MAXPATHLEN];
1788 char mo[MAXPATHLEN];
1789 } proxstruct, tmpstruct;
1790 struct comvars *ip, *op;
1793 oldintr = xsignal(SIGINT, psabort);
1807 ip->connect = connected;
1808 connected = op->connect;
1810 (void)strlcpy(ip->name, hostname, sizeof(ip->name));
1813 hostname = op->name;
1814 ip->hctl = hisctladdr;
1815 hisctladdr = op->hctl;
1816 ip->mctl = myctladdr;
1817 myctladdr = op->mctl;
1824 ip->curtpe = curtype;
1825 curtype = op->curtpe;
1828 ip->sunqe = sunique;
1829 sunique = op->sunqe;
1830 ip->runqe = runique;
1831 runique = op->runqe;
1836 (void)strlcpy(ip->nti, ntin, sizeof(ip->nti));
1837 (void)strlcpy(ntin, op->nti, sizeof(ntin));
1838 (void)strlcpy(ip->nto, ntout, sizeof(ip->nto));
1839 (void)strlcpy(ntout, op->nto, sizeof(ntout));
1840 ip->mapflg = mapflag;
1841 mapflag = op->mapflg;
1842 (void)strlcpy(ip->mi, mapin, sizeof(ip->mi));
1843 (void)strlcpy(mapin, op->mi, sizeof(mapin));
1844 (void)strlcpy(ip->mo, mapout, sizeof(ip->mo));
1845 (void)strlcpy(mapout, op->mo, sizeof(mapout));
1846 (void)xsignal(SIGINT, oldintr);
1854 abortpt(int notused)
1860 write(fileno(ttyout), "\n", 1);
1864 siglongjmp(ptabort, 1);
1868 proxtrans(const char *cmd, const char *local, const char *remote)
1871 int prox_type, nfnd;
1872 volatile int secndflag;
1875 #ifdef __GNUC__ /* to shut up gcc warnings */
1882 if (strcmp(cmd, "RETR"))
1885 cmd2 = runique ? "STOU" : "STOR";
1886 if ((prox_type = type) == 0) {
1887 if (unix_server && unix_proxy)
1892 if (curtype != prox_type)
1893 changetype(prox_type, 1);
1894 if (command("PASV") != COMPLETE) {
1895 fputs("proxy server does not support third party transfers.\n",
1901 fputs("No primary connection.\n", ttyout);
1906 if (curtype != prox_type)
1907 changetype(prox_type, 1);
1908 if (command("PORT %s", pasv) != COMPLETE) {
1912 if (sigsetjmp(ptabort, 1))
1914 oldintr = xsignal(SIGINT, abortpt);
1915 if ((restart_point &&
1916 (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1917 || (command("%s %s", cmd, remote) != PRELIM)) {
1918 (void)xsignal(SIGINT, oldintr);
1925 if ((restart_point &&
1926 (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1927 || (command("%s %s", cmd2, local) != PRELIM))
1933 (void)xsignal(SIGINT, oldintr);
1936 fprintf(ttyout, "local: %s remote: %s\n", local, remote);
1939 if (sigsetjmp(xferabort, 1)) {
1940 (void)xsignal(SIGINT, oldintr);
1943 (void)xsignal(SIGINT, abort_squared);
1945 if (strcmp(cmd, "RETR") && !proxy)
1947 else if (!strcmp(cmd, "RETR") && proxy)
1949 if (!cpend && !secndflag) { /* only here if cmd = "STOR" (proxy=1) */
1950 if (command("%s %s", cmd2, local) != PRELIM) {
1958 (void)xsignal(SIGINT, oldintr);
1964 if (!cpend && !secndflag) { /* only if cmd = "RETR" (proxy=1) */
1965 if (command("%s %s", cmd2, local) != PRELIM) {
1972 (void)xsignal(SIGINT, oldintr);
1980 if ((nfnd = empty(cin, NULL, 10)) <= 0) {
1995 (void)xsignal(SIGINT, oldintr);
1999 reset(int argc, char *argv[])
2003 if (argc == 0 && argv != NULL) {
2004 UPRINTF("usage: %s\n", argv[0]);
2009 if ((nfnd = empty(cin, NULL, 0)) < 0) {
2019 gunique(const char *local)
2021 static char new[MAXPATHLEN];
2022 char *cp = strrchr(local, '/');
2023 int d, count=0, len;
2028 d = access(cp == local ? "/" : cp ? local : ".", W_OK);
2032 warn("local: %s", local);
2035 len = strlcpy(new, local, sizeof(new));
2039 if (++count == 100) {
2040 fputs("runique: can't find unique file name.\n",
2050 if ((d = access(new, F_OK)) < 0)
2054 else if (*(cp - 2) == '.')
2057 *(cp - 2) = *(cp - 2) + 1;
2066 * aborts abort_remote(). lostpeer() is called because if the user is
2067 * too impatient to wait or there's another problem then ftp really
2068 * needs to get back to a known state.
2071 abort_squared(int dummy)
2078 len = strlcpy(msgbuf, "\nremote abort aborted; closing connection.\n",
2080 write(fileno(ttyout), msgbuf, len);
2082 siglongjmp(xferabort, 1);
2086 abort_remote(FILE *din)
2092 warnx("Lost control connection for abort.");
2099 * send IAC in urgent mode instead of DM because 4.3BSD places oob mark
2100 * after urgent byte rather than before as is protocol now
2105 if (send(fileno(cout), buf, 3, MSG_OOB) != 3)
2107 fprintf(cout, "%cABOR\r\n", DM);
2109 if ((nfnd = empty(cin, din, 10)) <= 0) {
2116 if (din && (nfnd & 2)) {
2117 while (read(fileno(din), buf, BUFSIZ) > 0)
2120 if (getreply(0) == ERROR && code == 552) {
2121 /* 552 needed for nic style abort */
2128 ai_unmapped(struct addrinfo *ai)
2131 struct sockaddr_in6 *sin6;
2132 struct sockaddr_in sin;
2135 if (ai->ai_family != AF_INET6)
2137 if (ai->ai_addrlen != sizeof(struct sockaddr_in6) ||
2138 sizeof(sin) > ai->ai_addrlen)
2140 sin6 = (struct sockaddr_in6 *)ai->ai_addr;
2141 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
2144 memset(&sin, 0, sizeof(sin));
2145 sin.sin_family = AF_INET;
2146 len = sizeof(struct sockaddr_in);
2147 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
2148 sizeof(sin.sin_addr));
2149 sin.sin_port = sin6->sin6_port;
2151 ai->ai_family = AF_INET;
2152 #if HAVE_SOCKADDR_SA_LEN
2155 memcpy(ai->ai_addr, &sin, len);
2156 ai->ai_addrlen = len;
2164 fputs("Usage error\n", ttyout);