1 /* $NetBSD: ftp.c,v 1.18 2009/05/20 12:53:47 lukem Exp $ */
2 /* from NetBSD: ftp.c,v 1.159 2009/04/15 03:42:33 jld Exp */
5 * Copyright (c) 1996-2009 The NetBSD Foundation, Inc.
8 * This code is derived from software contributed to The NetBSD Foundation
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
34 * Copyright (c) 1985, 1989, 1993, 1994
35 * The Regents of the University of California. All rights reserved.
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
40 * 1. Redistributions of source code must retain the above copyright
41 * notice, this list of conditions and the following disclaimer.
42 * 2. Redistributions in binary form must reproduce the above copyright
43 * notice, this list of conditions and the following disclaimer in the
44 * documentation and/or other materials provided with the distribution.
45 * 3. Neither the name of the University nor the names of its contributors
46 * may be used to endorse or promote products derived from this software
47 * without specific prior written permission.
49 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63 * Copyright (C) 1997 and 1998 WIDE Project.
64 * All rights reserved.
66 * Redistribution and use in source and binary forms, with or without
67 * modification, are permitted provided that the following conditions
69 * 1. Redistributions of source code must retain the above copyright
70 * notice, this list of conditions and the following disclaimer.
71 * 2. Redistributions in binary form must reproduce the above copyright
72 * notice, this list of conditions and the following disclaimer in the
73 * documentation and/or other materials provided with the distribution.
74 * 3. Neither the name of the project nor the names of its contributors
75 * may be used to endorse or promote products derived from this software
76 * without specific prior written permission.
78 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
79 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
81 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
82 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
83 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
84 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
85 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
86 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
87 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
92 #include <arpa/telnet.h>
96 #include <sys/cdefs.h>
99 static char sccsid[] = "@(#)ftp.c 8.6 (Berkeley) 10/27/94";
101 __RCSID(" NetBSD: ftp.c,v 1.159 2009/04/15 03:42:33 jld Exp ");
103 #endif /* not lint */
105 #include <sys/types.h>
106 #include <sys/stat.h>
107 #include <sys/socket.h>
108 #include <sys/time.h>
110 #include <netinet/in.h>
111 #include <netinet/in_systm.h>
112 #include <netinet/ip.h>
113 #include <arpa/inet.h>
114 #include <arpa/ftp.h>
115 #include <arpa/telnet.h>
133 volatile sig_atomic_t abrtflag;
134 volatile sig_atomic_t timeoutflag;
139 char pasv[BUFSIZ]; /* passive port for proxy data connection */
141 static int empty(FILE *, FILE *, int);
145 struct sockaddr_in su_sin;
147 struct sockaddr_in6 su_sin6;
150 #if !defined(HAVE_STRUCT_SOCKADDR_IN_SIN_LEN)
155 #if !defined(HAVE_STRUCT_SOCKADDR_IN_SIN_LEN)
156 # define su_len si_len
158 # define su_len si_su.su_sin.sin_len
160 #define su_family si_su.su_sin.sin_family
161 #define su_port si_su.su_sin.sin_port
163 struct sockinet myctladdr, hisctladdr, data_addr;
166 hookup(const char *host, const char *port)
169 struct addrinfo hints, *res, *res0;
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 hints.ai_flags = AI_CANONNAME;
178 hints.ai_family = family;
179 hints.ai_socktype = SOCK_STREAM;
180 hints.ai_protocol = 0;
181 error = getaddrinfo(host, port, &hints, &res0);
183 warnx("Can't lookup `%s:%s': %s", host, port,
184 (error == EAI_SYSTEM) ? strerror(errno)
185 : 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) {
198 char hname[NI_MAXHOST], sname[NI_MAXSERV];
201 if (getnameinfo(res->ai_addr, res->ai_addrlen,
202 hname, sizeof(hname), sname, sizeof(sname),
203 NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
204 strlcpy(hname, "?", sizeof(hname));
205 strlcpy(sname, "?", sizeof(sname));
207 if (verbose && res0->ai_next) {
208 /* if we have multiple possibilities */
209 fprintf(ttyout, "Trying %s:%s ...\n", hname, sname);
211 s = socket(res->ai_family, SOCK_STREAM, res->ai_protocol);
213 warn("Can't create socket for connection to `%s:%s'",
217 if (ftp_connect(s, res->ai_addr, res->ai_addrlen) < 0) {
223 /* finally we got one */
227 warnx("Can't connect to `%s:%s'", host, port);
232 memcpy(&hisctladdr.si_su, res->ai_addr, res->ai_addrlen);
233 hisctladdr.su_len = res->ai_addrlen;
237 len = hisctladdr.su_len;
238 if (getsockname(s, (struct sockaddr *)&myctladdr.si_su, &len) == -1) {
239 warn("Can't determine my address of connection to `%s:%s'",
244 myctladdr.su_len = len;
246 #ifdef IPTOS_LOWDELAY
247 if (hisctladdr.su_family == AF_INET) {
248 int tos = IPTOS_LOWDELAY;
249 if (setsockopt(s, IPPROTO_IP, IP_TOS,
250 (void *)&tos, sizeof(tos)) == -1) {
251 DWARN("setsockopt %s (ignored)",
256 cin = fdopen(s, "r");
257 cout = fdopen(s, "w");
258 if (cin == NULL || cout == NULL) {
259 warnx("Can't fdopen socket");
268 fprintf(ttyout, "Connected to %s.\n", hostname);
269 if (getreply(0) > 2) { /* read startup message from server */
278 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE,
279 (void *)&on, sizeof(on)) == -1) {
280 DWARN("setsockopt %s (ignored)", "SO_OOBINLINE");
290 cmdabort(int notused)
297 write(fileno(ttyout), "\n", 1);
300 siglongjmp(ptabort, 1);
305 cmdtimeout(int notused)
311 write(fileno(ttyout), "\n", 1);
314 siglongjmp(ptabort, 1);
320 command(const char *fmt, ...)
328 fputs("---> ", ttyout);
330 if (strncmp("PASS ", fmt, 5) == 0)
331 fputs("PASS XXXX", ttyout);
332 else if (strncmp("ACCT ", fmt, 5) == 0)
333 fputs("ACCT XXXX", ttyout);
335 vfprintf(ttyout, fmt, ap);
341 warnx("No control connection for command");
348 oldsigint = xsignal(SIGINT, cmdabort);
351 vfprintf(cout, fmt, ap);
356 r = getreply(!strcmp(fmt, "QUIT"));
357 if (abrtflag && oldsigint != SIG_IGN)
358 (*oldsigint)(SIGINT);
359 (void)xsignal(SIGINT, oldsigint);
363 static const char *m421[] = {
364 "remote server timed out. Connection closed",
365 "user interrupt. Connection closed",
366 "remote server has closed connection",
370 getreply(int expecteof)
372 char current_line[BUFSIZ]; /* last line of previous reply */
375 int originalcode = 0, continuation = 0;
376 sigfunc oldsigint, oldsigalrm;
378 char *cp, *pt = pasv;
383 oldsigint = xsignal(SIGINT, cmdabort);
384 oldsigalrm = xsignal(SIGALRM, cmdtimeout);
386 for (lineno = 0 ;; lineno++) {
389 while (alarmtimer(quit_time ? quit_time : 60),
390 ((c = getc(cin)) != '\n')) {
391 if (c == IAC) { /* handle telnet commands */
392 switch (c = getc(cin)) {
396 fprintf(cout, "%c%c%c", IAC, DONT, c);
402 fprintf(cout, "%c%c%c", IAC, WONT, c);
413 * these will get trashed by pswitch()
416 int reply_timeoutflag = timeoutflag;
417 int reply_abrtflag = abrtflag;
420 if (expecteof && feof(cin)) {
421 (void)xsignal(SIGINT, oldsigint);
422 (void)xsignal(SIGALRM, oldsigalrm);
430 if (reply_timeoutflag)
432 else if (reply_abrtflag)
436 (void)fprintf(ttyout,
437 "421 Service not available, %s.\n", m421[midx]);
438 (void)fflush(ttyout);
441 (void)xsignal(SIGINT, oldsigint);
442 (void)xsignal(SIGALRM, oldsigalrm);
445 if (c != '\r' && (verbose > 0 ||
446 ((verbose > -1 && n == '5' && dig > 4) &&
447 (((!n && c < '5') || (n && n < '5'))
448 || !retry_connect)))) {
450 (dig == 1 || (dig == 5 && verbose == 0)))
451 fprintf(ttyout, "%s:", hostname);
452 (void)putc(c, ttyout);
454 if (dig < 4 && isdigit(c))
455 code = code * 10 + (c - '0');
456 if (!pflag && (code == 227 || code == 228))
458 else if (!pflag && code == 229)
460 if (dig > 4 && pflag == 1 && isdigit(c))
463 if (c != '\r' && c != ')') {
464 if (pt < &pasv[sizeof(pasv) - 1])
471 if (pflag == 100 && c == '(')
473 if (dig == 4 && c == '-') {
480 if (cp < ¤t_line[sizeof(current_line) - 1])
483 if (verbose > 0 || ((verbose > -1 && n == '5') &&
484 (n < '5' || !retry_connect))) {
485 (void)putc(c, ttyout);
486 (void)fflush(ttyout);
492 (void)strlcpy(reply_string, current_line,
493 sizeof(reply_string));
494 if (lineno > 0 && code == 0 && reply_callback != NULL)
495 (*reply_callback)(current_line);
496 if (continuation && code != originalcode) {
497 if (originalcode == 0)
504 (void)xsignal(SIGINT, oldsigint);
505 (void)xsignal(SIGALRM, oldsigalrm);
506 if (code == 421 || originalcode == 421)
508 if (abrtflag && oldsigint != cmdabort && oldsigint != SIG_IGN)
509 (*oldsigint)(SIGINT);
510 if (timeoutflag && oldsigalrm != cmdtimeout &&
511 oldsigalrm != SIG_IGN)
512 (*oldsigalrm)(SIGINT);
518 empty(FILE *ecin, FILE *din, int sec)
521 struct pollfd pfd[2];
525 pfd[nfd].fd = fileno(ecin);
526 pfd[nfd++].events = POLLIN;
530 pfd[nfd].fd = fileno(din);
531 pfd[nfd++].events = POLLIN;
534 if ((nr = ftp_poll(pfd, nfd, sec * 1000)) <= 0)
540 nr |= (pfd[nfd++].revents & POLLIN) ? 1 : 0;
542 nr |= (pfd[nfd++].revents & POLLIN) ? 2 : 0;
546 sigjmp_buf xferabort;
549 abortxfer(int notused)
558 switch (direction[0]) {
560 strlcpy(msgbuf, "\nreceive", sizeof(msgbuf));
563 strlcpy(msgbuf, "\nsend", sizeof(msgbuf));
566 errx(1, "abortxfer: unknown direction `%s'", direction);
568 len = strlcat(msgbuf, " aborted. Waiting for remote to finish abort.\n",
570 write(fileno(ttyout), msgbuf, len);
571 siglongjmp(xferabort, 1);
575 * Read data from infd & write to outfd, using buf/bufsize as the temporary
576 * buffer, dealing with short writes.
577 * If rate_limit != 0, rate-limit the transfer.
578 * If hash_interval != 0, fputc('c', ttyout) every hash_interval bytes.
579 * Updates global variables: bytes.
580 * Returns 0 if ok, 1 if there was a read error, 2 if there was a write error.
581 * In the case of error, errno contains the appropriate error code.
584 copy_bytes(int infd, int outfd, char *buf, size_t bufsize,
585 int rate_limit, int hash_interval)
587 volatile off_t hashc;
590 struct timeval tvthen, tvnow, tvdiff;
591 off_t bufrem, bufchunk;
594 hashc = hash_interval;
596 bufchunk = rate_limit;
602 (void)gettimeofday(&tvthen, NULL);
606 /* copy bufchunk at a time */
609 inc = read(infd, buf, MIN((off_t)bufsize, bufrem));
616 outc = write(outfd, bufp, inc);
623 while (bytes >= hashc) {
624 (void)putc('#', ttyout);
625 hashc += hash_interval;
627 (void)fflush(ttyout);
630 if (rate_limit) { /* rate limited; wait if necessary */
632 (void)gettimeofday(&tvnow, NULL);
633 timersub(&tvnow, &tvthen, &tvdiff);
634 if (tvdiff.tv_sec > 0)
636 usleep(1000000 - tvdiff.tv_usec);
643 if (hash_interval && bytes > 0) {
644 if (bytes < hash_interval)
645 (void)putc('#', ttyout);
646 (void)putc('\n', ttyout);
647 (void)fflush(ttyout);
659 sendrequest(const char *cmd, const char *local, const char *remote,
666 int (*volatile closefunc)(FILE *);
667 sigfunc volatile oldintr;
668 sigfunc volatile oldintp;
669 off_t volatile hashbytes;
672 static size_t bufsize;
681 oprogress = progress;
682 if (verbose && printnames) {
684 fprintf(ttyout, "local: %s ", local);
686 fprintf(ttyout, "remote: %s\n", remote);
689 proxtrans(cmd, local, remote);
698 if (sigsetjmp(xferabort, 1)) {
704 (void)xsignal(SIGQUIT, psummary);
705 oldintr = xsignal(SIGINT, abortxfer);
706 if (strcmp(local, "-") == 0) {
709 } else if (*local == '|') {
710 oldintp = xsignal(SIGPIPE, SIG_IGN);
711 fin = popen(local + 1, "r");
713 warn("Can't execute `%s'", local + 1);
720 fin = fopen(local, "r");
722 warn("Can't open `%s'", local);
727 if (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode)) {
728 fprintf(ttyout, "%s: not a plain file.\n", local);
732 filesize = st.st_size;
738 if (sigsetjmp(xferabort, 1))
742 (strcmp(cmd, "STOR") == 0 || strcmp(cmd, "APPE") == 0)) {
748 rc = fseeko(fin, restart_point, SEEK_SET);
752 rc = lseek(fileno(fin), restart_point, SEEK_SET);
756 warn("Can't seek to restart `%s'", local);
759 if (command("REST " LLF, (LLT)restart_point) != CONTINUE)
764 if (command("%s %s", cmd, remote) != PRELIM)
767 if (command("%s", cmd) != PRELIM)
771 dout = dataconn(lmode);
775 if ((size_t)sndbuf_size > bufsize) {
778 bufsize = sndbuf_size;
779 buf = ftp_malloc(bufsize);
783 oldintp = xsignal(SIGPIPE, SIG_IGN);
784 hash_interval = (hash && (!progress || filesize < 0)) ? mark : 0;
790 c = copy_bytes(fileno(fin), fileno(dout), buf, bufsize,
791 rate_put, hash_interval);
793 warn("Reading `%s'", local);
796 warn("Writing to network");
802 while ((c = getc(fin)) != EOF) {
804 while (hash_interval && bytes >= hashbytes) {
805 (void)putc('#', ttyout);
806 (void)fflush(ttyout);
811 (void)putc('\r', dout);
816 #if 0 /* this violates RFC0959 */
818 (void)putc('\0', dout);
824 if (bytes < hashbytes)
825 (void)putc('#', ttyout);
826 (void)putc('\n', ttyout);
829 warn("Reading `%s'", local);
832 warn("Writing to network");
839 if (closefunc != NULL) {
851 (void)xsignal(SIGINT, oldintr);
872 (void)xsignal(SIGINT, oldintr);
874 (void)xsignal(SIGPIPE, oldintp);
879 if (closefunc != NULL && fin != NULL)
883 progress = oprogress;
889 recvrequest(const char *cmd, const char *volatile local, const char *remote,
890 const char *lmode, int printnames, int ignorespecial)
894 int (*volatile closefunc)(FILE *);
895 sigfunc volatile oldintr;
896 sigfunc volatile oldintp;
898 int volatile is_retr;
899 int volatile tcrflag;
900 int volatile bare_lfs;
901 static size_t bufsize;
903 off_t volatile hashbytes;
907 struct timeval tval[2];
914 direction = "received";
918 oprogress = progress;
919 opreserve = preserve;
920 is_retr = (strcmp(cmd, "RETR") == 0);
921 if (is_retr && verbose && printnames) {
922 if (ignorespecial || *local != '-')
923 fprintf(ttyout, "local: %s ", local);
925 fprintf(ttyout, "remote: %s\n", remote);
927 if (proxy && is_retr) {
928 proxtrans(cmd, local, remote);
934 tcrflag = !crflag && is_retr;
935 if (sigsetjmp(xferabort, 1)) {
941 (void)xsignal(SIGQUIT, psummary);
942 oldintr = xsignal(SIGINT, abortxfer);
943 if (ignorespecial || (strcmp(local, "-") && *local != '|')) {
944 if (access(local, W_OK) < 0) {
945 char *dir = strrchr(local, '/');
947 if (errno != ENOENT && errno != EACCES) {
948 warn("Can't access `%s'", local);
954 d = access(dir == local ? "/" :
955 dir ? local : ".", W_OK);
959 warn("Can't access `%s'", local);
963 if (!runique && errno == EACCES &&
964 chmod(local, (S_IRUSR|S_IWUSR)) < 0) {
965 warn("Can't chmod `%s'", local);
969 if (runique && errno == EACCES &&
970 (local = gunique(local)) == NULL) {
975 else if (runique && (local = gunique(local)) == NULL) {
981 if (curtype != TYPE_A)
982 changetype(TYPE_A, 0);
986 filesize = remotesize(remote, 0);
987 if (code == 421 || code == -1)
994 if (sigsetjmp(xferabort, 1))
996 if (is_retr && restart_point &&
997 command("REST " LLF, (LLT) restart_point) != CONTINUE)
999 if (! EMPTYSTRING(remote)) {
1000 if (command("%s %s", cmd, remote) != PRELIM)
1003 if (command("%s", cmd) != PRELIM)
1006 din = dataconn("r");
1009 if (!ignorespecial && strcmp(local, "-") == 0) {
1013 } else if (!ignorespecial && *local == '|') {
1014 oldintp = xsignal(SIGPIPE, SIG_IGN);
1015 fout = popen(local + 1, "w");
1017 warn("Can't execute `%s'", local+1);
1024 fout = fopen(local, lmode);
1026 warn("Can't open `%s'", local);
1032 if (fstat(fileno(fout), &st) != -1 && !S_ISREG(st.st_mode)) {
1036 if ((size_t)rcvbuf_size > bufsize) {
1039 bufsize = rcvbuf_size;
1040 buf = ftp_malloc(bufsize);
1044 hash_interval = (hash && (!progress || filesize < 0)) ? mark : 0;
1050 if (is_retr && restart_point &&
1051 lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1052 warn("Can't seek to restart `%s'", local);
1055 c = copy_bytes(fileno(din), fileno(fout), buf, bufsize,
1056 rate_get, hash_interval);
1059 warn("Reading from network");
1061 } else if (c == 2) {
1062 warn("Writing `%s'", local);
1067 if (is_retr && restart_point) {
1071 if (fseeko(fout, (off_t)0, SEEK_SET) < 0)
1073 for (i = 0; i++ < restart_point;) {
1074 if ((ch = getc(fout)) == EOF)
1079 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1081 warn("Can't seek to restart `%s'", local);
1085 while ((c = getc(din)) != EOF) {
1089 while (hash_interval && bytes >= hashbytes) {
1090 (void)putc('#', ttyout);
1091 (void)fflush(ttyout);
1095 if ((c = getc(din)) != '\n' || tcrflag) {
1098 (void)putc('\r', fout);
1107 (void)putc(c, fout);
1112 if (hash_interval) {
1113 if (bytes < hashbytes)
1114 (void)putc('#', ttyout);
1115 (void)putc('\n', ttyout);
1119 warn("Reading from network");
1123 warn("Writing `%s'", local);
1128 if (closefunc != NULL) {
1137 "WARNING! %d bare linefeeds received in ASCII mode.\n",
1139 fputs("File may not have transferred correctly.\n", ttyout);
1141 if (bytes >= 0 && is_retr) {
1144 if (preserve && (closefunc == fclose)) {
1145 mtime = remotemodtime(remote, 0);
1147 (void)gettimeofday(&tval[0], NULL);
1148 tval[1].tv_sec = mtime;
1149 tval[1].tv_usec = 0;
1150 if (utimes(local, tval) == -1) {
1152 "Can't change modification time on %s to %s",
1154 rfc2822time(localtime(&mtime)));
1163 * abort using RFC0959 recommended IP,SYNC sequence
1165 if (! sigsetjmp(xferabort, 1)) {
1166 /* this is the first call */
1167 (void)xsignal(SIGINT, abort_squared);
1180 (void)xsignal(SIGINT, oldintr);
1182 (void)xsignal(SIGPIPE, oldintp);
1187 if (closefunc != NULL && fout != NULL)
1191 progress = oprogress;
1192 preserve = opreserve;
1197 * Need to start a listen on the data channel before we send the command,
1198 * otherwise the server's connect may fail.
1204 int result, tmpno = 0;
1207 unsigned int addr[16], port[2];
1208 unsigned int af, hal, pal;
1210 const char *pasvcmd = NULL;
1215 if (myctladdr.su_family == AF_INET6 && ftp_debug &&
1216 (IN6_IS_ADDR_LINKLOCAL(&myctladdr.si_su.su_sin6.sin6_addr) ||
1217 IN6_IS_ADDR_SITELOCAL(&myctladdr.si_su.su_sin6.sin6_addr))) {
1218 warnx("Use of scoped addresses can be troublesome");
1225 data_addr = myctladdr;
1226 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1228 warn("Can't create socket for data connection");
1231 if ((options & SO_DEBUG) &&
1232 setsockopt(data, SOL_SOCKET, SO_DEBUG,
1233 (void *)&on, sizeof(on)) == -1) {
1234 DWARN("setsockopt %s (ignored)", "SO_DEBUG");
1236 result = COMPLETE + 1;
1237 switch (data_addr.su_family) {
1239 if (epsv4 && !epsv4bad) {
1244 result = command("EPSV");
1247 (result == COMPLETE || !connected))
1248 fprintf(ttyout, "%s\n", reply_string);
1252 * this code is to be friendly with broken
1255 if (code / 10 == 22 && code != 229) {
1257 "wrong server: return code must be 229\n",
1259 result = COMPLETE + 1;
1261 if (result != COMPLETE) {
1263 DPRINTF("disabling epsv4 for this "
1267 if (result != COMPLETE) {
1269 result = command("PASV");
1276 if (epsv6 && !epsv6bad) {
1281 result = command("EPSV");
1284 (result == COMPLETE || !connected))
1285 fprintf(ttyout, "%s\n", reply_string);
1289 * this code is to be friendly with
1292 if (code / 10 == 22 && code != 229) {
1294 "wrong server: return code must be 229\n",
1296 result = COMPLETE + 1;
1298 if (result != COMPLETE) {
1300 DPRINTF("disabling epsv6 for this "
1304 if (result != COMPLETE) {
1306 result = command("LPSV");
1313 result = COMPLETE + 1;
1316 if (result != COMPLETE) {
1317 if (activefallback) {
1326 fputs("Passive mode refused.\n", ttyout);
1330 #define pack2(var, off) \
1331 (((var[(off) + 0] & 0xff) << 8) | ((var[(off) + 1] & 0xff) << 0))
1332 #define pack4(var, off) \
1333 (((var[(off) + 0] & 0xff) << 24) | ((var[(off) + 1] & 0xff) << 16) | \
1334 ((var[(off) + 2] & 0xff) << 8) | ((var[(off) + 3] & 0xff) << 0))
1335 #define UC(b) (((int)b)&0xff)
1338 * What we've got at this point is a string of comma separated
1339 * one-byte unsigned integer values, separated by commas.
1341 if (strcmp(pasvcmd, "PASV") == 0) {
1342 if (data_addr.su_family != AF_INET) {
1344 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1348 if (code / 10 == 22 && code != 227) {
1349 fputs("wrong server: return code must be 227\n",
1354 error = sscanf(pasv, "%u,%u,%u,%u,%u,%u",
1355 &addr[0], &addr[1], &addr[2], &addr[3],
1356 &port[0], &port[1]);
1359 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1364 memset(&data_addr, 0, sizeof(data_addr));
1365 data_addr.su_family = AF_INET;
1366 data_addr.su_len = sizeof(struct sockaddr_in);
1367 data_addr.si_su.su_sin.sin_addr.s_addr =
1368 htonl(pack4(addr, 0));
1369 data_addr.su_port = htons(pack2(port, 0));
1370 } else if (strcmp(pasvcmd, "LPSV") == 0) {
1371 if (code / 10 == 22 && code != 228) {
1372 fputs("wrong server: return code must be 228\n",
1377 switch (data_addr.su_family) {
1379 error = sscanf(pasv,
1380 "%u,%u,%u,%u,%u,%u,%u,%u,%u",
1382 &addr[0], &addr[1], &addr[2], &addr[3],
1383 &pal, &port[0], &port[1]);
1386 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1390 if (af != 4 || hal != 4 || pal != 2) {
1392 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1398 memset(&data_addr, 0, sizeof(data_addr));
1399 data_addr.su_family = AF_INET;
1400 data_addr.su_len = sizeof(struct sockaddr_in);
1401 data_addr.si_su.su_sin.sin_addr.s_addr =
1402 htonl(pack4(addr, 0));
1403 data_addr.su_port = htons(pack2(port, 0));
1407 error = sscanf(pasv,
1408 "%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u",
1410 &addr[0], &addr[1], &addr[2], &addr[3],
1411 &addr[4], &addr[5], &addr[6], &addr[7],
1412 &addr[8], &addr[9], &addr[10],
1413 &addr[11], &addr[12], &addr[13],
1414 &addr[14], &addr[15],
1415 &pal, &port[0], &port[1]);
1418 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1422 if (af != 6 || hal != 16 || pal != 2) {
1424 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1430 memset(&data_addr, 0, sizeof(data_addr));
1431 data_addr.su_family = AF_INET6;
1432 data_addr.su_len = sizeof(struct sockaddr_in6);
1435 for (i = 0; i < sizeof(struct in6_addr); i++) {
1436 data_addr.si_su.su_sin6.sin6_addr.s6_addr[i] =
1440 data_addr.su_port = htons(pack2(port, 0));
1446 } else if (strcmp(pasvcmd, "EPSV") == 0) {
1450 if (code / 10 == 22 && code != 229) {
1451 fputs("wrong server: return code must be 229\n",
1456 if (sscanf(pasv, "%c%c%c%d%c", &delim[0],
1457 &delim[1], &delim[2], &port[1],
1459 fputs("parse error!\n", ttyout);
1463 if (delim[0] != delim[1] || delim[0] != delim[2]
1464 || delim[0] != delim[3]) {
1465 fputs("parse error!\n", ttyout);
1469 data_addr = hisctladdr;
1470 data_addr.su_port = htons(port[1]);
1474 if (ftp_connect(data, (struct sockaddr *)&data_addr.si_su,
1475 data_addr.su_len) < 0) {
1476 if (activefallback) {
1487 #ifdef IPTOS_THROUGHPUT
1488 if (data_addr.su_family == AF_INET) {
1489 on = IPTOS_THROUGHPUT;
1490 if (setsockopt(data, IPPROTO_IP, IP_TOS,
1491 (void *)&on, sizeof(on)) == -1) {
1492 DWARN("setsockopt %s (ignored)",
1493 "IPTOS_THROUGHPUT");
1501 data_addr = myctladdr;
1503 data_addr.su_port = 0; /* let system pick one */
1506 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1508 warn("Can't create socket for data connection");
1514 if (setsockopt(data, SOL_SOCKET, SO_REUSEADDR,
1515 (void *)&on, sizeof(on)) == -1) {
1516 warn("Can't set SO_REUSEADDR on data connection");
1519 if (bind(data, (struct sockaddr *)&data_addr.si_su,
1520 data_addr.su_len) < 0) {
1521 warn("Can't bind for data connection");
1524 if ((options & SO_DEBUG) &&
1525 setsockopt(data, SOL_SOCKET, SO_DEBUG,
1526 (void *)&on, sizeof(on)) == -1) {
1527 DWARN("setsockopt %s (ignored)", "SO_DEBUG");
1529 len = sizeof(data_addr.si_su);
1530 memset((char *)&data_addr, 0, sizeof (data_addr));
1531 if (getsockname(data, (struct sockaddr *)&data_addr.si_su, &len) == -1) {
1532 warn("Can't determine my address of data connection");
1535 data_addr.su_len = len;
1536 if (ftp_listen(data, 1) < 0)
1537 warn("Can't listen to data connection");
1540 char hname[NI_MAXHOST], sname[NI_MAXSERV];
1541 struct sockinet tmp;
1543 switch (data_addr.su_family) {
1545 if (!epsv4 || epsv4bad) {
1546 result = COMPLETE + 1;
1552 if (!epsv6 || epsv6bad) {
1553 result = COMPLETE + 1;
1557 af = (data_addr.su_family == AF_INET) ? 1 : 2;
1560 if (tmp.su_family == AF_INET6)
1561 tmp.si_su.su_sin6.sin6_scope_id = 0;
1563 if (getnameinfo((struct sockaddr *)&tmp.si_su,
1564 tmp.su_len, hname, sizeof(hname), sname,
1565 sizeof(sname), NI_NUMERICHOST | NI_NUMERICSERV)) {
1571 result = command("EPRT |%u|%s|%s|", af, hname,
1575 (result == COMPLETE || !connected))
1576 fprintf(ttyout, "%s\n", reply_string);
1579 if (result != COMPLETE) {
1581 DPRINTF("disabling epsv4 for this "
1587 result = COMPLETE + 1;
1590 if (result == COMPLETE)
1593 switch (data_addr.su_family) {
1595 a = (char *)&data_addr.si_su.su_sin.sin_addr;
1596 p = (char *)&data_addr.su_port;
1597 result = command("PORT %d,%d,%d,%d,%d,%d",
1598 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
1599 UC(p[0]), UC(p[1]));
1603 a = (char *)&data_addr.si_su.su_sin6.sin6_addr;
1604 p = (char *)&data_addr.su_port;
1606 "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
1608 UC(a[0]),UC(a[1]),UC(a[2]),UC(a[3]),
1609 UC(a[4]),UC(a[5]),UC(a[6]),UC(a[7]),
1610 UC(a[8]),UC(a[9]),UC(a[10]),UC(a[11]),
1611 UC(a[12]),UC(a[13]),UC(a[14]),UC(a[15]),
1612 2, UC(p[0]), UC(p[1]));
1616 result = COMPLETE + 1; /* xxx */
1622 if (result == ERROR && sendport == -1) {
1627 return (result != COMPLETE);
1631 #ifdef IPTOS_THROUGHPUT
1632 if (data_addr.su_family == AF_INET) {
1633 on = IPTOS_THROUGHPUT;
1634 if (setsockopt(data, IPPROTO_IP, IP_TOS,
1635 (void *)&on, sizeof(on)) == -1) {
1636 DWARN("setsockopt %s (ignored)", "IPTOS_THROUGHPUT");
1650 dataconn(const char *lmode)
1652 struct sockinet from;
1653 int s, flags, rv, timeout;
1654 struct timeval endtime, now, td;
1655 struct pollfd pfd[1];
1658 if (passivemode) /* passive data connection */
1659 return (fdopen(data, lmode));
1661 /* active mode data connection */
1663 if ((flags = fcntl(data, F_GETFL, 0)) == -1)
1664 goto dataconn_failed; /* get current socket flags */
1665 if (fcntl(data, F_SETFL, flags | O_NONBLOCK) == -1)
1666 goto dataconn_failed; /* set non-blocking connect */
1668 /* NOTE: we now must restore socket flags on successful exit */
1670 /* limit time waiting on listening socket */
1672 pfd[0].events = POLLIN;
1673 (void)gettimeofday(&endtime, NULL); /* determine end time */
1674 endtime.tv_sec += (quit_time > 0) ? quit_time: 60;
1675 /* without -q, default to 60s */
1677 (void)gettimeofday(&now, NULL);
1678 timersub(&endtime, &now, &td);
1679 timeout = td.tv_sec * 1000 + td.tv_usec/1000;
1682 rv = ftp_poll(pfd, 1, timeout);
1683 } while (rv == -1 && errno == EINTR); /* loop until poll ! EINTR */
1685 warn("Can't poll waiting before accept");
1686 goto dataconn_failed;
1689 warnx("Poll timeout waiting before accept");
1690 goto dataconn_failed;
1693 /* (non-blocking) accept the connection */
1694 fromlen = myctladdr.su_len;
1696 s = accept(data, (struct sockaddr *) &from.si_su, &fromlen);
1697 } while (s == -1 && errno == EINTR); /* loop until accept ! EINTR */
1699 warn("Can't accept data connection");
1700 goto dataconn_failed;
1705 if (fcntl(data, F_SETFL, flags) == -1) /* restore socket flags */
1706 goto dataconn_failed;
1708 #ifdef IPTOS_THROUGHPUT
1709 if (from.su_family == AF_INET) {
1710 int tos = IPTOS_THROUGHPUT;
1711 if (setsockopt(s, IPPROTO_IP, IP_TOS,
1712 (void *)&tos, sizeof(tos)) == -1) {
1713 DWARN("setsockopt %s (ignored)", "IPTOS_THROUGHPUT");
1717 return (fdopen(data, lmode));
1726 psabort(int notused)
1740 static struct comvars {
1742 char name[MAXHOSTNAMELEN];
1743 struct sockinet mctl;
1744 struct sockinet hctl;
1757 char mi[MAXPATHLEN];
1758 char mo[MAXPATHLEN];
1759 } proxstruct, tmpstruct;
1760 struct comvars *ip, *op;
1763 oldintr = xsignal(SIGINT, psabort);
1777 ip->connect = connected;
1778 connected = op->connect;
1780 (void)strlcpy(ip->name, hostname, sizeof(ip->name));
1783 hostname = op->name;
1784 ip->hctl = hisctladdr;
1785 hisctladdr = op->hctl;
1786 ip->mctl = myctladdr;
1787 myctladdr = op->mctl;
1794 ip->curtpe = curtype;
1795 curtype = op->curtpe;
1798 ip->sunqe = sunique;
1799 sunique = op->sunqe;
1800 ip->runqe = runique;
1801 runique = op->runqe;
1806 (void)strlcpy(ip->nti, ntin, sizeof(ip->nti));
1807 (void)strlcpy(ntin, op->nti, sizeof(ntin));
1808 (void)strlcpy(ip->nto, ntout, sizeof(ip->nto));
1809 (void)strlcpy(ntout, op->nto, sizeof(ntout));
1810 ip->mapflg = mapflag;
1811 mapflag = op->mapflg;
1812 (void)strlcpy(ip->mi, mapin, sizeof(ip->mi));
1813 (void)strlcpy(mapin, op->mi, sizeof(mapin));
1814 (void)strlcpy(ip->mo, mapout, sizeof(ip->mo));
1815 (void)strlcpy(mapout, op->mo, sizeof(mapout));
1816 (void)xsignal(SIGINT, oldintr);
1824 abortpt(int notused)
1830 write(fileno(ttyout), "\n", 1);
1834 siglongjmp(ptabort, 1);
1838 proxtrans(const char *cmd, const char *local, const char *remote)
1840 sigfunc volatile oldintr;
1841 int prox_type, nfnd;
1842 int volatile secndflag;
1843 const char *volatile cmd2;
1847 if (strcmp(cmd, "RETR"))
1850 cmd2 = runique ? "STOU" : "STOR";
1851 if ((prox_type = type) == 0) {
1852 if (unix_server && unix_proxy)
1857 if (curtype != prox_type)
1858 changetype(prox_type, 1);
1859 if (command("PASV") != COMPLETE) {
1860 fputs("proxy server does not support third party transfers.\n",
1866 fputs("No primary connection.\n", ttyout);
1871 if (curtype != prox_type)
1872 changetype(prox_type, 1);
1873 if (command("PORT %s", pasv) != COMPLETE) {
1877 if (sigsetjmp(ptabort, 1))
1879 oldintr = xsignal(SIGINT, abortpt);
1880 if ((restart_point &&
1881 (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1882 || (command("%s %s", cmd, remote) != PRELIM)) {
1883 (void)xsignal(SIGINT, oldintr);
1890 if ((restart_point &&
1891 (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1892 || (command("%s %s", cmd2, local) != PRELIM))
1898 (void)xsignal(SIGINT, oldintr);
1901 fprintf(ttyout, "local: %s remote: %s\n", local, remote);
1904 if (sigsetjmp(xferabort, 1)) {
1905 (void)xsignal(SIGINT, oldintr);
1908 (void)xsignal(SIGINT, abort_squared);
1910 if (strcmp(cmd, "RETR") && !proxy)
1912 else if (!strcmp(cmd, "RETR") && proxy)
1914 if (!cpend && !secndflag) { /* only here if cmd = "STOR" (proxy=1) */
1915 if (command("%s %s", cmd2, local) != PRELIM) {
1923 (void)xsignal(SIGINT, oldintr);
1929 if (!cpend && !secndflag) { /* only if cmd = "RETR" (proxy=1) */
1930 if (command("%s %s", cmd2, local) != PRELIM) {
1937 (void)xsignal(SIGINT, oldintr);
1945 if ((nfnd = empty(cin, NULL, 10)) <= 0) {
1947 warn("Error aborting proxy command");
1960 (void)xsignal(SIGINT, oldintr);
1964 reset(int argc, char *argv[])
1968 if (argc == 0 && argv != NULL) {
1969 UPRINTF("usage: %s\n", argv[0]);
1974 if ((nfnd = empty(cin, NULL, 0)) < 0) {
1975 warn("Error resetting connection");
1984 gunique(const char *local)
1986 static char new[MAXPATHLEN];
1987 char *cp = strrchr(local, '/');
1988 int d, count=0, len;
1993 d = access(cp == local ? "/" : cp ? local : ".", W_OK);
1997 warn("Can't access `%s'", local);
2000 len = strlcpy(new, local, sizeof(new));
2004 if (++count == 100) {
2005 fputs("runique: can't find unique file name.\n",
2015 if ((d = access(new, F_OK)) < 0)
2019 else if (*(cp - 2) == '.')
2022 *(cp - 2) = *(cp - 2) + 1;
2031 * aborts abort_remote(). lostpeer() is called because if the user is
2032 * too impatient to wait or there's another problem then ftp really
2033 * needs to get back to a known state.
2036 abort_squared(int dummy)
2043 len = strlcpy(msgbuf, "\nremote abort aborted; closing connection.\n",
2045 write(fileno(ttyout), msgbuf, len);
2047 siglongjmp(xferabort, 1);
2051 abort_remote(FILE *din)
2057 warnx("Lost control connection for abort");
2064 * send IAC in urgent mode instead of DM because 4.3BSD places oob mark
2065 * after urgent byte rather than before as is protocol now
2070 if (send(fileno(cout), buf, 3, MSG_OOB) != 3)
2071 warn("Can't send abort message");
2072 fprintf(cout, "%cABOR\r\n", DM);
2074 if ((nfnd = empty(cin, din, 10)) <= 0) {
2076 warn("Can't send abort message");
2081 if (din && (nfnd & 2)) {
2082 while (read(fileno(din), buf, BUFSIZ) > 0)
2085 if (getreply(0) == ERROR && code == 552) {
2086 /* 552 needed for nic style abort */
2093 * Ensure that ai->ai_addr is NOT an IPv4 mapped address.
2094 * IPv4 mapped address complicates too many things in FTP
2095 * protocol handling, as FTP protocol is defined differently
2096 * between IPv4 and IPv6.
2098 * This may not be the best way to handle this situation,
2099 * since the semantics of IPv4 mapped address is defined in
2100 * the kernel. There are configurations where we should use
2101 * IPv4 mapped address as native IPv6 address, not as
2102 * "an IPv6 address that embeds IPv4 address" (namely, SIIT).
2104 * More complete solution would be to have an additional
2105 * getsockopt to grab "real" peername/sockname. "real"
2106 * peername/sockname will be AF_INET if IPv4 mapped address
2107 * is used to embed IPv4 address, and will be AF_INET6 if
2108 * we use it as native. What a mess!
2111 ai_unmapped(struct addrinfo *ai)
2114 struct sockaddr_in6 *sin6;
2115 struct sockaddr_in sin;
2118 if (ai->ai_family != AF_INET6)
2120 if (ai->ai_addrlen != sizeof(struct sockaddr_in6) ||
2121 sizeof(sin) > ai->ai_addrlen)
2123 sin6 = (struct sockaddr_in6 *)ai->ai_addr;
2124 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
2127 memset(&sin, 0, sizeof(sin));
2128 sin.sin_family = AF_INET;
2129 len = sizeof(struct sockaddr_in);
2130 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
2131 sizeof(sin.sin_addr));
2132 sin.sin_port = sin6->sin6_port;
2134 ai->ai_family = AF_INET;
2135 #if defined(HAVE_STRUCT_SOCKADDR_IN_SIN_LEN)
2138 memcpy(ai->ai_addr, &sin, len);
2139 ai->ai_addrlen = len;
2147 fputs("Usage error\n", ttyout);