1 /* $NetBSD: ftp.c,v 1.163 2011/12/10 05:53:58 lukem Exp $ */
4 * Copyright (c) 1996-2009 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.
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
33 * Copyright (c) 1985, 1989, 1993, 1994
34 * The Regents of the University of California. All rights reserved.
36 * Redistribution and use in source and binary forms, with or without
37 * modification, are permitted provided that the following conditions
39 * 1. Redistributions of source code must retain the above copyright
40 * notice, this list of conditions and the following disclaimer.
41 * 2. Redistributions in binary form must reproduce the above copyright
42 * notice, this list of conditions and the following disclaimer in the
43 * documentation and/or other materials provided with the distribution.
44 * 3. Neither the name of the University nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62 * Copyright (C) 1997 and 1998 WIDE Project.
63 * All rights reserved.
65 * Redistribution and use in source and binary forms, with or without
66 * modification, are permitted provided that the following conditions
68 * 1. Redistributions of source code must retain the above copyright
69 * notice, this list of conditions and the following disclaimer.
70 * 2. Redistributions in binary form must reproduce the above copyright
71 * notice, this list of conditions and the following disclaimer in the
72 * documentation and/or other materials provided with the distribution.
73 * 3. Neither the name of the project nor the names of its contributors
74 * may be used to endorse or promote products derived from this software
75 * without specific prior written permission.
77 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
78 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
79 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
80 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
81 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
82 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
83 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
84 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
85 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
86 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
90 #include <sys/cdefs.h>
93 static char sccsid[] = "@(#)ftp.c 8.6 (Berkeley) 10/27/94";
95 __RCSID("$NetBSD: ftp.c,v 1.163 2011/12/10 05:53:58 lukem Exp $");
99 #include <sys/types.h>
100 #include <sys/stat.h>
101 #include <sys/socket.h>
102 #include <sys/time.h>
104 #include <netinet/in.h>
105 #include <netinet/in_systm.h>
106 #include <netinet/ip.h>
107 #include <arpa/inet.h>
108 #include <arpa/ftp.h>
109 #include <arpa/telnet.h>
126 volatile sig_atomic_t abrtflag;
127 volatile sig_atomic_t timeoutflag;
132 char pasv[BUFSIZ]; /* passive port for proxy data connection */
134 static int empty(FILE *, FILE *, int);
135 __dead static void abort_squared(int);
139 struct sockaddr_in su_sin;
141 struct sockaddr_in6 su_sin6;
144 #if !defined(HAVE_STRUCT_SOCKADDR_IN_SIN_LEN)
149 #if !defined(HAVE_STRUCT_SOCKADDR_IN_SIN_LEN)
150 # define su_len si_len
152 # define su_len si_su.su_sin.sin_len
154 #define su_family si_su.su_sin.sin_family
155 #define su_port si_su.su_sin.sin_port
157 struct sockinet myctladdr, hisctladdr, data_addr;
160 hookup(const char *host, const char *port)
163 struct addrinfo hints, *res, *res0;
164 static char hostnamebuf[MAXHOSTNAMELEN];
168 memset((char *)&hisctladdr, 0, sizeof (hisctladdr));
169 memset((char *)&myctladdr, 0, sizeof (myctladdr));
170 memset(&hints, 0, sizeof(hints));
171 hints.ai_flags = AI_CANONNAME;
172 hints.ai_family = family;
173 hints.ai_socktype = SOCK_STREAM;
174 hints.ai_protocol = 0;
175 error = getaddrinfo(host, port, &hints, &res0);
177 warnx("Can't lookup `%s:%s': %s", host, port,
178 (error == EAI_SYSTEM) ? strerror(errno)
179 : gai_strerror(error));
184 if (res0->ai_canonname)
185 (void)strlcpy(hostnamebuf, res0->ai_canonname,
186 sizeof(hostnamebuf));
188 (void)strlcpy(hostnamebuf, host, sizeof(hostnamebuf));
189 hostname = hostnamebuf;
191 for (res = res0; res; res = res->ai_next) {
192 char hname[NI_MAXHOST], sname[NI_MAXSERV];
195 if (getnameinfo(res->ai_addr, res->ai_addrlen,
196 hname, sizeof(hname), sname, sizeof(sname),
197 NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
198 strlcpy(hname, "?", sizeof(hname));
199 strlcpy(sname, "?", sizeof(sname));
201 if (verbose && res0->ai_next) {
202 /* if we have multiple possibilities */
203 fprintf(ttyout, "Trying %s:%s ...\n", hname, sname);
205 s = socket(res->ai_family, SOCK_STREAM, res->ai_protocol);
207 warn("Can't create socket for connection to `%s:%s'",
211 if (ftp_connect(s, res->ai_addr, res->ai_addrlen) < 0) {
217 /* finally we got one */
221 warnx("Can't connect to `%s:%s'", host, port);
226 memcpy(&hisctladdr.si_su, res->ai_addr, res->ai_addrlen);
227 hisctladdr.su_len = res->ai_addrlen;
231 len = hisctladdr.su_len;
232 if (getsockname(s, (struct sockaddr *)&myctladdr.si_su, &len) == -1) {
233 warn("Can't determine my address of connection to `%s:%s'",
238 myctladdr.su_len = len;
240 #ifdef IPTOS_LOWDELAY
241 if (hisctladdr.su_family == AF_INET) {
242 int tos = IPTOS_LOWDELAY;
243 if (setsockopt(s, IPPROTO_IP, IP_TOS,
244 (void *)&tos, sizeof(tos)) == -1) {
245 DWARN("setsockopt %s (ignored)",
250 cin = fdopen(s, "r");
251 cout = fdopen(s, "w");
252 if (cin == NULL || cout == NULL) {
253 warnx("Can't fdopen socket");
262 fprintf(ttyout, "Connected to %s.\n", hostname);
263 if (getreply(0) > 2) { /* read startup message from server */
272 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE,
273 (void *)&on, sizeof(on)) == -1) {
274 DWARN("setsockopt %s (ignored)", "SO_OOBINLINE");
284 cmdabort(int notused)
291 write(fileno(ttyout), "\n", 1);
294 siglongjmp(ptabort, 1);
299 cmdtimeout(int notused)
305 write(fileno(ttyout), "\n", 1);
308 siglongjmp(ptabort, 1);
314 command(const char *fmt, ...)
322 fputs("---> ", ttyout);
324 if (strncmp("PASS ", fmt, 5) == 0)
325 fputs("PASS XXXX", ttyout);
326 else if (strncmp("ACCT ", fmt, 5) == 0)
327 fputs("ACCT XXXX", ttyout);
329 vfprintf(ttyout, fmt, ap);
335 warnx("No control connection for command");
342 oldsigint = xsignal(SIGINT, cmdabort);
345 vfprintf(cout, fmt, ap);
350 r = getreply(!strcmp(fmt, "QUIT"));
351 if (abrtflag && oldsigint != SIG_IGN)
352 (*oldsigint)(SIGINT);
353 (void)xsignal(SIGINT, oldsigint);
357 static const char *m421[] = {
358 "remote server timed out. Connection closed",
359 "user interrupt. Connection closed",
360 "remote server has closed connection",
364 getreply(int expecteof)
366 char current_line[BUFSIZ]; /* last line of previous reply */
369 int originalcode = 0, continuation = 0;
370 sigfunc oldsigint, oldsigalrm;
372 char *cp, *pt = pasv;
377 oldsigint = xsignal(SIGINT, cmdabort);
378 oldsigalrm = xsignal(SIGALRM, cmdtimeout);
380 for (lineno = 0 ;; lineno++) {
383 while (alarmtimer(quit_time ? quit_time : 60),
384 ((c = getc(cin)) != '\n')) {
385 if (c == IAC) { /* handle telnet commands */
386 switch (c = getc(cin)) {
390 fprintf(cout, "%c%c%c", IAC, DONT, c);
396 fprintf(cout, "%c%c%c", IAC, WONT, c);
407 * these will get trashed by pswitch()
410 int reply_timeoutflag = timeoutflag;
411 int reply_abrtflag = abrtflag;
414 if (expecteof && feof(cin)) {
415 (void)xsignal(SIGINT, oldsigint);
416 (void)xsignal(SIGALRM, oldsigalrm);
424 if (reply_timeoutflag)
426 else if (reply_abrtflag)
430 (void)fprintf(ttyout,
431 "421 Service not available, %s.\n", m421[midx]);
432 (void)fflush(ttyout);
435 (void)xsignal(SIGINT, oldsigint);
436 (void)xsignal(SIGALRM, oldsigalrm);
439 if (c != '\r' && (verbose > 0 ||
440 ((verbose > -1 && n == '5' && dig > 4) &&
441 (((!n && c < '5') || (n && n < '5'))
442 || !retry_connect)))) {
444 (dig == 1 || (dig == 5 && verbose == 0)))
445 fprintf(ttyout, "%s:", hostname);
446 (void)putc(c, ttyout);
448 if (dig < 4 && isdigit(c))
449 code = code * 10 + (c - '0');
450 if (!pflag && (code == 227 || code == 228))
452 else if (!pflag && code == 229)
454 if (dig > 4 && pflag == 1 && isdigit(c))
457 if (c != '\r' && c != ')') {
458 if (pt < &pasv[sizeof(pasv) - 1])
465 if (pflag == 100 && c == '(')
467 if (dig == 4 && c == '-') {
474 if (cp < ¤t_line[sizeof(current_line) - 1])
477 if (verbose > 0 || ((verbose > -1 && n == '5') &&
478 (n < '5' || !retry_connect))) {
479 (void)putc(c, ttyout);
480 (void)fflush(ttyout);
486 (void)strlcpy(reply_string, current_line,
487 sizeof(reply_string));
488 if (lineno > 0 && code == 0 && reply_callback != NULL)
489 (*reply_callback)(current_line);
490 if (continuation && code != originalcode) {
491 if (originalcode == 0)
498 (void)xsignal(SIGINT, oldsigint);
499 (void)xsignal(SIGALRM, oldsigalrm);
500 if (code == 421 || originalcode == 421)
502 if (abrtflag && oldsigint != cmdabort && oldsigint != SIG_IGN)
503 (*oldsigint)(SIGINT);
504 if (timeoutflag && oldsigalrm != cmdtimeout &&
505 oldsigalrm != SIG_IGN)
506 (*oldsigalrm)(SIGINT);
512 empty(FILE *ecin, FILE *din, int sec)
515 struct pollfd pfd[2];
519 pfd[nfd].fd = fileno(ecin);
520 pfd[nfd++].events = POLLIN;
524 pfd[nfd].fd = fileno(din);
525 pfd[nfd++].events = POLLIN;
528 if ((nr = ftp_poll(pfd, nfd, sec * 1000)) <= 0)
534 nr |= (pfd[nfd++].revents & POLLIN) ? 1 : 0;
536 nr |= (pfd[nfd++].revents & POLLIN) ? 2 : 0;
540 sigjmp_buf xferabort;
543 abortxfer(int notused)
552 switch (direction[0]) {
554 strlcpy(msgbuf, "\nreceive", sizeof(msgbuf));
557 strlcpy(msgbuf, "\nsend", sizeof(msgbuf));
560 errx(1, "abortxfer: unknown direction `%s'", direction);
562 len = strlcat(msgbuf, " aborted. Waiting for remote to finish abort.\n",
564 write(fileno(ttyout), msgbuf, len);
565 siglongjmp(xferabort, 1);
569 * Read data from infd & write to outfd, using buf/bufsize as the temporary
570 * buffer, dealing with short writes.
571 * If rate_limit != 0, rate-limit the transfer.
572 * If hash_interval != 0, fputc('c', ttyout) every hash_interval bytes.
573 * Updates global variables: bytes.
574 * Returns 0 if ok, 1 if there was a read error, 2 if there was a write error.
575 * In the case of error, errno contains the appropriate error code.
578 copy_bytes(int infd, int outfd, char *buf, size_t bufsize,
579 int rate_limit, int hash_interval)
581 volatile off_t hashc;
584 struct timeval tvthen, tvnow, tvdiff;
585 off_t bufrem, bufchunk;
588 hashc = hash_interval;
590 bufchunk = rate_limit;
596 (void)gettimeofday(&tvthen, NULL);
600 /* copy bufchunk at a time */
603 inc = read(infd, buf, MIN((off_t)bufsize, bufrem));
610 outc = write(outfd, bufp, inc);
617 while (bytes >= hashc) {
618 (void)putc('#', ttyout);
619 hashc += hash_interval;
621 (void)fflush(ttyout);
624 if (rate_limit) { /* rate limited; wait if necessary */
626 (void)gettimeofday(&tvnow, NULL);
627 timersub(&tvnow, &tvthen, &tvdiff);
628 if (tvdiff.tv_sec > 0)
630 usleep(1000000 - tvdiff.tv_usec);
637 if (hash_interval && bytes > 0) {
638 if (bytes < hash_interval)
639 (void)putc('#', ttyout);
640 (void)putc('\n', ttyout);
641 (void)fflush(ttyout);
653 sendrequest(const char *cmd, const char *local, const char *remote,
660 int (*volatile closefunc)(FILE *);
661 sigfunc volatile oldintr;
662 sigfunc volatile oldintp;
663 off_t volatile hashbytes;
666 static size_t bufsize;
675 oprogress = progress;
676 if (verbose && printnames) {
678 fprintf(ttyout, "local: %s ", local);
680 fprintf(ttyout, "remote: %s\n", remote);
683 proxtrans(cmd, local, remote);
692 if (sigsetjmp(xferabort, 1)) {
698 (void)xsignal(SIGQUIT, psummary);
699 oldintr = xsignal(SIGINT, abortxfer);
700 if (strcmp(local, "-") == 0) {
703 } else if (*local == '|') {
704 oldintp = xsignal(SIGPIPE, SIG_IGN);
705 fin = popen(local + 1, "r");
707 warn("Can't execute `%s'", local + 1);
714 fin = fopen(local, "r");
716 warn("Can't open `%s'", local);
721 if (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode)) {
722 fprintf(ttyout, "%s: not a plain file.\n", local);
726 filesize = st.st_size;
732 if (sigsetjmp(xferabort, 1))
736 (strcmp(cmd, "STOR") == 0 || strcmp(cmd, "APPE") == 0)) {
742 rc = fseeko(fin, restart_point, SEEK_SET);
746 rc = lseek(fileno(fin), restart_point, SEEK_SET);
750 warn("Can't seek to restart `%s'", local);
753 if (command("REST " LLF, (LLT)restart_point) != CONTINUE)
758 if (command("%s %s", cmd, remote) != PRELIM)
761 if (command("%s", cmd) != PRELIM)
765 dout = dataconn(lmode);
769 assert(sndbuf_size > 0);
770 if ((size_t)sndbuf_size > bufsize) {
773 bufsize = sndbuf_size;
774 buf = ftp_malloc(bufsize);
778 oldintp = xsignal(SIGPIPE, SIG_IGN);
779 hash_interval = (hash && (!progress || filesize < 0)) ? mark : 0;
785 c = copy_bytes(fileno(fin), fileno(dout), buf, bufsize,
786 rate_put, hash_interval);
788 warn("Reading `%s'", local);
791 warn("Writing to network");
797 while ((c = getc(fin)) != EOF) {
799 while (hash_interval && bytes >= hashbytes) {
800 (void)putc('#', ttyout);
801 (void)fflush(ttyout);
806 (void)putc('\r', dout);
811 #if 0 /* this violates RFC 959 */
813 (void)putc('\0', dout);
819 if (bytes < hashbytes)
820 (void)putc('#', ttyout);
821 (void)putc('\n', ttyout);
824 warn("Reading `%s'", local);
827 warn("Writing to network");
834 if (closefunc != NULL) {
846 (void)xsignal(SIGINT, oldintr);
867 (void)xsignal(SIGINT, oldintr);
869 (void)xsignal(SIGPIPE, oldintp);
874 if (closefunc != NULL && fin != NULL)
878 progress = oprogress;
884 recvrequest(const char *cmd, const char *volatile local, const char *remote,
885 const char *lmode, int printnames, int ignorespecial)
889 int (*volatile closefunc)(FILE *);
890 sigfunc volatile oldintr;
891 sigfunc volatile oldintp;
893 int volatile is_retr;
894 int volatile tcrflag;
895 int volatile bare_lfs;
896 static size_t bufsize;
898 off_t volatile hashbytes;
902 struct timeval tval[2];
909 direction = "received";
913 oprogress = progress;
914 opreserve = preserve;
915 is_retr = (strcmp(cmd, "RETR") == 0);
916 if (is_retr && verbose && printnames) {
917 if (ignorespecial || *local != '-')
918 fprintf(ttyout, "local: %s ", local);
920 fprintf(ttyout, "remote: %s\n", remote);
922 if (proxy && is_retr) {
923 proxtrans(cmd, local, remote);
929 tcrflag = !crflag && is_retr;
930 if (sigsetjmp(xferabort, 1)) {
936 (void)xsignal(SIGQUIT, psummary);
937 oldintr = xsignal(SIGINT, abortxfer);
938 if (ignorespecial || (strcmp(local, "-") && *local != '|')) {
939 if (access(local, W_OK) < 0) {
940 char *dir = strrchr(local, '/');
942 if (errno != ENOENT && errno != EACCES) {
943 warn("Can't access `%s'", local);
949 d = access(dir == local ? "/" :
950 dir ? local : ".", W_OK);
954 warn("Can't access `%s'", local);
958 if (!runique && errno == EACCES &&
959 chmod(local, (S_IRUSR|S_IWUSR)) < 0) {
960 warn("Can't chmod `%s'", local);
964 if (runique && errno == EACCES &&
965 (local = gunique(local)) == NULL) {
970 else if (runique && (local = gunique(local)) == NULL) {
976 if (curtype != TYPE_A)
977 changetype(TYPE_A, 0);
981 filesize = remotesize(remote, 0);
982 if (code == 421 || code == -1)
989 if (sigsetjmp(xferabort, 1))
991 if (is_retr && restart_point &&
992 command("REST " LLF, (LLT) restart_point) != CONTINUE)
994 if (! EMPTYSTRING(remote)) {
995 if (command("%s %s", cmd, remote) != PRELIM)
998 if (command("%s", cmd) != PRELIM)
1001 din = dataconn("r");
1004 if (!ignorespecial && strcmp(local, "-") == 0) {
1008 } else if (!ignorespecial && *local == '|') {
1009 oldintp = xsignal(SIGPIPE, SIG_IGN);
1010 fout = popen(local + 1, "w");
1012 warn("Can't execute `%s'", local+1);
1019 fout = fopen(local, lmode);
1021 warn("Can't open `%s'", local);
1027 if (fstat(fileno(fout), &st) != -1 && !S_ISREG(st.st_mode)) {
1031 assert(rcvbuf_size > 0);
1032 if ((size_t)rcvbuf_size > bufsize) {
1035 bufsize = rcvbuf_size;
1036 buf = ftp_malloc(bufsize);
1040 hash_interval = (hash && (!progress || filesize < 0)) ? mark : 0;
1046 if (is_retr && restart_point &&
1047 lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1048 warn("Can't seek to restart `%s'", local);
1051 c = copy_bytes(fileno(din), fileno(fout), buf, bufsize,
1052 rate_get, hash_interval);
1055 warn("Reading from network");
1057 } else if (c == 2) {
1058 warn("Writing `%s'", local);
1063 if (is_retr && restart_point) {
1067 if (fseeko(fout, (off_t)0, SEEK_SET) < 0)
1069 for (i = 0; i++ < restart_point;) {
1070 if ((ch = getc(fout)) == EOF)
1075 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1077 warn("Can't seek to restart `%s'", local);
1081 while ((c = getc(din)) != EOF) {
1085 while (hash_interval && bytes >= hashbytes) {
1086 (void)putc('#', ttyout);
1087 (void)fflush(ttyout);
1091 if ((c = getc(din)) != '\n' || tcrflag) {
1094 (void)putc('\r', fout);
1103 (void)putc(c, fout);
1108 if (hash_interval) {
1109 if (bytes < hashbytes)
1110 (void)putc('#', ttyout);
1111 (void)putc('\n', ttyout);
1115 warn("Reading from network");
1119 warn("Writing `%s'", local);
1124 if (closefunc != NULL) {
1133 "WARNING! %d bare linefeeds received in ASCII mode.\n",
1135 fputs("File may not have transferred correctly.\n", ttyout);
1137 if (bytes >= 0 && is_retr) {
1140 if (preserve && (closefunc == fclose)) {
1141 mtime = remotemodtime(remote, 0);
1143 (void)gettimeofday(&tval[0], NULL);
1144 tval[1].tv_sec = mtime;
1145 tval[1].tv_usec = 0;
1146 if (utimes(local, tval) == -1) {
1148 "Can't change modification time on %s to %s",
1150 rfc2822time(localtime(&mtime)));
1159 * abort using RFC 959 recommended IP,SYNC sequence
1161 if (! sigsetjmp(xferabort, 1)) {
1162 /* this is the first call */
1163 (void)xsignal(SIGINT, abort_squared);
1176 (void)xsignal(SIGINT, oldintr);
1178 (void)xsignal(SIGPIPE, oldintp);
1183 if (closefunc != NULL && fout != NULL)
1187 progress = oprogress;
1188 preserve = opreserve;
1193 * Need to start a listen on the data channel before we send the command,
1194 * otherwise the server's connect may fail.
1200 int result, tmpno = 0;
1203 unsigned int addr[16], port[2];
1204 unsigned int af, hal, pal;
1206 const char *pasvcmd = NULL;
1211 if (myctladdr.su_family == AF_INET6 && ftp_debug &&
1212 (IN6_IS_ADDR_LINKLOCAL(&myctladdr.si_su.su_sin6.sin6_addr) ||
1213 IN6_IS_ADDR_SITELOCAL(&myctladdr.si_su.su_sin6.sin6_addr))) {
1214 warnx("Use of scoped addresses can be troublesome");
1221 data_addr = myctladdr;
1222 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1224 warn("Can't create socket for data connection");
1227 if ((options & SO_DEBUG) &&
1228 setsockopt(data, SOL_SOCKET, SO_DEBUG,
1229 (void *)&on, sizeof(on)) == -1) {
1230 DWARN("setsockopt %s (ignored)", "SO_DEBUG");
1232 result = COMPLETE + 1;
1233 switch (data_addr.su_family) {
1235 if (epsv4 && !epsv4bad) {
1240 result = command("EPSV");
1243 (result == COMPLETE || !connected))
1244 fprintf(ttyout, "%s\n", reply_string);
1248 * this code is to be friendly with broken
1251 if (code / 10 == 22 && code != 229) {
1253 "wrong server: return code must be 229\n",
1255 result = COMPLETE + 1;
1257 if (result != COMPLETE) {
1259 DPRINTF("disabling epsv4 for this "
1263 if (result != COMPLETE) {
1265 result = command("PASV");
1272 if (epsv6 && !epsv6bad) {
1277 result = command("EPSV");
1280 (result == COMPLETE || !connected))
1281 fprintf(ttyout, "%s\n", reply_string);
1285 * this code is to be friendly with
1288 if (code / 10 == 22 && code != 229) {
1290 "wrong server: return code must be 229\n",
1292 result = COMPLETE + 1;
1294 if (result != COMPLETE) {
1296 DPRINTF("disabling epsv6 for this "
1300 if (result != COMPLETE) {
1302 result = command("LPSV");
1309 result = COMPLETE + 1;
1312 if (result != COMPLETE) {
1313 if (activefallback) {
1322 fputs("Passive mode refused.\n", ttyout);
1326 #define pack2(var, off) \
1327 (((var[(off) + 0] & 0xff) << 8) | ((var[(off) + 1] & 0xff) << 0))
1328 #define pack4(var, off) \
1329 (((var[(off) + 0] & 0xff) << 24) | ((var[(off) + 1] & 0xff) << 16) | \
1330 ((var[(off) + 2] & 0xff) << 8) | ((var[(off) + 3] & 0xff) << 0))
1331 #define UC(b) (((int)b)&0xff)
1334 * What we've got at this point is a string of comma separated
1335 * one-byte unsigned integer values, separated by commas.
1337 if (strcmp(pasvcmd, "PASV") == 0) {
1338 if (data_addr.su_family != AF_INET) {
1340 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1344 if (code / 10 == 22 && code != 227) {
1345 fputs("wrong server: return code must be 227\n",
1350 error = sscanf(pasv, "%u,%u,%u,%u,%u,%u",
1351 &addr[0], &addr[1], &addr[2], &addr[3],
1352 &port[0], &port[1]);
1355 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1360 memset(&data_addr, 0, sizeof(data_addr));
1361 data_addr.su_family = AF_INET;
1362 data_addr.su_len = sizeof(struct sockaddr_in);
1363 data_addr.si_su.su_sin.sin_addr.s_addr =
1364 htonl(pack4(addr, 0));
1365 data_addr.su_port = htons(pack2(port, 0));
1366 } else if (strcmp(pasvcmd, "LPSV") == 0) {
1367 if (code / 10 == 22 && code != 228) {
1368 fputs("wrong server: return code must be 228\n",
1373 switch (data_addr.su_family) {
1375 error = sscanf(pasv,
1376 "%u,%u,%u,%u,%u,%u,%u,%u,%u",
1378 &addr[0], &addr[1], &addr[2], &addr[3],
1379 &pal, &port[0], &port[1]);
1382 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1386 if (af != 4 || hal != 4 || pal != 2) {
1388 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1394 memset(&data_addr, 0, sizeof(data_addr));
1395 data_addr.su_family = AF_INET;
1396 data_addr.su_len = sizeof(struct sockaddr_in);
1397 data_addr.si_su.su_sin.sin_addr.s_addr =
1398 htonl(pack4(addr, 0));
1399 data_addr.su_port = htons(pack2(port, 0));
1403 error = sscanf(pasv,
1404 "%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u",
1406 &addr[0], &addr[1], &addr[2], &addr[3],
1407 &addr[4], &addr[5], &addr[6], &addr[7],
1408 &addr[8], &addr[9], &addr[10],
1409 &addr[11], &addr[12], &addr[13],
1410 &addr[14], &addr[15],
1411 &pal, &port[0], &port[1]);
1414 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1418 if (af != 6 || hal != 16 || pal != 2) {
1420 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1426 memset(&data_addr, 0, sizeof(data_addr));
1427 data_addr.su_family = AF_INET6;
1428 data_addr.su_len = sizeof(struct sockaddr_in6);
1431 for (i = 0; i < sizeof(struct in6_addr); i++) {
1432 data_addr.si_su.su_sin6.sin6_addr.s6_addr[i] =
1436 data_addr.su_port = htons(pack2(port, 0));
1442 } else if (strcmp(pasvcmd, "EPSV") == 0) {
1446 if (code / 10 == 22 && code != 229) {
1447 fputs("wrong server: return code must be 229\n",
1452 if (sscanf(pasv, "%c%c%c%d%c", &delim[0],
1453 &delim[1], &delim[2], &port[1],
1455 fputs("parse error!\n", ttyout);
1459 if (delim[0] != delim[1] || delim[0] != delim[2]
1460 || delim[0] != delim[3]) {
1461 fputs("parse error!\n", ttyout);
1465 data_addr = hisctladdr;
1466 data_addr.su_port = htons(port[1]);
1470 if (ftp_connect(data, (struct sockaddr *)&data_addr.si_su,
1471 data_addr.su_len) < 0) {
1472 if (activefallback) {
1483 #ifdef IPTOS_THROUGHPUT
1484 if (data_addr.su_family == AF_INET) {
1485 on = IPTOS_THROUGHPUT;
1486 if (setsockopt(data, IPPROTO_IP, IP_TOS,
1487 (void *)&on, sizeof(on)) == -1) {
1488 DWARN("setsockopt %s (ignored)",
1489 "IPTOS_THROUGHPUT");
1497 data_addr = myctladdr;
1499 data_addr.su_port = 0; /* let system pick one */
1502 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1504 warn("Can't create socket for data connection");
1510 if (setsockopt(data, SOL_SOCKET, SO_REUSEADDR,
1511 (void *)&on, sizeof(on)) == -1) {
1512 warn("Can't set SO_REUSEADDR on data connection");
1515 if (bind(data, (struct sockaddr *)&data_addr.si_su,
1516 data_addr.su_len) < 0) {
1517 warn("Can't bind for data connection");
1520 if ((options & SO_DEBUG) &&
1521 setsockopt(data, SOL_SOCKET, SO_DEBUG,
1522 (void *)&on, sizeof(on)) == -1) {
1523 DWARN("setsockopt %s (ignored)", "SO_DEBUG");
1525 len = sizeof(data_addr.si_su);
1526 memset((char *)&data_addr, 0, sizeof (data_addr));
1527 if (getsockname(data, (struct sockaddr *)&data_addr.si_su, &len) == -1) {
1528 warn("Can't determine my address of data connection");
1531 data_addr.su_len = len;
1532 if (ftp_listen(data, 1) < 0)
1533 warn("Can't listen to data connection");
1536 char hname[NI_MAXHOST], sname[NI_MAXSERV];
1537 struct sockinet tmp;
1539 switch (data_addr.su_family) {
1541 if (!epsv4 || epsv4bad) {
1542 result = COMPLETE + 1;
1548 if (!epsv6 || epsv6bad) {
1549 result = COMPLETE + 1;
1553 af = (data_addr.su_family == AF_INET) ? 1 : 2;
1556 if (tmp.su_family == AF_INET6)
1557 tmp.si_su.su_sin6.sin6_scope_id = 0;
1559 if (getnameinfo((struct sockaddr *)&tmp.si_su,
1560 tmp.su_len, hname, sizeof(hname), sname,
1561 sizeof(sname), NI_NUMERICHOST | NI_NUMERICSERV)) {
1567 result = command("EPRT |%u|%s|%s|", af, hname,
1571 (result == COMPLETE || !connected))
1572 fprintf(ttyout, "%s\n", reply_string);
1575 if (result != COMPLETE) {
1577 DPRINTF("disabling epsv4 for this "
1583 result = COMPLETE + 1;
1586 if (result == COMPLETE)
1589 switch (data_addr.su_family) {
1591 a = (char *)&data_addr.si_su.su_sin.sin_addr;
1592 p = (char *)&data_addr.su_port;
1593 result = command("PORT %d,%d,%d,%d,%d,%d",
1594 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
1595 UC(p[0]), UC(p[1]));
1599 uint8_t ua[sizeof(data_addr.si_su.su_sin6.sin6_addr)];
1600 uint8_t up[sizeof(data_addr.su_port)];
1602 memcpy(ua, &data_addr.si_su.su_sin6.sin6_addr,
1604 memcpy(up, &data_addr.su_port, sizeof(up));
1607 "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
1609 ua[0], ua[1], ua[2], ua[3],
1610 ua[4], ua[5], ua[6], ua[7],
1611 ua[8], ua[9], ua[10], ua[11],
1612 ua[12], ua[13], ua[14], ua[15],
1619 result = COMPLETE + 1; /* xxx */
1625 if (result == ERROR && sendport == -1) {
1630 return (result != COMPLETE);
1634 #ifdef IPTOS_THROUGHPUT
1635 if (data_addr.su_family == AF_INET) {
1636 on = IPTOS_THROUGHPUT;
1637 if (setsockopt(data, IPPROTO_IP, IP_TOS,
1638 (void *)&on, sizeof(on)) == -1) {
1639 DWARN("setsockopt %s (ignored)", "IPTOS_THROUGHPUT");
1653 dataconn(const char *lmode)
1655 struct sockinet from;
1656 int s, flags, rv, timeout;
1657 struct timeval endtime, now, td;
1658 struct pollfd pfd[1];
1661 if (passivemode) /* passive data connection */
1662 return (fdopen(data, lmode));
1664 /* active mode data connection */
1666 if ((flags = fcntl(data, F_GETFL, 0)) == -1)
1667 goto dataconn_failed; /* get current socket flags */
1668 if (fcntl(data, F_SETFL, flags | O_NONBLOCK) == -1)
1669 goto dataconn_failed; /* set non-blocking connect */
1671 /* NOTE: we now must restore socket flags on successful exit */
1673 /* limit time waiting on listening socket */
1675 pfd[0].events = POLLIN;
1676 (void)gettimeofday(&endtime, NULL); /* determine end time */
1677 endtime.tv_sec += (quit_time > 0) ? quit_time: 60;
1678 /* without -q, default to 60s */
1680 (void)gettimeofday(&now, NULL);
1681 timersub(&endtime, &now, &td);
1682 timeout = td.tv_sec * 1000 + td.tv_usec/1000;
1685 rv = ftp_poll(pfd, 1, timeout);
1686 } while (rv == -1 && errno == EINTR); /* loop until poll ! EINTR */
1688 warn("Can't poll waiting before accept");
1689 goto dataconn_failed;
1692 warnx("Poll timeout waiting before accept");
1693 goto dataconn_failed;
1696 /* (non-blocking) accept the connection */
1697 fromlen = myctladdr.su_len;
1699 s = accept(data, (struct sockaddr *) &from.si_su, &fromlen);
1700 } while (s == -1 && errno == EINTR); /* loop until accept ! EINTR */
1702 warn("Can't accept data connection");
1703 goto dataconn_failed;
1708 if (fcntl(data, F_SETFL, flags) == -1) /* restore socket flags */
1709 goto dataconn_failed;
1711 #ifdef IPTOS_THROUGHPUT
1712 if (from.su_family == AF_INET) {
1713 int tos = IPTOS_THROUGHPUT;
1714 if (setsockopt(s, IPPROTO_IP, IP_TOS,
1715 (void *)&tos, sizeof(tos)) == -1) {
1716 DWARN("setsockopt %s (ignored)", "IPTOS_THROUGHPUT");
1720 return (fdopen(data, lmode));
1729 psabort(int notused)
1743 static struct comvars {
1745 char name[MAXHOSTNAMELEN];
1746 struct sockinet mctl;
1747 struct sockinet hctl;
1760 char mi[MAXPATHLEN];
1761 char mo[MAXPATHLEN];
1762 } proxstruct, tmpstruct;
1763 struct comvars *ip, *op;
1766 oldintr = xsignal(SIGINT, psabort);
1780 ip->connect = connected;
1781 connected = op->connect;
1783 (void)strlcpy(ip->name, hostname, sizeof(ip->name));
1786 hostname = op->name;
1787 ip->hctl = hisctladdr;
1788 hisctladdr = op->hctl;
1789 ip->mctl = myctladdr;
1790 myctladdr = op->mctl;
1797 ip->curtpe = curtype;
1798 curtype = op->curtpe;
1801 ip->sunqe = sunique;
1802 sunique = op->sunqe;
1803 ip->runqe = runique;
1804 runique = op->runqe;
1809 (void)strlcpy(ip->nti, ntin, sizeof(ip->nti));
1810 (void)strlcpy(ntin, op->nti, sizeof(ntin));
1811 (void)strlcpy(ip->nto, ntout, sizeof(ip->nto));
1812 (void)strlcpy(ntout, op->nto, sizeof(ntout));
1813 ip->mapflg = mapflag;
1814 mapflag = op->mapflg;
1815 (void)strlcpy(ip->mi, mapin, sizeof(ip->mi));
1816 (void)strlcpy(mapin, op->mi, sizeof(mapin));
1817 (void)strlcpy(ip->mo, mapout, sizeof(ip->mo));
1818 (void)strlcpy(mapout, op->mo, sizeof(mapout));
1819 (void)xsignal(SIGINT, oldintr);
1827 abortpt(int notused)
1833 write(fileno(ttyout), "\n", 1);
1837 siglongjmp(ptabort, 1);
1841 proxtrans(const char *cmd, const char *local, const char *remote)
1843 sigfunc volatile oldintr;
1844 int prox_type, nfnd;
1845 int volatile secndflag;
1846 const char *volatile cmd2;
1850 if (strcmp(cmd, "RETR"))
1853 cmd2 = runique ? "STOU" : "STOR";
1854 if ((prox_type = type) == 0) {
1855 if (unix_server && unix_proxy)
1860 if (curtype != prox_type)
1861 changetype(prox_type, 1);
1862 if (command("PASV") != COMPLETE) {
1863 fputs("proxy server does not support third party transfers.\n",
1869 fputs("No primary connection.\n", ttyout);
1874 if (curtype != prox_type)
1875 changetype(prox_type, 1);
1876 if (command("PORT %s", pasv) != COMPLETE) {
1880 if (sigsetjmp(ptabort, 1))
1882 oldintr = xsignal(SIGINT, abortpt);
1883 if ((restart_point &&
1884 (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1885 || (command("%s %s", cmd, remote) != PRELIM)) {
1886 (void)xsignal(SIGINT, oldintr);
1893 if ((restart_point &&
1894 (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1895 || (command("%s %s", cmd2, local) != PRELIM))
1901 (void)xsignal(SIGINT, oldintr);
1904 fprintf(ttyout, "local: %s remote: %s\n", local, remote);
1907 if (sigsetjmp(xferabort, 1)) {
1908 (void)xsignal(SIGINT, oldintr);
1911 (void)xsignal(SIGINT, abort_squared);
1913 if (strcmp(cmd, "RETR") && !proxy)
1915 else if (!strcmp(cmd, "RETR") && proxy)
1917 if (!cpend && !secndflag) { /* only here if cmd = "STOR" (proxy=1) */
1918 if (command("%s %s", cmd2, local) != PRELIM) {
1926 (void)xsignal(SIGINT, oldintr);
1932 if (!cpend && !secndflag) { /* only if cmd = "RETR" (proxy=1) */
1933 if (command("%s %s", cmd2, local) != PRELIM) {
1940 (void)xsignal(SIGINT, oldintr);
1948 if ((nfnd = empty(cin, NULL, 10)) <= 0) {
1950 warn("Error aborting proxy command");
1963 (void)xsignal(SIGINT, oldintr);
1967 reset(int argc, char *argv[])
1971 if (argc == 0 && argv != NULL) {
1972 UPRINTF("usage: %s\n", argv[0]);
1977 if ((nfnd = empty(cin, NULL, 0)) < 0) {
1978 warn("Error resetting connection");
1987 gunique(const char *local)
1989 static char new[MAXPATHLEN];
1990 char *cp = strrchr(local, '/');
1991 int d, count=0, len;
1996 d = access(cp == local ? "/" : cp ? local : ".", W_OK);
2000 warn("Can't access `%s'", local);
2003 len = strlcpy(new, local, sizeof(new));
2007 if (++count == 100) {
2008 fputs("runique: can't find unique file name.\n",
2018 if ((d = access(new, F_OK)) < 0)
2022 else if (*(cp - 2) == '.')
2025 *(cp - 2) = *(cp - 2) + 1;
2034 * aborts abort_remote(). lostpeer() is called because if the user is
2035 * too impatient to wait or there's another problem then ftp really
2036 * needs to get back to a known state.
2039 abort_squared(int dummy)
2046 len = strlcpy(msgbuf, "\nremote abort aborted; closing connection.\n",
2048 write(fileno(ttyout), msgbuf, len);
2050 siglongjmp(xferabort, 1);
2054 abort_remote(FILE *din)
2060 warnx("Lost control connection for abort");
2067 * send IAC in urgent mode instead of DM because 4.3BSD places oob mark
2068 * after urgent byte rather than before as is protocol now
2073 if (send(fileno(cout), buf, 3, MSG_OOB) != 3)
2074 warn("Can't send abort message");
2075 fprintf(cout, "%cABOR\r\n", DM);
2077 if ((nfnd = empty(cin, din, 10)) <= 0) {
2079 warn("Can't send abort message");
2084 if (din && (nfnd & 2)) {
2085 while (read(fileno(din), buf, BUFSIZ) > 0)
2088 if (getreply(0) == ERROR && code == 552) {
2089 /* 552 needed for nic style abort */
2096 * Ensure that ai->ai_addr is NOT an IPv4 mapped address.
2097 * IPv4 mapped address complicates too many things in FTP
2098 * protocol handling, as FTP protocol is defined differently
2099 * between IPv4 and IPv6.
2101 * This may not be the best way to handle this situation,
2102 * since the semantics of IPv4 mapped address is defined in
2103 * the kernel. There are configurations where we should use
2104 * IPv4 mapped address as native IPv6 address, not as
2105 * "an IPv6 address that embeds IPv4 address" (namely, SIIT).
2107 * More complete solution would be to have an additional
2108 * getsockopt to grab "real" peername/sockname. "real"
2109 * peername/sockname will be AF_INET if IPv4 mapped address
2110 * is used to embed IPv4 address, and will be AF_INET6 if
2111 * we use it as native. What a mess!
2114 ai_unmapped(struct addrinfo *ai)
2117 struct sockaddr_in6 *sin6;
2118 struct sockaddr_in sin;
2121 if (ai->ai_family != AF_INET6)
2123 if (ai->ai_addrlen != sizeof(struct sockaddr_in6) ||
2124 sizeof(sin) > ai->ai_addrlen)
2126 sin6 = (struct sockaddr_in6 *)ai->ai_addr;
2127 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
2130 memset(&sin, 0, sizeof(sin));
2131 sin.sin_family = AF_INET;
2132 len = sizeof(struct sockaddr_in);
2133 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
2134 sizeof(sin.sin_addr));
2135 sin.sin_port = sin6->sin6_port;
2137 ai->ai_family = AF_INET;
2138 #if defined(HAVE_STRUCT_SOCKADDR_IN_SIN_LEN)
2141 memcpy(ai->ai_addr, &sin, len);
2142 ai->ai_addrlen = len;
2150 fputs("Usage error\n", ttyout);