1 /* $NetBSD: ftp.c,v 1.148 2007/04/18 01:50:45 lukem Exp $ */
4 * Copyright (c) 1996-2007 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.148 2007/04/18 01:50:45 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];
174 memset((char *)&hisctladdr, 0, sizeof (hisctladdr));
175 memset((char *)&myctladdr, 0, sizeof (myctladdr));
176 memset(&hints, 0, sizeof(hints));
177 portnum = parseport(port, FTP_PORT);
178 hints.ai_flags = AI_CANONNAME;
179 hints.ai_family = family;
180 hints.ai_socktype = SOCK_STREAM;
181 hints.ai_protocol = 0;
182 error = getaddrinfo(host, NULL, &hints, &res0);
184 warnx("Can't lookup `%s': %s", host,
185 (error == EAI_SYSTEM) ? strerror(errno)
186 : gai_strerror(error));
191 if (res0->ai_canonname)
192 (void)strlcpy(hostnamebuf, res0->ai_canonname,
193 sizeof(hostnamebuf));
195 (void)strlcpy(hostnamebuf, host, sizeof(hostnamebuf));
196 hostname = hostnamebuf;
198 for (res = res0; res; res = res->ai_next) {
200 if (getnameinfo(res->ai_addr, res->ai_addrlen,
201 hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST))
202 strlcpy(hbuf, "?", sizeof(hbuf));
203 if (verbose && res0->ai_next) {
204 /* if we have multiple possibilities */
205 fprintf(ttyout, "Trying %s...\n", hbuf);
207 ((struct sockaddr_in *)res->ai_addr)->sin_port = htons(portnum);
208 s = socket(res->ai_family, SOCK_STREAM, res->ai_protocol);
210 warn("Can't create socket for connection to `%s'",
214 if (ftp_connect(s, res->ai_addr, res->ai_addrlen) < 0) {
220 /* finally we got one */
224 warnx("Can't connect to `%s'", host);
229 memcpy(&hisctladdr.si_su, res->ai_addr, res->ai_addrlen);
230 hisctladdr.su_len = res->ai_addrlen;
234 len = hisctladdr.su_len;
235 if (getsockname(s, (struct sockaddr *)&myctladdr.si_su, &len) == -1) {
236 warn("Can't determine my address of connection to `%s'", host);
240 myctladdr.su_len = len;
242 #ifdef IPTOS_LOWDELAY
243 if (hisctladdr.su_family == AF_INET) {
244 int tos = IPTOS_LOWDELAY;
245 if (setsockopt(s, IPPROTO_IP, IP_TOS,
246 (void *)&tos, sizeof(tos)) == -1) {
247 DWARN("setsockopt %s (ignored)",
252 cin = fdopen(s, "r");
253 cout = fdopen(s, "w");
254 if (cin == NULL || cout == NULL) {
255 warnx("Can't fdopen socket");
264 fprintf(ttyout, "Connected to %s.\n", hostname);
265 if (getreply(0) > 2) { /* read startup message from server */
274 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE,
275 (void *)&on, sizeof(on)) == -1) {
276 DWARN("setsockopt %s (ignored)", "SO_OOBINLINE");
286 cmdabort(int notused)
293 write(fileno(ttyout), "\n", 1);
296 siglongjmp(ptabort, 1);
301 cmdtimeout(int notused)
307 write(fileno(ttyout), "\n", 1);
310 siglongjmp(ptabort, 1);
316 command(const char *fmt, ...)
324 fputs("---> ", ttyout);
326 if (strncmp("PASS ", fmt, 5) == 0)
327 fputs("PASS XXXX", ttyout);
328 else if (strncmp("ACCT ", fmt, 5) == 0)
329 fputs("ACCT XXXX", ttyout);
331 vfprintf(ttyout, fmt, ap);
337 warnx("No control connection for command");
344 oldsigint = xsignal(SIGINT, cmdabort);
347 vfprintf(cout, fmt, ap);
352 r = getreply(!strcmp(fmt, "QUIT"));
353 if (abrtflag && oldsigint != SIG_IGN)
354 (*oldsigint)(SIGINT);
355 (void)xsignal(SIGINT, oldsigint);
359 static const char *m421[] = {
360 "remote server timed out. Connection closed",
361 "user interrupt. Connection closed",
362 "remote server has closed connection",
366 getreply(int expecteof)
368 char current_line[BUFSIZ]; /* last line of previous reply */
371 int originalcode = 0, continuation = 0;
372 sigfunc oldsigint, oldsigalrm;
374 char *cp, *pt = pasv;
379 oldsigint = xsignal(SIGINT, cmdabort);
380 oldsigalrm = xsignal(SIGALRM, cmdtimeout);
382 for (line = 0 ;; line++) {
385 while (alarmtimer(quit_time ? quit_time : 60),
386 ((c = getc(cin)) != '\n')) {
387 if (c == IAC) { /* handle telnet commands */
388 switch (c = getc(cin)) {
392 fprintf(cout, "%c%c%c", IAC, DONT, c);
398 fprintf(cout, "%c%c%c", IAC, WONT, c);
409 * these will get trashed by pswitch()
412 int reply_timeoutflag = timeoutflag;
413 int reply_abrtflag = abrtflag;
416 if (expecteof && feof(cin)) {
417 (void)xsignal(SIGINT, oldsigint);
418 (void)xsignal(SIGALRM, oldsigalrm);
426 if (reply_timeoutflag)
428 else if (reply_abrtflag)
432 (void)fprintf(ttyout,
433 "421 Service not available, %s.\n", m421[midx]);
434 (void)fflush(ttyout);
437 (void)xsignal(SIGINT, oldsigint);
438 (void)xsignal(SIGALRM, oldsigalrm);
441 if (c != '\r' && (verbose > 0 ||
442 ((verbose > -1 && n == '5' && dig > 4) &&
443 (((!n && c < '5') || (n && n < '5'))
444 || !retry_connect)))) {
446 (dig == 1 || (dig == 5 && verbose == 0)))
447 fprintf(ttyout, "%s:", hostname);
448 (void)putc(c, ttyout);
450 if (dig < 4 && isdigit(c))
451 code = code * 10 + (c - '0');
452 if (!pflag && (code == 227 || code == 228))
454 else if (!pflag && code == 229)
456 if (dig > 4 && pflag == 1 && isdigit(c))
459 if (c != '\r' && c != ')') {
460 if (pt < &pasv[sizeof(pasv) - 1])
467 if (pflag == 100 && c == '(')
469 if (dig == 4 && c == '-') {
476 if (cp < ¤t_line[sizeof(current_line) - 1])
479 if (verbose > 0 || ((verbose > -1 && n == '5') &&
480 (n < '5' || !retry_connect))) {
481 (void)putc(c, ttyout);
482 (void)fflush(ttyout);
488 (void)strlcpy(reply_string, current_line,
489 sizeof(reply_string));
490 if (line > 0 && code == 0 && reply_callback != NULL)
491 (*reply_callback)(current_line);
492 if (continuation && code != originalcode) {
493 if (originalcode == 0)
500 (void)xsignal(SIGINT, oldsigint);
501 (void)xsignal(SIGALRM, oldsigalrm);
502 if (code == 421 || originalcode == 421)
504 if (abrtflag && oldsigint != cmdabort && oldsigint != SIG_IGN)
505 (*oldsigint)(SIGINT);
506 if (timeoutflag && oldsigalrm != cmdtimeout &&
507 oldsigalrm != SIG_IGN)
508 (*oldsigalrm)(SIGINT);
514 empty(FILE *cin, FILE *din, int sec)
517 struct pollfd pfd[2];
521 pfd[nfd].fd = fileno(cin);
522 pfd[nfd++].events = POLLIN;
526 pfd[nfd].fd = fileno(din);
527 pfd[nfd++].events = POLLIN;
530 if ((nr = ftp_poll(pfd, nfd, sec * 1000)) <= 0)
536 nr |= (pfd[nfd++].revents & POLLIN) ? 1 : 0;
538 nr |= (pfd[nfd++].revents & POLLIN) ? 2 : 0;
542 sigjmp_buf xferabort;
545 abortxfer(int notused)
554 switch (direction[0]) {
556 strlcpy(msgbuf, "\nreceive", sizeof(msgbuf));
559 strlcpy(msgbuf, "\nsend", sizeof(msgbuf));
562 errx(1, "abortxfer: unknown direction `%s'", direction);
564 len = strlcat(msgbuf, " aborted. Waiting for remote to finish abort.\n",
566 write(fileno(ttyout), msgbuf, len);
567 siglongjmp(xferabort, 1);
571 sendrequest(const char *cmd, const char *local, const char *remote,
578 int (*volatile closefunc)(FILE *);
579 sigfunc volatile oldintr;
580 sigfunc volatile oldintp;
581 off_t volatile hashbytes;
582 char *volatile lmode;
584 static size_t bufsize;
593 oprogress = progress;
594 if (verbose && printnames) {
596 fprintf(ttyout, "local: %s ", local);
598 fprintf(ttyout, "remote: %s\n", remote);
601 proxtrans(cmd, local, remote);
610 if (sigsetjmp(xferabort, 1)) {
616 (void)xsignal(SIGQUIT, psummary);
617 oldintr = xsignal(SIGINT, abortxfer);
618 if (strcmp(local, "-") == 0) {
621 } else if (*local == '|') {
622 oldintp = xsignal(SIGPIPE, SIG_IGN);
623 fin = popen(local + 1, "r");
625 warn("Can't execute `%s'", local + 1);
632 fin = fopen(local, "r");
634 warn("Can't open `%s'", local);
639 if (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode)) {
640 fprintf(ttyout, "%s: not a plain file.\n", local);
644 filesize = st.st_size;
650 if (sigsetjmp(xferabort, 1))
654 (strcmp(cmd, "STOR") == 0 || strcmp(cmd, "APPE") == 0)) {
660 rc = fseeko(fin, restart_point, SEEK_SET);
664 rc = lseek(fileno(fin), restart_point, SEEK_SET);
668 warn("Can't seek to restart `%s'", local);
671 if (command("REST " LLF, (LLT)restart_point) != CONTINUE)
676 if (command("%s %s", cmd, remote) != PRELIM)
679 if (command("%s", cmd) != PRELIM)
683 dout = dataconn(lmode);
687 if (sndbuf_size > bufsize) {
690 bufsize = sndbuf_size;
691 buf = ftp_malloc(bufsize);
695 oldintp = xsignal(SIGPIPE, SIG_IGN);
701 if (rate_put) { /* rate limited */
703 struct timeval then, now, td;
706 (void)gettimeofday(&then, NULL);
710 if ((c = read(fileno(fin), buf,
711 MIN(bufsize, bufrem))) <= 0)
715 for (bufp = buf; c > 0;
717 if ((d = write(fileno(dout),
723 (!progress || filesize < 0) ) {
724 while (bytes >= hashbytes) {
725 (void)putc('#', ttyout);
728 (void)fflush(ttyout);
732 (void)gettimeofday(&now, NULL);
733 timersub(&now, &then, &td);
736 usleep(1000000 - td.tv_usec);
739 } else { /* simpler/faster; no rate limit */
742 if ((c = read(fileno(fin), buf, bufsize)) <= 0)
745 for (bufp = buf; c > 0; c -= d, bufp += d)
746 if ((d = write(fileno(dout), bufp, c))
751 if (hash && (!progress || filesize < 0) ) {
752 while (bytes >= hashbytes) {
753 (void)putc('#', ttyout);
756 (void)fflush(ttyout);
761 if (hash && (!progress || filesize < 0) && bytes > 0) {
763 (void)putc('#', ttyout);
764 (void)putc('\n', ttyout);
767 warn("Reading `%s'", local);
770 warn("Writing to network");
776 while ((c = getc(fin)) != EOF) {
778 while (hash && (!progress || filesize < 0) &&
779 (bytes >= hashbytes)) {
780 (void)putc('#', ttyout);
781 (void)fflush(ttyout);
786 (void)putc('\r', dout);
791 #if 0 /* this violates RFC */
793 (void)putc('\0', dout);
798 if (hash && (!progress || filesize < 0)) {
799 if (bytes < hashbytes)
800 (void)putc('#', ttyout);
801 (void)putc('\n', ttyout);
804 warn("Reading `%s'", local);
807 warn("Writing to network");
814 if (closefunc != NULL) {
826 (void)xsignal(SIGINT, oldintr);
847 (void)xsignal(SIGINT, oldintr);
849 (void)xsignal(SIGPIPE, oldintp);
854 if (closefunc != NULL && fin != NULL)
858 progress = oprogress;
864 recvrequest(const char *cmd, const char *volatile local, const char *remote,
865 const char *lmode, int printnames, int ignorespecial)
869 int (*volatile closefunc)(FILE *);
870 sigfunc volatile oldintr;
871 sigfunc volatile oldintp;
873 int volatile is_retr;
874 int volatile tcrflag;
875 int volatile bare_lfs;
876 static size_t bufsize;
878 off_t volatile hashbytes;
881 struct timeval tval[2];
888 direction = "received";
892 oprogress = progress;
893 opreserve = preserve;
894 is_retr = (strcmp(cmd, "RETR") == 0);
895 if (is_retr && verbose && printnames) {
896 if (ignorespecial || *local != '-')
897 fprintf(ttyout, "local: %s ", local);
899 fprintf(ttyout, "remote: %s\n", remote);
901 if (proxy && is_retr) {
902 proxtrans(cmd, local, remote);
908 tcrflag = !crflag && is_retr;
909 if (sigsetjmp(xferabort, 1)) {
915 (void)xsignal(SIGQUIT, psummary);
916 oldintr = xsignal(SIGINT, abortxfer);
917 if (ignorespecial || (strcmp(local, "-") && *local != '|')) {
918 if (access(local, W_OK) < 0) {
919 char *dir = strrchr(local, '/');
921 if (errno != ENOENT && errno != EACCES) {
922 warn("Can't access `%s'", local);
928 d = access(dir == local ? "/" :
929 dir ? local : ".", W_OK);
933 warn("Can't access `%s'", local);
937 if (!runique && errno == EACCES &&
938 chmod(local, (S_IRUSR|S_IWUSR)) < 0) {
939 warn("Can't chmod `%s'", local);
943 if (runique && errno == EACCES &&
944 (local = gunique(local)) == NULL) {
949 else if (runique && (local = gunique(local)) == NULL) {
955 if (curtype != TYPE_A)
956 changetype(TYPE_A, 0);
960 filesize = remotesize(remote, 0);
961 if (code == 421 || code == -1)
968 if (sigsetjmp(xferabort, 1))
970 if (is_retr && restart_point &&
971 command("REST " LLF, (LLT) restart_point) != CONTINUE)
973 if (! EMPTYSTRING(remote)) {
974 if (command("%s %s", cmd, remote) != PRELIM)
977 if (command("%s", cmd) != PRELIM)
983 if (!ignorespecial && strcmp(local, "-") == 0) {
987 } else if (!ignorespecial && *local == '|') {
988 oldintp = xsignal(SIGPIPE, SIG_IGN);
989 fout = popen(local + 1, "w");
991 warn("Can't execute `%s'", local+1);
998 fout = fopen(local, lmode);
1000 warn("Can't open `%s'", local);
1006 if (fstat(fileno(fout), &st) != -1 && !S_ISREG(st.st_mode)) {
1010 if (rcvbuf_size > bufsize) {
1013 bufsize = rcvbuf_size;
1014 buf = ftp_malloc(bufsize);
1023 if (is_retr && restart_point &&
1024 lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1025 warn("Can't seek to restart `%s'", local);
1028 if (rate_get) { /* rate limiting */
1030 struct timeval then, now, td;
1033 (void)gettimeofday(&then, NULL);
1035 for (bufrem = rate_get; bufrem > 0; ) {
1036 if ((c = read(fileno(din), buf,
1037 MIN(bufsize, bufrem))) <= 0)
1041 if ((d = write(fileno(fout), buf, c))
1045 (!progress || filesize < 0)) {
1046 while (bytes >= hashbytes) {
1047 (void)putc('#', ttyout);
1050 (void)fflush(ttyout);
1053 /* sleep until time is up */
1055 (void)gettimeofday(&now, NULL);
1056 timersub(&now, &then, &td);
1059 usleep(1000000 - td.tv_usec);
1062 } else { /* faster code (no limiting) */
1065 if ((c = read(fileno(din), buf, bufsize)) <= 0)
1068 if ((d = write(fileno(fout), buf, c)) != c)
1070 if (hash && (!progress || filesize < 0)) {
1071 while (bytes >= hashbytes) {
1072 (void)putc('#', ttyout);
1075 (void)fflush(ttyout);
1080 if (hash && (!progress || filesize < 0) && bytes > 0) {
1082 (void)putc('#', ttyout);
1083 (void)putc('\n', ttyout);
1087 warn("Reading from network");
1092 warn("Writing `%s'", local);
1094 warnx("Writing `%s': short write", local);
1099 if (is_retr && restart_point) {
1103 if (fseeko(fout, (off_t)0, SEEK_SET) < 0)
1105 for (i = 0; i++ < restart_point;) {
1106 if ((ch = getc(fout)) == EOF)
1111 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1113 warn("Can't seek to restart `%s'", local);
1117 while ((c = getc(din)) != EOF) {
1121 while (hash && (!progress || filesize < 0) &&
1122 (bytes >= hashbytes)) {
1123 (void)putc('#', ttyout);
1124 (void)fflush(ttyout);
1128 if ((c = getc(din)) != '\n' || tcrflag) {
1131 (void)putc('\r', fout);
1140 (void)putc(c, fout);
1145 if (hash && (!progress || filesize < 0)) {
1146 if (bytes < hashbytes)
1147 (void)putc('#', ttyout);
1148 (void)putc('\n', ttyout);
1152 warn("Reading from network");
1156 warn("Writing `%s'", local);
1161 if (closefunc != NULL) {
1170 "WARNING! %d bare linefeeds received in ASCII mode.\n",
1172 fputs("File may not have transferred correctly.\n", ttyout);
1174 if (bytes >= 0 && is_retr) {
1177 if (preserve && (closefunc == fclose)) {
1178 mtime = remotemodtime(remote, 0);
1180 (void)gettimeofday(&tval[0], NULL);
1181 tval[1].tv_sec = mtime;
1182 tval[1].tv_usec = 0;
1183 if (utimes(local, tval) == -1) {
1185 "Can't change modification time on %s to %s",
1186 local, asctime(localtime(&mtime)));
1195 * abort using RFC 959 recommended IP,SYNC sequence
1197 if (! sigsetjmp(xferabort, 1)) {
1198 /* this is the first call */
1199 (void)xsignal(SIGINT, abort_squared);
1212 (void)xsignal(SIGINT, oldintr);
1214 (void)xsignal(SIGPIPE, oldintp);
1219 if (closefunc != NULL && fout != NULL)
1223 progress = oprogress;
1224 preserve = opreserve;
1229 * Need to start a listen on the data channel before we send the command,
1230 * otherwise the server's connect may fail.
1236 int result, tmpno = 0;
1239 unsigned int addr[16], port[2];
1240 unsigned int af, hal, pal;
1242 char *pasvcmd = NULL;
1247 if (myctladdr.su_family == AF_INET6 && ftp_debug &&
1248 (IN6_IS_ADDR_LINKLOCAL(&myctladdr.si_su.su_sin6.sin6_addr) ||
1249 IN6_IS_ADDR_SITELOCAL(&myctladdr.si_su.su_sin6.sin6_addr))) {
1250 warnx("Use of scoped addresses can be troublesome");
1257 data_addr = myctladdr;
1258 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1260 warn("Can't create socket for data connection");
1263 if ((options & SO_DEBUG) &&
1264 setsockopt(data, SOL_SOCKET, SO_DEBUG,
1265 (void *)&on, sizeof(on)) == -1) {
1266 DWARN("setsockopt %s (ignored)", "SO_DEBUG");
1268 result = COMPLETE + 1;
1269 switch (data_addr.su_family) {
1271 if (epsv4 && !epsv4bad) {
1276 result = command("EPSV");
1279 (result == COMPLETE || !connected))
1280 fprintf(ttyout, "%s\n", reply_string);
1284 * this code is to be friendly with broken
1287 if (code / 10 == 22 && code != 229) {
1289 "wrong server: return code must be 229\n",
1291 result = COMPLETE + 1;
1293 if (result != COMPLETE) {
1295 DPRINTF("disabling epsv4 for this "
1299 if (result != COMPLETE) {
1301 result = command("PASV");
1312 result = command("EPSV");
1315 (result == COMPLETE || !connected))
1316 fprintf(ttyout, "%s\n", reply_string);
1319 /* this code is to be friendly with broken BSDI ftpd */
1320 if (code / 10 == 22 && code != 229) {
1322 "wrong server: return code must be 229\n",
1324 result = COMPLETE + 1;
1326 if (result != COMPLETE) {
1328 result = command("LPSV");
1335 result = COMPLETE + 1;
1338 if (result != COMPLETE) {
1339 if (activefallback) {
1348 fputs("Passive mode refused.\n", ttyout);
1352 #define pack2(var, off) \
1353 (((var[(off) + 0] & 0xff) << 8) | ((var[(off) + 1] & 0xff) << 0))
1354 #define pack4(var, off) \
1355 (((var[(off) + 0] & 0xff) << 24) | ((var[(off) + 1] & 0xff) << 16) | \
1356 ((var[(off) + 2] & 0xff) << 8) | ((var[(off) + 3] & 0xff) << 0))
1357 #define UC(b) (((int)b)&0xff)
1360 * What we've got at this point is a string of comma separated
1361 * one-byte unsigned integer values, separated by commas.
1363 if (strcmp(pasvcmd, "PASV") == 0) {
1364 if (data_addr.su_family != AF_INET) {
1366 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1370 if (code / 10 == 22 && code != 227) {
1371 fputs("wrong server: return code must be 227\n",
1376 error = sscanf(pasv, "%u,%u,%u,%u,%u,%u",
1377 &addr[0], &addr[1], &addr[2], &addr[3],
1378 &port[0], &port[1]);
1381 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1386 memset(&data_addr, 0, sizeof(data_addr));
1387 data_addr.su_family = AF_INET;
1388 data_addr.su_len = sizeof(struct sockaddr_in);
1389 data_addr.si_su.su_sin.sin_addr.s_addr =
1390 htonl(pack4(addr, 0));
1391 data_addr.su_port = htons(pack2(port, 0));
1392 } else if (strcmp(pasvcmd, "LPSV") == 0) {
1393 if (code / 10 == 22 && code != 228) {
1394 fputs("wrong server: return code must be 228\n",
1399 switch (data_addr.su_family) {
1401 error = sscanf(pasv,
1402 "%u,%u,%u,%u,%u,%u,%u,%u,%u",
1404 &addr[0], &addr[1], &addr[2], &addr[3],
1405 &pal, &port[0], &port[1]);
1408 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1412 if (af != 4 || hal != 4 || pal != 2) {
1414 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1420 memset(&data_addr, 0, sizeof(data_addr));
1421 data_addr.su_family = AF_INET;
1422 data_addr.su_len = sizeof(struct sockaddr_in);
1423 data_addr.si_su.su_sin.sin_addr.s_addr =
1424 htonl(pack4(addr, 0));
1425 data_addr.su_port = htons(pack2(port, 0));
1429 error = sscanf(pasv,
1430 "%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u",
1432 &addr[0], &addr[1], &addr[2], &addr[3],
1433 &addr[4], &addr[5], &addr[6], &addr[7],
1434 &addr[8], &addr[9], &addr[10],
1435 &addr[11], &addr[12], &addr[13],
1436 &addr[14], &addr[15],
1437 &pal, &port[0], &port[1]);
1440 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1444 if (af != 6 || hal != 16 || pal != 2) {
1446 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1452 memset(&data_addr, 0, sizeof(data_addr));
1453 data_addr.su_family = AF_INET6;
1454 data_addr.su_len = sizeof(struct sockaddr_in6);
1457 for (i = 0; i < sizeof(struct in6_addr); i++) {
1458 data_addr.si_su.su_sin6.sin6_addr.s6_addr[i] =
1462 data_addr.su_port = htons(pack2(port, 0));
1468 } else if (strcmp(pasvcmd, "EPSV") == 0) {
1472 if (code / 10 == 22 && code != 229) {
1473 fputs("wrong server: return code must be 229\n",
1478 if (sscanf(pasv, "%c%c%c%d%c", &delim[0],
1479 &delim[1], &delim[2], &port[1],
1481 fputs("parse error!\n", ttyout);
1485 if (delim[0] != delim[1] || delim[0] != delim[2]
1486 || delim[0] != delim[3]) {
1487 fputs("parse error!\n", ttyout);
1491 data_addr = hisctladdr;
1492 data_addr.su_port = htons(port[1]);
1496 if (ftp_connect(data, (struct sockaddr *)&data_addr.si_su,
1497 data_addr.su_len) < 0) {
1498 if (activefallback) {
1509 #ifdef IPTOS_THROUGHPUT
1510 if (data_addr.su_family == AF_INET) {
1511 on = IPTOS_THROUGHPUT;
1512 if (setsockopt(data, IPPROTO_IP, IP_TOS,
1513 (void *)&on, sizeof(on)) == -1) {
1514 DWARN("setsockopt %s (ignored)",
1515 "IPTOS_THROUGHPUT");
1523 data_addr = myctladdr;
1525 data_addr.su_port = 0; /* let system pick one */
1528 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1530 warn("Can't create socket for data connection");
1536 if (setsockopt(data, SOL_SOCKET, SO_REUSEADDR,
1537 (void *)&on, sizeof(on)) == -1) {
1538 warn("Can't set SO_REUSEADDR on data connection");
1541 if (bind(data, (struct sockaddr *)&data_addr.si_su,
1542 data_addr.su_len) < 0) {
1543 warn("Can't bind for data connection");
1546 if ((options & SO_DEBUG) &&
1547 setsockopt(data, SOL_SOCKET, SO_DEBUG,
1548 (void *)&on, sizeof(on)) == -1) {
1549 DWARN("setsockopt %s (ignored)", "SO_DEBUG");
1551 len = sizeof(data_addr.si_su);
1552 memset((char *)&data_addr, 0, sizeof (data_addr));
1553 if (getsockname(data, (struct sockaddr *)&data_addr.si_su, &len) == -1) {
1554 warn("Can't determine my address of data connection");
1557 data_addr.su_len = len;
1558 if (ftp_listen(data, 1) < 0)
1559 warn("Can't listen to data connection");
1562 char hname[NI_MAXHOST], sname[NI_MAXSERV];
1564 struct sockinet tmp;
1566 switch (data_addr.su_family) {
1568 if (!epsv4 || epsv4bad) {
1569 result = COMPLETE + 1;
1576 af = (data_addr.su_family == AF_INET) ? 1 : 2;
1579 if (tmp.su_family == AF_INET6)
1580 tmp.si_su.su_sin6.sin6_scope_id = 0;
1582 if (getnameinfo((struct sockaddr *)&tmp.si_su,
1583 tmp.su_len, hname, sizeof(hname), sname,
1584 sizeof(sname), NI_NUMERICHOST | NI_NUMERICSERV)) {
1590 result = command("EPRT |%d|%s|%s|", af, hname,
1594 (result == COMPLETE || !connected))
1595 fprintf(ttyout, "%s\n", reply_string);
1598 if (result != COMPLETE) {
1600 DPRINTF("disabling epsv4 for this "
1606 result = COMPLETE + 1;
1609 if (result == COMPLETE)
1612 switch (data_addr.su_family) {
1614 a = (char *)&data_addr.si_su.su_sin.sin_addr;
1615 p = (char *)&data_addr.su_port;
1616 result = command("PORT %d,%d,%d,%d,%d,%d",
1617 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
1618 UC(p[0]), UC(p[1]));
1622 a = (char *)&data_addr.si_su.su_sin6.sin6_addr;
1623 p = (char *)&data_addr.su_port;
1625 "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
1627 UC(a[0]),UC(a[1]),UC(a[2]),UC(a[3]),
1628 UC(a[4]),UC(a[5]),UC(a[6]),UC(a[7]),
1629 UC(a[8]),UC(a[9]),UC(a[10]),UC(a[11]),
1630 UC(a[12]),UC(a[13]),UC(a[14]),UC(a[15]),
1631 2, UC(p[0]), UC(p[1]));
1635 result = COMPLETE + 1; /* xxx */
1641 if (result == ERROR && sendport == -1) {
1646 return (result != COMPLETE);
1650 #ifdef IPTOS_THROUGHPUT
1651 if (data_addr.su_family == AF_INET) {
1652 on = IPTOS_THROUGHPUT;
1653 if (setsockopt(data, IPPROTO_IP, IP_TOS,
1654 (void *)&on, sizeof(on)) == -1)
1655 DWARN("setsockopt %s (ignored)", "IPTOS_THROUGHPUT");
1668 dataconn(const char *lmode)
1670 struct sockinet from;
1671 int s, flags, rv, timeout;
1672 struct timeval endtime, now, td;
1673 struct pollfd pfd[1];
1676 if (passivemode) /* passive data connection */
1677 return (fdopen(data, lmode));
1679 /* active mode data connection */
1681 if ((flags = fcntl(data, F_GETFL, 0)) == -1)
1682 goto dataconn_failed; /* get current socket flags */
1683 if (fcntl(data, F_SETFL, flags | O_NONBLOCK) == -1)
1684 goto dataconn_failed; /* set non-blocking connect */
1686 /* NOTE: we now must restore socket flags on successful exit */
1688 /* limit time waiting on listening socket */
1690 pfd[0].events = POLLIN;
1691 (void)gettimeofday(&endtime, NULL); /* determine end time */
1692 endtime.tv_sec += (quit_time > 0) ? quit_time: 60;
1693 /* without -q, default to 60s */
1695 (void)gettimeofday(&now, NULL);
1696 timersub(&endtime, &now, &td);
1697 timeout = td.tv_sec * 1000 + td.tv_usec/1000;
1700 rv = ftp_poll(pfd, 1, timeout);
1701 } while (rv == -1 && errno == EINTR); /* loop until poll ! EINTR */
1703 warn("Can't poll waiting before accept");
1704 goto dataconn_failed;
1707 warnx("Poll timeout waiting before accept");
1708 goto dataconn_failed;
1711 /* (non-blocking) accept the connection */
1712 fromlen = myctladdr.su_len;
1714 s = accept(data, (struct sockaddr *) &from.si_su, &fromlen);
1715 } while (s == -1 && errno == EINTR); /* loop until accept ! EINTR */
1717 warn("Can't accept data connection");
1718 goto dataconn_failed;
1723 if (fcntl(data, F_SETFL, flags) == -1) /* restore socket flags */
1724 goto dataconn_failed;
1726 #ifdef IPTOS_THROUGHPUT
1727 if (from.su_family == AF_INET) {
1728 int tos = IPTOS_THROUGHPUT;
1729 if (setsockopt(s, IPPROTO_IP, IP_TOS,
1730 (void *)&tos, sizeof(tos)) == -1) {
1731 DWARN("setsockopt %s (ignored)", "IPTOS_THROUGHPUT");
1735 return (fdopen(data, lmode));
1744 psabort(int notused)
1758 static struct comvars {
1760 char name[MAXHOSTNAMELEN];
1761 struct sockinet mctl;
1762 struct sockinet hctl;
1775 char mi[MAXPATHLEN];
1776 char mo[MAXPATHLEN];
1777 } proxstruct, tmpstruct;
1778 struct comvars *ip, *op;
1781 oldintr = xsignal(SIGINT, psabort);
1795 ip->connect = connected;
1796 connected = op->connect;
1798 (void)strlcpy(ip->name, hostname, sizeof(ip->name));
1801 hostname = op->name;
1802 ip->hctl = hisctladdr;
1803 hisctladdr = op->hctl;
1804 ip->mctl = myctladdr;
1805 myctladdr = op->mctl;
1812 ip->curtpe = curtype;
1813 curtype = op->curtpe;
1816 ip->sunqe = sunique;
1817 sunique = op->sunqe;
1818 ip->runqe = runique;
1819 runique = op->runqe;
1824 (void)strlcpy(ip->nti, ntin, sizeof(ip->nti));
1825 (void)strlcpy(ntin, op->nti, sizeof(ntin));
1826 (void)strlcpy(ip->nto, ntout, sizeof(ip->nto));
1827 (void)strlcpy(ntout, op->nto, sizeof(ntout));
1828 ip->mapflg = mapflag;
1829 mapflag = op->mapflg;
1830 (void)strlcpy(ip->mi, mapin, sizeof(ip->mi));
1831 (void)strlcpy(mapin, op->mi, sizeof(mapin));
1832 (void)strlcpy(ip->mo, mapout, sizeof(ip->mo));
1833 (void)strlcpy(mapout, op->mo, sizeof(mapout));
1834 (void)xsignal(SIGINT, oldintr);
1842 abortpt(int notused)
1848 write(fileno(ttyout), "\n", 1);
1852 siglongjmp(ptabort, 1);
1856 proxtrans(const char *cmd, const char *local, const char *remote)
1858 sigfunc volatile oldintr;
1859 int prox_type, nfnd;
1860 int volatile secndflag;
1861 char *volatile cmd2;
1865 if (strcmp(cmd, "RETR"))
1868 cmd2 = runique ? "STOU" : "STOR";
1869 if ((prox_type = type) == 0) {
1870 if (unix_server && unix_proxy)
1875 if (curtype != prox_type)
1876 changetype(prox_type, 1);
1877 if (command("PASV") != COMPLETE) {
1878 fputs("proxy server does not support third party transfers.\n",
1884 fputs("No primary connection.\n", ttyout);
1889 if (curtype != prox_type)
1890 changetype(prox_type, 1);
1891 if (command("PORT %s", pasv) != COMPLETE) {
1895 if (sigsetjmp(ptabort, 1))
1897 oldintr = xsignal(SIGINT, abortpt);
1898 if ((restart_point &&
1899 (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1900 || (command("%s %s", cmd, remote) != PRELIM)) {
1901 (void)xsignal(SIGINT, oldintr);
1908 if ((restart_point &&
1909 (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1910 || (command("%s %s", cmd2, local) != PRELIM))
1916 (void)xsignal(SIGINT, oldintr);
1919 fprintf(ttyout, "local: %s remote: %s\n", local, remote);
1922 if (sigsetjmp(xferabort, 1)) {
1923 (void)xsignal(SIGINT, oldintr);
1926 (void)xsignal(SIGINT, abort_squared);
1928 if (strcmp(cmd, "RETR") && !proxy)
1930 else if (!strcmp(cmd, "RETR") && proxy)
1932 if (!cpend && !secndflag) { /* only here if cmd = "STOR" (proxy=1) */
1933 if (command("%s %s", cmd2, local) != PRELIM) {
1941 (void)xsignal(SIGINT, oldintr);
1947 if (!cpend && !secndflag) { /* only if cmd = "RETR" (proxy=1) */
1948 if (command("%s %s", cmd2, local) != PRELIM) {
1955 (void)xsignal(SIGINT, oldintr);
1963 if ((nfnd = empty(cin, NULL, 10)) <= 0) {
1965 warn("Error aborting proxy command");
1978 (void)xsignal(SIGINT, oldintr);
1982 reset(int argc, char *argv[])
1986 if (argc == 0 && argv != NULL) {
1987 UPRINTF("usage: %s\n", argv[0]);
1992 if ((nfnd = empty(cin, NULL, 0)) < 0) {
1993 warn("Error resetting connection");
2002 gunique(const char *local)
2004 static char new[MAXPATHLEN];
2005 char *cp = strrchr(local, '/');
2006 int d, count=0, len;
2011 d = access(cp == local ? "/" : cp ? local : ".", W_OK);
2015 warn("Can't access `%s'", local);
2018 len = strlcpy(new, local, sizeof(new));
2022 if (++count == 100) {
2023 fputs("runique: can't find unique file name.\n",
2033 if ((d = access(new, F_OK)) < 0)
2037 else if (*(cp - 2) == '.')
2040 *(cp - 2) = *(cp - 2) + 1;
2049 * aborts abort_remote(). lostpeer() is called because if the user is
2050 * too impatient to wait or there's another problem then ftp really
2051 * needs to get back to a known state.
2054 abort_squared(int dummy)
2061 len = strlcpy(msgbuf, "\nremote abort aborted; closing connection.\n",
2063 write(fileno(ttyout), msgbuf, len);
2065 siglongjmp(xferabort, 1);
2069 abort_remote(FILE *din)
2075 warnx("Lost control connection for abort");
2082 * send IAC in urgent mode instead of DM because 4.3BSD places oob mark
2083 * after urgent byte rather than before as is protocol now
2088 if (send(fileno(cout), buf, 3, MSG_OOB) != 3)
2089 warn("Can't send abort message");
2090 fprintf(cout, "%cABOR\r\n", DM);
2092 if ((nfnd = empty(cin, din, 10)) <= 0) {
2094 warn("Can't send abort message");
2099 if (din && (nfnd & 2)) {
2100 while (read(fileno(din), buf, BUFSIZ) > 0)
2103 if (getreply(0) == ERROR && code == 552) {
2104 /* 552 needed for nic style abort */
2111 * Ensure that ai->ai_addr is NOT an IPv4 mapped address.
2112 * IPv4 mapped address complicates too many things in FTP
2113 * protocol handling, as FTP protocol is defined differently
2114 * between IPv4 and IPv6.
2116 * This may not be the best way to handle this situation,
2117 * since the semantics of IPv4 mapped address is defined in
2118 * the kernel. There are configurations where we should use
2119 * IPv4 mapped address as native IPv6 address, not as
2120 * "an IPv6 address that embeds IPv4 address" (namely, SIIT).
2122 * More complete solution would be to have an additional
2123 * getsockopt to grab "real" peername/sockname. "real"
2124 * peername/sockname will be AF_INET if IPv4 mapped address
2125 * is used to embed IPv4 address, and will be AF_INET6 if
2126 * we use it as native. What a mess!
2129 ai_unmapped(struct addrinfo *ai)
2132 struct sockaddr_in6 *sin6;
2133 struct sockaddr_in sin;
2136 if (ai->ai_family != AF_INET6)
2138 if (ai->ai_addrlen != sizeof(struct sockaddr_in6) ||
2139 sizeof(sin) > ai->ai_addrlen)
2141 sin6 = (struct sockaddr_in6 *)ai->ai_addr;
2142 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
2145 memset(&sin, 0, sizeof(sin));
2146 sin.sin_family = AF_INET;
2147 len = sizeof(struct sockaddr_in);
2148 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
2149 sizeof(sin.sin_addr));
2150 sin.sin_port = sin6->sin6_port;
2152 ai->ai_family = AF_INET;
2153 #if HAVE_SOCKADDR_SA_LEN
2156 memcpy(ai->ai_addr, &sin, len);
2157 ai->ai_addrlen = len;
2165 fputs("Usage error\n", ttyout);