Make vinum use libedit instead of libreadline.
[dragonfly.git] / contrib / tnftp / ftp.c
blobb6cc64f124437d181e4f68da1df0dd1cd569e40d
1 /* $NetBSD: ftp.c,v 1.148 2007/04/18 01:50:45 lukem Exp $ */
3 /*-
4 * Copyright (c) 1996-2007 The NetBSD Foundation, Inc.
5 * All rights reserved.
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Luke Mewburn.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
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
45 * are met:
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
65 * SUCH DAMAGE.
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
74 * are met:
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
94 * SUCH DAMAGE.
97 #include <sys/cdefs.h>
98 #ifndef lint
99 #if 0
100 static char sccsid[] = "@(#)ftp.c 8.6 (Berkeley) 10/27/94";
101 #else
102 __RCSID("$NetBSD: ftp.c,v 1.148 2007/04/18 01:50:45 lukem Exp $");
103 #endif
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>
118 #include <ctype.h>
119 #include <err.h>
120 #include <errno.h>
121 #include <fcntl.h>
122 #include <netdb.h>
123 #include <stdio.h>
124 #include <stdlib.h>
125 #include <string.h>
126 #include <time.h>
127 #include <unistd.h>
128 #include <stdarg.h>
130 #include "ftp_var.h"
132 volatile sig_atomic_t abrtflag;
133 volatile sig_atomic_t timeoutflag;
135 sigjmp_buf ptabort;
136 int ptabflg;
137 int ptflag = 0;
138 char pasv[BUFSIZ]; /* passive port for proxy data connection */
140 static int empty(FILE *, FILE *, int);
142 struct sockinet {
143 union sockunion {
144 struct sockaddr_in su_sin;
145 #ifdef INET6
146 struct sockaddr_in6 su_sin6;
147 #endif
148 } si_su;
149 #if !HAVE_SOCKADDR_SA_LEN
150 int si_len;
151 #endif
154 #if !HAVE_SOCKADDR_SA_LEN
155 # define su_len si_len
156 #else
157 # define su_len si_su.su_sin.sin_len
158 #endif
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;
164 char *
165 hookup(char *host, char *port)
167 int s = -1, error, portnum;
168 struct addrinfo hints, *res, *res0;
169 char hbuf[MAXHOSTNAMELEN];
170 static char hostnamebuf[MAXHOSTNAMELEN];
171 socklen_t len;
172 int on = 1;
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);
183 if (error) {
184 warnx("Can't lookup `%s': %s", host,
185 (error == EAI_SYSTEM) ? strerror(errno)
186 : gai_strerror(error));
187 code = -1;
188 return (0);
191 if (res0->ai_canonname)
192 (void)strlcpy(hostnamebuf, res0->ai_canonname,
193 sizeof(hostnamebuf));
194 else
195 (void)strlcpy(hostnamebuf, host, sizeof(hostnamebuf));
196 hostname = hostnamebuf;
198 for (res = res0; res; res = res->ai_next) {
199 ai_unmapped(res);
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);
209 if (s < 0) {
210 warn("Can't create socket for connection to `%s'",
211 hbuf);
212 continue;
214 if (ftp_connect(s, res->ai_addr, res->ai_addrlen) < 0) {
215 close(s);
216 s = -1;
217 continue;
220 /* finally we got one */
221 break;
223 if (s < 0) {
224 warnx("Can't connect to `%s'", host);
225 code = -1;
226 freeaddrinfo(res0);
227 return 0;
229 memcpy(&hisctladdr.si_su, res->ai_addr, res->ai_addrlen);
230 hisctladdr.su_len = res->ai_addrlen;
231 freeaddrinfo(res0);
232 res0 = res = NULL;
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);
237 code = -1;
238 goto bad;
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)",
248 "IPTOS_LOWDELAY");
251 #endif
252 cin = fdopen(s, "r");
253 cout = fdopen(s, "w");
254 if (cin == NULL || cout == NULL) {
255 warnx("Can't fdopen socket");
256 if (cin)
257 (void)fclose(cin);
258 if (cout)
259 (void)fclose(cout);
260 code = -1;
261 goto bad;
263 if (verbose)
264 fprintf(ttyout, "Connected to %s.\n", hostname);
265 if (getreply(0) > 2) { /* read startup message from server */
266 if (cin)
267 (void)fclose(cin);
268 if (cout)
269 (void)fclose(cout);
270 code = -1;
271 goto bad;
274 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE,
275 (void *)&on, sizeof(on)) == -1) {
276 DWARN("setsockopt %s (ignored)", "SO_OOBINLINE");
279 return (hostname);
280 bad:
281 (void)close(s);
282 return (NULL);
285 void
286 cmdabort(int notused)
288 int oerrno = errno;
290 sigint_raised = 1;
291 alarmtimer(0);
292 if (fromatty)
293 write(fileno(ttyout), "\n", 1);
294 abrtflag++;
295 if (ptflag)
296 siglongjmp(ptabort, 1);
297 errno = oerrno;
300 void
301 cmdtimeout(int notused)
303 int oerrno = errno;
305 alarmtimer(0);
306 if (fromatty)
307 write(fileno(ttyout), "\n", 1);
308 timeoutflag++;
309 if (ptflag)
310 siglongjmp(ptabort, 1);
311 errno = oerrno;
314 /*VARARGS*/
316 command(const char *fmt, ...)
318 va_list ap;
319 int r;
320 sigfunc oldsigint;
322 #ifndef NO_DEBUG
323 if (ftp_debug) {
324 fputs("---> ", ttyout);
325 va_start(ap, fmt);
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);
330 else
331 vfprintf(ttyout, fmt, ap);
332 va_end(ap);
333 putc('\n', ttyout);
335 #endif
336 if (cout == NULL) {
337 warnx("No control connection for command");
338 code = -1;
339 return (0);
342 abrtflag = 0;
344 oldsigint = xsignal(SIGINT, cmdabort);
346 va_start(ap, fmt);
347 vfprintf(cout, fmt, ap);
348 va_end(ap);
349 fputs("\r\n", cout);
350 (void)fflush(cout);
351 cpend = 1;
352 r = getreply(!strcmp(fmt, "QUIT"));
353 if (abrtflag && oldsigint != SIG_IGN)
354 (*oldsigint)(SIGINT);
355 (void)xsignal(SIGINT, oldsigint);
356 return (r);
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 */
369 int c, n, line;
370 int dig;
371 int originalcode = 0, continuation = 0;
372 sigfunc oldsigint, oldsigalrm;
373 int pflag = 0;
374 char *cp, *pt = pasv;
376 abrtflag = 0;
377 timeoutflag = 0;
379 oldsigint = xsignal(SIGINT, cmdabort);
380 oldsigalrm = xsignal(SIGALRM, cmdtimeout);
382 for (line = 0 ;; line++) {
383 dig = n = code = 0;
384 cp = current_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)) {
389 case WILL:
390 case WONT:
391 c = getc(cin);
392 fprintf(cout, "%c%c%c", IAC, DONT, c);
393 (void)fflush(cout);
394 break;
395 case DO:
396 case DONT:
397 c = getc(cin);
398 fprintf(cout, "%c%c%c", IAC, WONT, c);
399 (void)fflush(cout);
400 break;
401 default:
402 break;
404 continue;
406 dig++;
407 if (c == EOF) {
409 * these will get trashed by pswitch()
410 * in lostpeer()
412 int reply_timeoutflag = timeoutflag;
413 int reply_abrtflag = abrtflag;
415 alarmtimer(0);
416 if (expecteof && feof(cin)) {
417 (void)xsignal(SIGINT, oldsigint);
418 (void)xsignal(SIGALRM, oldsigalrm);
419 code = 221;
420 return (0);
422 cpend = 0;
423 lostpeer(0);
424 if (verbose) {
425 size_t midx;
426 if (reply_timeoutflag)
427 midx = 0;
428 else if (reply_abrtflag)
429 midx = 1;
430 else
431 midx = 2;
432 (void)fprintf(ttyout,
433 "421 Service not available, %s.\n", m421[midx]);
434 (void)fflush(ttyout);
436 code = 421;
437 (void)xsignal(SIGINT, oldsigint);
438 (void)xsignal(SIGALRM, oldsigalrm);
439 return (4);
441 if (c != '\r' && (verbose > 0 ||
442 ((verbose > -1 && n == '5' && dig > 4) &&
443 (((!n && c < '5') || (n && n < '5'))
444 || !retry_connect)))) {
445 if (proxflag &&
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))
453 pflag = 1;
454 else if (!pflag && code == 229)
455 pflag = 100;
456 if (dig > 4 && pflag == 1 && isdigit(c))
457 pflag = 2;
458 if (pflag == 2) {
459 if (c != '\r' && c != ')') {
460 if (pt < &pasv[sizeof(pasv) - 1])
461 *pt++ = c;
462 } else {
463 *pt = '\0';
464 pflag = 3;
467 if (pflag == 100 && c == '(')
468 pflag = 2;
469 if (dig == 4 && c == '-') {
470 if (continuation)
471 code = 0;
472 continuation++;
474 if (n == 0)
475 n = c;
476 if (cp < &current_line[sizeof(current_line) - 1])
477 *cp++ = c;
479 if (verbose > 0 || ((verbose > -1 && n == '5') &&
480 (n < '5' || !retry_connect))) {
481 (void)putc(c, ttyout);
482 (void)fflush(ttyout);
484 if (cp[-1] == '\r')
485 cp[-1] = '\0';
486 *cp = '\0';
487 if (line == 0)
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)
494 originalcode = code;
495 continue;
497 if (n != '1')
498 cpend = 0;
499 alarmtimer(0);
500 (void)xsignal(SIGINT, oldsigint);
501 (void)xsignal(SIGALRM, oldsigalrm);
502 if (code == 421 || originalcode == 421)
503 lostpeer(0);
504 if (abrtflag && oldsigint != cmdabort && oldsigint != SIG_IGN)
505 (*oldsigint)(SIGINT);
506 if (timeoutflag && oldsigalrm != cmdtimeout &&
507 oldsigalrm != SIG_IGN)
508 (*oldsigalrm)(SIGINT);
509 return (n - '0');
513 static int
514 empty(FILE *cin, FILE *din, int sec)
516 int nr, nfd;
517 struct pollfd pfd[2];
519 nfd = 0;
520 if (cin) {
521 pfd[nfd].fd = fileno(cin);
522 pfd[nfd++].events = POLLIN;
525 if (din) {
526 pfd[nfd].fd = fileno(din);
527 pfd[nfd++].events = POLLIN;
530 if ((nr = ftp_poll(pfd, nfd, sec * 1000)) <= 0)
531 return nr;
533 nr = 0;
534 nfd = 0;
535 if (cin)
536 nr |= (pfd[nfd++].revents & POLLIN) ? 1 : 0;
537 if (din)
538 nr |= (pfd[nfd++].revents & POLLIN) ? 2 : 0;
539 return nr;
542 sigjmp_buf xferabort;
544 void
545 abortxfer(int notused)
547 char msgbuf[100];
548 size_t len;
550 sigint_raised = 1;
551 alarmtimer(0);
552 mflag = 0;
553 abrtflag = 0;
554 switch (direction[0]) {
555 case 'r':
556 strlcpy(msgbuf, "\nreceive", sizeof(msgbuf));
557 break;
558 case 's':
559 strlcpy(msgbuf, "\nsend", sizeof(msgbuf));
560 break;
561 default:
562 errx(1, "abortxfer: unknown direction `%s'", direction);
564 len = strlcat(msgbuf, " aborted. Waiting for remote to finish abort.\n",
565 sizeof(msgbuf));
566 write(fileno(ttyout), msgbuf, len);
567 siglongjmp(xferabort, 1);
570 void
571 sendrequest(const char *cmd, const char *local, const char *remote,
572 int printnames)
574 struct stat st;
575 int c, d;
576 FILE *volatile fin;
577 FILE *volatile dout;
578 int (*volatile closefunc)(FILE *);
579 sigfunc volatile oldintr;
580 sigfunc volatile oldintp;
581 off_t volatile hashbytes;
582 char *volatile lmode;
583 char *bufp;
584 static size_t bufsize;
585 static char *buf;
586 int oprogress;
588 hashbytes = mark;
589 direction = "sent";
590 dout = NULL;
591 bytes = 0;
592 filesize = -1;
593 oprogress = progress;
594 if (verbose && printnames) {
595 if (*local != '-')
596 fprintf(ttyout, "local: %s ", local);
597 if (remote)
598 fprintf(ttyout, "remote: %s\n", remote);
600 if (proxy) {
601 proxtrans(cmd, local, remote);
602 return;
604 if (curtype != type)
605 changetype(type, 0);
606 closefunc = NULL;
607 oldintr = NULL;
608 oldintp = NULL;
609 lmode = "w";
610 if (sigsetjmp(xferabort, 1)) {
611 while (cpend)
612 (void)getreply(0);
613 code = -1;
614 goto cleanupsend;
616 (void)xsignal(SIGQUIT, psummary);
617 oldintr = xsignal(SIGINT, abortxfer);
618 if (strcmp(local, "-") == 0) {
619 fin = stdin;
620 progress = 0;
621 } else if (*local == '|') {
622 oldintp = xsignal(SIGPIPE, SIG_IGN);
623 fin = popen(local + 1, "r");
624 if (fin == NULL) {
625 warn("Can't execute `%s'", local + 1);
626 code = -1;
627 goto cleanupsend;
629 progress = 0;
630 closefunc = pclose;
631 } else {
632 fin = fopen(local, "r");
633 if (fin == NULL) {
634 warn("Can't open `%s'", local);
635 code = -1;
636 goto cleanupsend;
638 closefunc = fclose;
639 if (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode)) {
640 fprintf(ttyout, "%s: not a plain file.\n", local);
641 code = -1;
642 goto cleanupsend;
644 filesize = st.st_size;
646 if (initconn()) {
647 code = -1;
648 goto cleanupsend;
650 if (sigsetjmp(xferabort, 1))
651 goto abort;
653 if (restart_point &&
654 (strcmp(cmd, "STOR") == 0 || strcmp(cmd, "APPE") == 0)) {
655 int rc;
657 rc = -1;
658 switch (curtype) {
659 case TYPE_A:
660 rc = fseeko(fin, restart_point, SEEK_SET);
661 break;
662 case TYPE_I:
663 case TYPE_L:
664 rc = lseek(fileno(fin), restart_point, SEEK_SET);
665 break;
667 if (rc < 0) {
668 warn("Can't seek to restart `%s'", local);
669 goto cleanupsend;
671 if (command("REST " LLF, (LLT)restart_point) != CONTINUE)
672 goto cleanupsend;
673 lmode = "r+";
675 if (remote) {
676 if (command("%s %s", cmd, remote) != PRELIM)
677 goto cleanupsend;
678 } else {
679 if (command("%s", cmd) != PRELIM)
680 goto cleanupsend;
682 dirchange = 1;
683 dout = dataconn(lmode);
684 if (dout == NULL)
685 goto abort;
687 if (sndbuf_size > bufsize) {
688 if (buf)
689 (void)free(buf);
690 bufsize = sndbuf_size;
691 buf = ftp_malloc(bufsize);
694 progressmeter(-1);
695 oldintp = xsignal(SIGPIPE, SIG_IGN);
697 switch (curtype) {
699 case TYPE_I:
700 case TYPE_L:
701 if (rate_put) { /* rate limited */
702 while (1) {
703 struct timeval then, now, td;
704 off_t bufrem;
706 (void)gettimeofday(&then, NULL);
707 errno = c = d = 0;
708 bufrem = rate_put;
709 while (bufrem > 0) {
710 if ((c = read(fileno(fin), buf,
711 MIN(bufsize, bufrem))) <= 0)
712 goto senddone;
713 bytes += c;
714 bufrem -= c;
715 for (bufp = buf; c > 0;
716 c -= d, bufp += d)
717 if ((d = write(fileno(dout),
718 bufp, c)) <= 0)
719 break;
720 if (d < 0)
721 goto senddone;
722 if (hash &&
723 (!progress || filesize < 0) ) {
724 while (bytes >= hashbytes) {
725 (void)putc('#', ttyout);
726 hashbytes += mark;
728 (void)fflush(ttyout);
731 while (1) {
732 (void)gettimeofday(&now, NULL);
733 timersub(&now, &then, &td);
734 if (td.tv_sec > 0)
735 break;
736 usleep(1000000 - td.tv_usec);
739 } else { /* simpler/faster; no rate limit */
740 while (1) {
741 errno = c = d = 0;
742 if ((c = read(fileno(fin), buf, bufsize)) <= 0)
743 goto senddone;
744 bytes += c;
745 for (bufp = buf; c > 0; c -= d, bufp += d)
746 if ((d = write(fileno(dout), bufp, c))
747 <= 0)
748 break;
749 if (d < 0)
750 goto senddone;
751 if (hash && (!progress || filesize < 0) ) {
752 while (bytes >= hashbytes) {
753 (void)putc('#', ttyout);
754 hashbytes += mark;
756 (void)fflush(ttyout);
760 senddone:
761 if (hash && (!progress || filesize < 0) && bytes > 0) {
762 if (bytes < mark)
763 (void)putc('#', ttyout);
764 (void)putc('\n', ttyout);
766 if (c < 0)
767 warn("Reading `%s'", local);
768 if (d < 0) {
769 if (errno != EPIPE)
770 warn("Writing to network");
771 bytes = -1;
773 break;
775 case TYPE_A:
776 while ((c = getc(fin)) != EOF) {
777 if (c == '\n') {
778 while (hash && (!progress || filesize < 0) &&
779 (bytes >= hashbytes)) {
780 (void)putc('#', ttyout);
781 (void)fflush(ttyout);
782 hashbytes += mark;
784 if (ferror(dout))
785 break;
786 (void)putc('\r', dout);
787 bytes++;
789 (void)putc(c, dout);
790 bytes++;
791 #if 0 /* this violates RFC */
792 if (c == '\r') {
793 (void)putc('\0', dout);
794 bytes++;
796 #endif
798 if (hash && (!progress || filesize < 0)) {
799 if (bytes < hashbytes)
800 (void)putc('#', ttyout);
801 (void)putc('\n', ttyout);
803 if (ferror(fin))
804 warn("Reading `%s'", local);
805 if (ferror(dout)) {
806 if (errno != EPIPE)
807 warn("Writing to network");
808 bytes = -1;
810 break;
813 progressmeter(1);
814 if (closefunc != NULL) {
815 (*closefunc)(fin);
816 fin = NULL;
818 (void)fclose(dout);
819 dout = NULL;
820 (void)getreply(0);
821 if (bytes > 0)
822 ptransfer(0);
823 goto cleanupsend;
825 abort:
826 (void)xsignal(SIGINT, oldintr);
827 oldintr = NULL;
828 if (!cpend) {
829 code = -1;
830 goto cleanupsend;
832 if (data >= 0) {
833 (void)close(data);
834 data = -1;
836 if (dout) {
837 (void)fclose(dout);
838 dout = NULL;
840 (void)getreply(0);
841 code = -1;
842 if (bytes > 0)
843 ptransfer(0);
845 cleanupsend:
846 if (oldintr)
847 (void)xsignal(SIGINT, oldintr);
848 if (oldintp)
849 (void)xsignal(SIGPIPE, oldintp);
850 if (data >= 0) {
851 (void)close(data);
852 data = -1;
854 if (closefunc != NULL && fin != NULL)
855 (*closefunc)(fin);
856 if (dout)
857 (void)fclose(dout);
858 progress = oprogress;
859 restart_point = 0;
860 bytes = 0;
863 void
864 recvrequest(const char *cmd, const char *volatile local, const char *remote,
865 const char *lmode, int printnames, int ignorespecial)
867 FILE *volatile fout;
868 FILE *volatile din;
869 int (*volatile closefunc)(FILE *);
870 sigfunc volatile oldintr;
871 sigfunc volatile oldintp;
872 int c, d;
873 int volatile is_retr;
874 int volatile tcrflag;
875 int volatile bare_lfs;
876 static size_t bufsize;
877 static char *buf;
878 off_t volatile hashbytes;
879 struct stat st;
880 time_t mtime;
881 struct timeval tval[2];
882 int oprogress;
883 int opreserve;
885 fout = NULL;
886 din = NULL;
887 hashbytes = mark;
888 direction = "received";
889 bytes = 0;
890 bare_lfs = 0;
891 filesize = -1;
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);
898 if (remote)
899 fprintf(ttyout, "remote: %s\n", remote);
901 if (proxy && is_retr) {
902 proxtrans(cmd, local, remote);
903 return;
905 closefunc = NULL;
906 oldintr = NULL;
907 oldintp = NULL;
908 tcrflag = !crflag && is_retr;
909 if (sigsetjmp(xferabort, 1)) {
910 while (cpend)
911 (void)getreply(0);
912 code = -1;
913 goto cleanuprecv;
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);
923 code = -1;
924 goto cleanuprecv;
926 if (dir != NULL)
927 *dir = 0;
928 d = access(dir == local ? "/" :
929 dir ? local : ".", W_OK);
930 if (dir != NULL)
931 *dir = '/';
932 if (d < 0) {
933 warn("Can't access `%s'", local);
934 code = -1;
935 goto cleanuprecv;
937 if (!runique && errno == EACCES &&
938 chmod(local, (S_IRUSR|S_IWUSR)) < 0) {
939 warn("Can't chmod `%s'", local);
940 code = -1;
941 goto cleanuprecv;
943 if (runique && errno == EACCES &&
944 (local = gunique(local)) == NULL) {
945 code = -1;
946 goto cleanuprecv;
949 else if (runique && (local = gunique(local)) == NULL) {
950 code = -1;
951 goto cleanuprecv;
954 if (!is_retr) {
955 if (curtype != TYPE_A)
956 changetype(TYPE_A, 0);
957 } else {
958 if (curtype != type)
959 changetype(type, 0);
960 filesize = remotesize(remote, 0);
961 if (code == 421 || code == -1)
962 goto cleanuprecv;
964 if (initconn()) {
965 code = -1;
966 goto cleanuprecv;
968 if (sigsetjmp(xferabort, 1))
969 goto abort;
970 if (is_retr && restart_point &&
971 command("REST " LLF, (LLT) restart_point) != CONTINUE)
972 goto cleanuprecv;
973 if (! EMPTYSTRING(remote)) {
974 if (command("%s %s", cmd, remote) != PRELIM)
975 goto cleanuprecv;
976 } else {
977 if (command("%s", cmd) != PRELIM)
978 goto cleanuprecv;
980 din = dataconn("r");
981 if (din == NULL)
982 goto abort;
983 if (!ignorespecial && strcmp(local, "-") == 0) {
984 fout = stdout;
985 progress = 0;
986 preserve = 0;
987 } else if (!ignorespecial && *local == '|') {
988 oldintp = xsignal(SIGPIPE, SIG_IGN);
989 fout = popen(local + 1, "w");
990 if (fout == NULL) {
991 warn("Can't execute `%s'", local+1);
992 goto abort;
994 progress = 0;
995 preserve = 0;
996 closefunc = pclose;
997 } else {
998 fout = fopen(local, lmode);
999 if (fout == NULL) {
1000 warn("Can't open `%s'", local);
1001 goto abort;
1003 closefunc = fclose;
1006 if (fstat(fileno(fout), &st) != -1 && !S_ISREG(st.st_mode)) {
1007 progress = 0;
1008 preserve = 0;
1010 if (rcvbuf_size > bufsize) {
1011 if (buf)
1012 (void)free(buf);
1013 bufsize = rcvbuf_size;
1014 buf = ftp_malloc(bufsize);
1017 progressmeter(-1);
1019 switch (curtype) {
1021 case TYPE_I:
1022 case TYPE_L:
1023 if (is_retr && restart_point &&
1024 lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1025 warn("Can't seek to restart `%s'", local);
1026 goto cleanuprecv;
1028 if (rate_get) { /* rate limiting */
1029 while (1) {
1030 struct timeval then, now, td;
1031 off_t bufrem;
1033 (void)gettimeofday(&then, NULL);
1034 errno = c = d = 0;
1035 for (bufrem = rate_get; bufrem > 0; ) {
1036 if ((c = read(fileno(din), buf,
1037 MIN(bufsize, bufrem))) <= 0)
1038 goto recvdone;
1039 bytes += c;
1040 bufrem -=c;
1041 if ((d = write(fileno(fout), buf, c))
1042 != c)
1043 goto recvdone;
1044 if (hash &&
1045 (!progress || filesize < 0)) {
1046 while (bytes >= hashbytes) {
1047 (void)putc('#', ttyout);
1048 hashbytes += mark;
1050 (void)fflush(ttyout);
1053 /* sleep until time is up */
1054 while (1) {
1055 (void)gettimeofday(&now, NULL);
1056 timersub(&now, &then, &td);
1057 if (td.tv_sec > 0)
1058 break;
1059 usleep(1000000 - td.tv_usec);
1062 } else { /* faster code (no limiting) */
1063 while (1) {
1064 errno = c = d = 0;
1065 if ((c = read(fileno(din), buf, bufsize)) <= 0)
1066 goto recvdone;
1067 bytes += c;
1068 if ((d = write(fileno(fout), buf, c)) != c)
1069 goto recvdone;
1070 if (hash && (!progress || filesize < 0)) {
1071 while (bytes >= hashbytes) {
1072 (void)putc('#', ttyout);
1073 hashbytes += mark;
1075 (void)fflush(ttyout);
1079 recvdone:
1080 if (hash && (!progress || filesize < 0) && bytes > 0) {
1081 if (bytes < mark)
1082 (void)putc('#', ttyout);
1083 (void)putc('\n', ttyout);
1085 if (c < 0) {
1086 if (errno != EPIPE)
1087 warn("Reading from network");
1088 bytes = -1;
1090 if (d < c) {
1091 if (d < 0)
1092 warn("Writing `%s'", local);
1093 else
1094 warnx("Writing `%s': short write", local);
1096 break;
1098 case TYPE_A:
1099 if (is_retr && restart_point) {
1100 int ch;
1101 off_t i;
1103 if (fseeko(fout, (off_t)0, SEEK_SET) < 0)
1104 goto done;
1105 for (i = 0; i++ < restart_point;) {
1106 if ((ch = getc(fout)) == EOF)
1107 goto done;
1108 if (ch == '\n')
1109 i++;
1111 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1112 done:
1113 warn("Can't seek to restart `%s'", local);
1114 goto cleanuprecv;
1117 while ((c = getc(din)) != EOF) {
1118 if (c == '\n')
1119 bare_lfs++;
1120 while (c == '\r') {
1121 while (hash && (!progress || filesize < 0) &&
1122 (bytes >= hashbytes)) {
1123 (void)putc('#', ttyout);
1124 (void)fflush(ttyout);
1125 hashbytes += mark;
1127 bytes++;
1128 if ((c = getc(din)) != '\n' || tcrflag) {
1129 if (ferror(fout))
1130 goto break2;
1131 (void)putc('\r', fout);
1132 if (c == '\0') {
1133 bytes++;
1134 goto contin2;
1136 if (c == EOF)
1137 goto contin2;
1140 (void)putc(c, fout);
1141 bytes++;
1142 contin2: ;
1144 break2:
1145 if (hash && (!progress || filesize < 0)) {
1146 if (bytes < hashbytes)
1147 (void)putc('#', ttyout);
1148 (void)putc('\n', ttyout);
1150 if (ferror(din)) {
1151 if (errno != EPIPE)
1152 warn("Reading from network");
1153 bytes = -1;
1155 if (ferror(fout))
1156 warn("Writing `%s'", local);
1157 break;
1160 progressmeter(1);
1161 if (closefunc != NULL) {
1162 (*closefunc)(fout);
1163 fout = NULL;
1165 (void)fclose(din);
1166 din = NULL;
1167 (void)getreply(0);
1168 if (bare_lfs) {
1169 fprintf(ttyout,
1170 "WARNING! %d bare linefeeds received in ASCII mode.\n",
1171 bare_lfs);
1172 fputs("File may not have transferred correctly.\n", ttyout);
1174 if (bytes >= 0 && is_retr) {
1175 if (bytes > 0)
1176 ptransfer(0);
1177 if (preserve && (closefunc == fclose)) {
1178 mtime = remotemodtime(remote, 0);
1179 if (mtime != -1) {
1180 (void)gettimeofday(&tval[0], NULL);
1181 tval[1].tv_sec = mtime;
1182 tval[1].tv_usec = 0;
1183 if (utimes(local, tval) == -1) {
1184 fprintf(ttyout,
1185 "Can't change modification time on %s to %s",
1186 local, asctime(localtime(&mtime)));
1191 goto cleanuprecv;
1193 abort:
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);
1200 if (!cpend) {
1201 code = -1;
1202 goto cleanuprecv;
1204 abort_remote(din);
1206 code = -1;
1207 if (bytes > 0)
1208 ptransfer(0);
1210 cleanuprecv:
1211 if (oldintr)
1212 (void)xsignal(SIGINT, oldintr);
1213 if (oldintp)
1214 (void)xsignal(SIGPIPE, oldintp);
1215 if (data >= 0) {
1216 (void)close(data);
1217 data = -1;
1219 if (closefunc != NULL && fout != NULL)
1220 (*closefunc)(fout);
1221 if (din)
1222 (void)fclose(din);
1223 progress = oprogress;
1224 preserve = opreserve;
1225 bytes = 0;
1229 * Need to start a listen on the data channel before we send the command,
1230 * otherwise the server's connect may fail.
1233 initconn(void)
1235 char *p, *a;
1236 int result, tmpno = 0;
1237 int on = 1;
1238 int error;
1239 unsigned int addr[16], port[2];
1240 unsigned int af, hal, pal;
1241 socklen_t len;
1242 char *pasvcmd = NULL;
1243 int overbose;
1245 #ifdef INET6
1246 #ifndef NO_DEBUG
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");
1252 #endif
1253 #endif
1255 reinit:
1256 if (passivemode) {
1257 data_addr = myctladdr;
1258 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1259 if (data < 0) {
1260 warn("Can't create socket for data connection");
1261 return (1);
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) {
1270 case AF_INET:
1271 if (epsv4 && !epsv4bad) {
1272 pasvcmd = "EPSV";
1273 overbose = verbose;
1274 if (ftp_debug == 0)
1275 verbose = -1;
1276 result = command("EPSV");
1277 verbose = overbose;
1278 if (verbose > 0 &&
1279 (result == COMPLETE || !connected))
1280 fprintf(ttyout, "%s\n", reply_string);
1281 if (!connected)
1282 return (1);
1284 * this code is to be friendly with broken
1285 * BSDI ftpd
1287 if (code / 10 == 22 && code != 229) {
1288 fputs(
1289 "wrong server: return code must be 229\n",
1290 ttyout);
1291 result = COMPLETE + 1;
1293 if (result != COMPLETE) {
1294 epsv4bad = 1;
1295 DPRINTF("disabling epsv4 for this "
1296 "connection\n");
1299 if (result != COMPLETE) {
1300 pasvcmd = "PASV";
1301 result = command("PASV");
1302 if (!connected)
1303 return (1);
1305 break;
1306 #ifdef INET6
1307 case AF_INET6:
1308 pasvcmd = "EPSV";
1309 overbose = verbose;
1310 if (ftp_debug == 0)
1311 verbose = -1;
1312 result = command("EPSV");
1313 verbose = overbose;
1314 if (verbose > 0 &&
1315 (result == COMPLETE || !connected))
1316 fprintf(ttyout, "%s\n", reply_string);
1317 if (!connected)
1318 return (1);
1319 /* this code is to be friendly with broken BSDI ftpd */
1320 if (code / 10 == 22 && code != 229) {
1321 fputs(
1322 "wrong server: return code must be 229\n",
1323 ttyout);
1324 result = COMPLETE + 1;
1326 if (result != COMPLETE) {
1327 pasvcmd = "LPSV";
1328 result = command("LPSV");
1330 if (!connected)
1331 return (1);
1332 break;
1333 #endif
1334 default:
1335 result = COMPLETE + 1;
1336 break;
1338 if (result != COMPLETE) {
1339 if (activefallback) {
1340 (void)close(data);
1341 data = -1;
1342 passivemode = 0;
1343 #if 0
1344 activefallback = 0;
1345 #endif
1346 goto reinit;
1348 fputs("Passive mode refused.\n", ttyout);
1349 goto bad;
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) {
1365 fputs(
1366 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1367 error = 1;
1368 goto bad;
1370 if (code / 10 == 22 && code != 227) {
1371 fputs("wrong server: return code must be 227\n",
1372 ttyout);
1373 error = 1;
1374 goto bad;
1376 error = sscanf(pasv, "%u,%u,%u,%u,%u,%u",
1377 &addr[0], &addr[1], &addr[2], &addr[3],
1378 &port[0], &port[1]);
1379 if (error != 6) {
1380 fputs(
1381 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1382 error = 1;
1383 goto bad;
1385 error = 0;
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",
1395 ttyout);
1396 error = 1;
1397 goto bad;
1399 switch (data_addr.su_family) {
1400 case AF_INET:
1401 error = sscanf(pasv,
1402 "%u,%u,%u,%u,%u,%u,%u,%u,%u",
1403 &af, &hal,
1404 &addr[0], &addr[1], &addr[2], &addr[3],
1405 &pal, &port[0], &port[1]);
1406 if (error != 9) {
1407 fputs(
1408 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1409 error = 1;
1410 goto bad;
1412 if (af != 4 || hal != 4 || pal != 2) {
1413 fputs(
1414 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1415 error = 1;
1416 goto bad;
1419 error = 0;
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));
1426 break;
1427 #ifdef INET6
1428 case AF_INET6:
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",
1431 &af, &hal,
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]);
1438 if (error != 21) {
1439 fputs(
1440 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1441 error = 1;
1442 goto bad;
1444 if (af != 6 || hal != 16 || pal != 2) {
1445 fputs(
1446 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1447 error = 1;
1448 goto bad;
1451 error = 0;
1452 memset(&data_addr, 0, sizeof(data_addr));
1453 data_addr.su_family = AF_INET6;
1454 data_addr.su_len = sizeof(struct sockaddr_in6);
1456 int i;
1457 for (i = 0; i < sizeof(struct in6_addr); i++) {
1458 data_addr.si_su.su_sin6.sin6_addr.s6_addr[i] =
1459 UC(addr[i]);
1462 data_addr.su_port = htons(pack2(port, 0));
1463 break;
1464 #endif
1465 default:
1466 error = 1;
1468 } else if (strcmp(pasvcmd, "EPSV") == 0) {
1469 char delim[4];
1471 port[0] = 0;
1472 if (code / 10 == 22 && code != 229) {
1473 fputs("wrong server: return code must be 229\n",
1474 ttyout);
1475 error = 1;
1476 goto bad;
1478 if (sscanf(pasv, "%c%c%c%d%c", &delim[0],
1479 &delim[1], &delim[2], &port[1],
1480 &delim[3]) != 5) {
1481 fputs("parse error!\n", ttyout);
1482 error = 1;
1483 goto bad;
1485 if (delim[0] != delim[1] || delim[0] != delim[2]
1486 || delim[0] != delim[3]) {
1487 fputs("parse error!\n", ttyout);
1488 error = 1;
1489 goto bad;
1491 data_addr = hisctladdr;
1492 data_addr.su_port = htons(port[1]);
1493 } else
1494 goto bad;
1496 if (ftp_connect(data, (struct sockaddr *)&data_addr.si_su,
1497 data_addr.su_len) < 0) {
1498 if (activefallback) {
1499 (void)close(data);
1500 data = -1;
1501 passivemode = 0;
1502 #if 0
1503 activefallback = 0;
1504 #endif
1505 goto reinit;
1507 goto bad;
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");
1518 #endif
1519 return (0);
1522 noport:
1523 data_addr = myctladdr;
1524 if (sendport)
1525 data_addr.su_port = 0; /* let system pick one */
1526 if (data != -1)
1527 (void)close(data);
1528 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1529 if (data < 0) {
1530 warn("Can't create socket for data connection");
1531 if (tmpno)
1532 sendport = 1;
1533 return (1);
1535 if (!sendport)
1536 if (setsockopt(data, SOL_SOCKET, SO_REUSEADDR,
1537 (void *)&on, sizeof(on)) == -1) {
1538 warn("Can't set SO_REUSEADDR on data connection");
1539 goto bad;
1541 if (bind(data, (struct sockaddr *)&data_addr.si_su,
1542 data_addr.su_len) < 0) {
1543 warn("Can't bind for data connection");
1544 goto bad;
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");
1555 goto bad;
1557 data_addr.su_len = len;
1558 if (ftp_listen(data, 1) < 0)
1559 warn("Can't listen to data connection");
1561 if (sendport) {
1562 char hname[NI_MAXHOST], sname[NI_MAXSERV];
1563 int af;
1564 struct sockinet tmp;
1566 switch (data_addr.su_family) {
1567 case AF_INET:
1568 if (!epsv4 || epsv4bad) {
1569 result = COMPLETE + 1;
1570 break;
1572 /* FALLTHROUGH */
1573 #ifdef INET6
1574 case AF_INET6:
1575 #endif
1576 af = (data_addr.su_family == AF_INET) ? 1 : 2;
1577 tmp = data_addr;
1578 #ifdef INET6
1579 if (tmp.su_family == AF_INET6)
1580 tmp.si_su.su_sin6.sin6_scope_id = 0;
1581 #endif
1582 if (getnameinfo((struct sockaddr *)&tmp.si_su,
1583 tmp.su_len, hname, sizeof(hname), sname,
1584 sizeof(sname), NI_NUMERICHOST | NI_NUMERICSERV)) {
1585 result = ERROR;
1586 } else {
1587 overbose = verbose;
1588 if (ftp_debug == 0)
1589 verbose = -1;
1590 result = command("EPRT |%d|%s|%s|", af, hname,
1591 sname);
1592 verbose = overbose;
1593 if (verbose > 0 &&
1594 (result == COMPLETE || !connected))
1595 fprintf(ttyout, "%s\n", reply_string);
1596 if (!connected)
1597 return (1);
1598 if (result != COMPLETE) {
1599 epsv4bad = 1;
1600 DPRINTF("disabling epsv4 for this "
1601 "connection\n");
1604 break;
1605 default:
1606 result = COMPLETE + 1;
1607 break;
1609 if (result == COMPLETE)
1610 goto skip_port;
1612 switch (data_addr.su_family) {
1613 case AF_INET:
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]));
1619 break;
1620 #ifdef INET6
1621 case AF_INET6:
1622 a = (char *)&data_addr.si_su.su_sin6.sin6_addr;
1623 p = (char *)&data_addr.su_port;
1624 result = command(
1625 "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
1626 6, 16,
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]));
1632 break;
1633 #endif
1634 default:
1635 result = COMPLETE + 1; /* xxx */
1637 if (!connected)
1638 return (1);
1639 skip_port:
1641 if (result == ERROR && sendport == -1) {
1642 sendport = 0;
1643 tmpno = 1;
1644 goto noport;
1646 return (result != COMPLETE);
1648 if (tmpno)
1649 sendport = 1;
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");
1657 #endif
1658 return (0);
1659 bad:
1660 (void)close(data);
1661 data = -1;
1662 if (tmpno)
1663 sendport = 1;
1664 return (1);
1667 FILE *
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];
1674 socklen_t fromlen;
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 */
1689 pfd[0].fd = data;
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 */
1694 do {
1695 (void)gettimeofday(&now, NULL);
1696 timersub(&endtime, &now, &td);
1697 timeout = td.tv_sec * 1000 + td.tv_usec/1000;
1698 if (timeout < 0)
1699 timeout = 0;
1700 rv = ftp_poll(pfd, 1, timeout);
1701 } while (rv == -1 && errno == EINTR); /* loop until poll ! EINTR */
1702 if (rv == -1) {
1703 warn("Can't poll waiting before accept");
1704 goto dataconn_failed;
1706 if (rv == 0) {
1707 warnx("Poll timeout waiting before accept");
1708 goto dataconn_failed;
1711 /* (non-blocking) accept the connection */
1712 fromlen = myctladdr.su_len;
1713 do {
1714 s = accept(data, (struct sockaddr *) &from.si_su, &fromlen);
1715 } while (s == -1 && errno == EINTR); /* loop until accept ! EINTR */
1716 if (s == -1) {
1717 warn("Can't accept data connection");
1718 goto dataconn_failed;
1721 (void)close(data);
1722 data = s;
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");
1734 #endif
1735 return (fdopen(data, lmode));
1737 dataconn_failed:
1738 (void)close(data);
1739 data = -1;
1740 return (NULL);
1743 void
1744 psabort(int notused)
1746 int oerrno = errno;
1748 sigint_raised = 1;
1749 alarmtimer(0);
1750 abrtflag++;
1751 errno = oerrno;
1754 void
1755 pswitch(int flag)
1757 sigfunc oldintr;
1758 static struct comvars {
1759 int connect;
1760 char name[MAXHOSTNAMELEN];
1761 struct sockinet mctl;
1762 struct sockinet hctl;
1763 FILE *in;
1764 FILE *out;
1765 int tpe;
1766 int curtpe;
1767 int cpnd;
1768 int sunqe;
1769 int runqe;
1770 int mcse;
1771 int ntflg;
1772 char nti[17];
1773 char nto[17];
1774 int mapflg;
1775 char mi[MAXPATHLEN];
1776 char mo[MAXPATHLEN];
1777 } proxstruct, tmpstruct;
1778 struct comvars *ip, *op;
1780 abrtflag = 0;
1781 oldintr = xsignal(SIGINT, psabort);
1782 if (flag) {
1783 if (proxy)
1784 return;
1785 ip = &tmpstruct;
1786 op = &proxstruct;
1787 proxy++;
1788 } else {
1789 if (!proxy)
1790 return;
1791 ip = &proxstruct;
1792 op = &tmpstruct;
1793 proxy = 0;
1795 ip->connect = connected;
1796 connected = op->connect;
1797 if (hostname)
1798 (void)strlcpy(ip->name, hostname, sizeof(ip->name));
1799 else
1800 ip->name[0] = '\0';
1801 hostname = op->name;
1802 ip->hctl = hisctladdr;
1803 hisctladdr = op->hctl;
1804 ip->mctl = myctladdr;
1805 myctladdr = op->mctl;
1806 ip->in = cin;
1807 cin = op->in;
1808 ip->out = cout;
1809 cout = op->out;
1810 ip->tpe = type;
1811 type = op->tpe;
1812 ip->curtpe = curtype;
1813 curtype = op->curtpe;
1814 ip->cpnd = cpend;
1815 cpend = op->cpnd;
1816 ip->sunqe = sunique;
1817 sunique = op->sunqe;
1818 ip->runqe = runique;
1819 runique = op->runqe;
1820 ip->mcse = mcase;
1821 mcase = op->mcse;
1822 ip->ntflg = ntflag;
1823 ntflag = op->ntflg;
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);
1835 if (abrtflag) {
1836 abrtflag = 0;
1837 (*oldintr)(SIGINT);
1841 void
1842 abortpt(int notused)
1845 sigint_raised = 1;
1846 alarmtimer(0);
1847 if (fromatty)
1848 write(fileno(ttyout), "\n", 1);
1849 ptabflg++;
1850 mflag = 0;
1851 abrtflag = 0;
1852 siglongjmp(ptabort, 1);
1855 void
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;
1863 oldintr = NULL;
1864 secndflag = 0;
1865 if (strcmp(cmd, "RETR"))
1866 cmd2 = "RETR";
1867 else
1868 cmd2 = runique ? "STOU" : "STOR";
1869 if ((prox_type = type) == 0) {
1870 if (unix_server && unix_proxy)
1871 prox_type = TYPE_I;
1872 else
1873 prox_type = TYPE_A;
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",
1879 ttyout);
1880 return;
1882 pswitch(0);
1883 if (!connected) {
1884 fputs("No primary connection.\n", ttyout);
1885 pswitch(1);
1886 code = -1;
1887 return;
1889 if (curtype != prox_type)
1890 changetype(prox_type, 1);
1891 if (command("PORT %s", pasv) != COMPLETE) {
1892 pswitch(1);
1893 return;
1895 if (sigsetjmp(ptabort, 1))
1896 goto abort;
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);
1902 pswitch(1);
1903 return;
1905 sleep(2);
1906 pswitch(1);
1907 secndflag++;
1908 if ((restart_point &&
1909 (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1910 || (command("%s %s", cmd2, local) != PRELIM))
1911 goto abort;
1912 ptflag++;
1913 (void)getreply(0);
1914 pswitch(0);
1915 (void)getreply(0);
1916 (void)xsignal(SIGINT, oldintr);
1917 pswitch(1);
1918 ptflag = 0;
1919 fprintf(ttyout, "local: %s remote: %s\n", local, remote);
1920 return;
1921 abort:
1922 if (sigsetjmp(xferabort, 1)) {
1923 (void)xsignal(SIGINT, oldintr);
1924 return;
1926 (void)xsignal(SIGINT, abort_squared);
1927 ptflag = 0;
1928 if (strcmp(cmd, "RETR") && !proxy)
1929 pswitch(1);
1930 else if (!strcmp(cmd, "RETR") && proxy)
1931 pswitch(0);
1932 if (!cpend && !secndflag) { /* only here if cmd = "STOR" (proxy=1) */
1933 if (command("%s %s", cmd2, local) != PRELIM) {
1934 pswitch(0);
1935 if (cpend)
1936 abort_remote(NULL);
1938 pswitch(1);
1939 if (ptabflg)
1940 code = -1;
1941 (void)xsignal(SIGINT, oldintr);
1942 return;
1944 if (cpend)
1945 abort_remote(NULL);
1946 pswitch(!proxy);
1947 if (!cpend && !secndflag) { /* only if cmd = "RETR" (proxy=1) */
1948 if (command("%s %s", cmd2, local) != PRELIM) {
1949 pswitch(0);
1950 if (cpend)
1951 abort_remote(NULL);
1952 pswitch(1);
1953 if (ptabflg)
1954 code = -1;
1955 (void)xsignal(SIGINT, oldintr);
1956 return;
1959 if (cpend)
1960 abort_remote(NULL);
1961 pswitch(!proxy);
1962 if (cpend) {
1963 if ((nfnd = empty(cin, NULL, 10)) <= 0) {
1964 if (nfnd < 0)
1965 warn("Error aborting proxy command");
1966 if (ptabflg)
1967 code = -1;
1968 lostpeer(0);
1970 (void)getreply(0);
1971 (void)getreply(0);
1973 if (proxy)
1974 pswitch(0);
1975 pswitch(1);
1976 if (ptabflg)
1977 code = -1;
1978 (void)xsignal(SIGINT, oldintr);
1981 void
1982 reset(int argc, char *argv[])
1984 int nfnd = 1;
1986 if (argc == 0 && argv != NULL) {
1987 UPRINTF("usage: %s\n", argv[0]);
1988 code = -1;
1989 return;
1991 while (nfnd > 0) {
1992 if ((nfnd = empty(cin, NULL, 0)) < 0) {
1993 warn("Error resetting connection");
1994 code = -1;
1995 lostpeer(0);
1996 } else if (nfnd)
1997 (void)getreply(0);
2001 char *
2002 gunique(const char *local)
2004 static char new[MAXPATHLEN];
2005 char *cp = strrchr(local, '/');
2006 int d, count=0, len;
2007 char ext = '1';
2009 if (cp)
2010 *cp = '\0';
2011 d = access(cp == local ? "/" : cp ? local : ".", W_OK);
2012 if (cp)
2013 *cp = '/';
2014 if (d < 0) {
2015 warn("Can't access `%s'", local);
2016 return (NULL);
2018 len = strlcpy(new, local, sizeof(new));
2019 cp = &new[len];
2020 *cp++ = '.';
2021 while (!d) {
2022 if (++count == 100) {
2023 fputs("runique: can't find unique file name.\n",
2024 ttyout);
2025 return (NULL);
2027 *cp++ = ext;
2028 *cp = '\0';
2029 if (ext == '9')
2030 ext = '0';
2031 else
2032 ext++;
2033 if ((d = access(new, F_OK)) < 0)
2034 break;
2035 if (ext != '0')
2036 cp--;
2037 else if (*(cp - 2) == '.')
2038 *(cp - 1) = '1';
2039 else {
2040 *(cp - 2) = *(cp - 2) + 1;
2041 cp--;
2044 return (new);
2048 * abort_squared --
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.
2053 void
2054 abort_squared(int dummy)
2056 char msgbuf[100];
2057 size_t len;
2059 sigint_raised = 1;
2060 alarmtimer(0);
2061 len = strlcpy(msgbuf, "\nremote abort aborted; closing connection.\n",
2062 sizeof(msgbuf));
2063 write(fileno(ttyout), msgbuf, len);
2064 lostpeer(0);
2065 siglongjmp(xferabort, 1);
2068 void
2069 abort_remote(FILE *din)
2071 char buf[BUFSIZ];
2072 int nfnd;
2074 if (cout == NULL) {
2075 warnx("Lost control connection for abort");
2076 if (ptabflg)
2077 code = -1;
2078 lostpeer(0);
2079 return;
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
2085 buf[0] = IAC;
2086 buf[1] = IP;
2087 buf[2] = IAC;
2088 if (send(fileno(cout), buf, 3, MSG_OOB) != 3)
2089 warn("Can't send abort message");
2090 fprintf(cout, "%cABOR\r\n", DM);
2091 (void)fflush(cout);
2092 if ((nfnd = empty(cin, din, 10)) <= 0) {
2093 if (nfnd < 0)
2094 warn("Can't send abort message");
2095 if (ptabflg)
2096 code = -1;
2097 lostpeer(0);
2099 if (din && (nfnd & 2)) {
2100 while (read(fileno(din), buf, BUFSIZ) > 0)
2101 continue;
2103 if (getreply(0) == ERROR && code == 552) {
2104 /* 552 needed for nic style abort */
2105 (void)getreply(0);
2107 (void)getreply(0);
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!
2128 void
2129 ai_unmapped(struct addrinfo *ai)
2131 #ifdef INET6
2132 struct sockaddr_in6 *sin6;
2133 struct sockaddr_in sin;
2134 socklen_t len;
2136 if (ai->ai_family != AF_INET6)
2137 return;
2138 if (ai->ai_addrlen != sizeof(struct sockaddr_in6) ||
2139 sizeof(sin) > ai->ai_addrlen)
2140 return;
2141 sin6 = (struct sockaddr_in6 *)ai->ai_addr;
2142 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
2143 return;
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
2154 sin.sin_len = len;
2155 #endif
2156 memcpy(ai->ai_addr, &sin, len);
2157 ai->ai_addrlen = len;
2158 #endif
2161 #ifdef NO_USAGE
2162 void
2163 xusage(void)
2165 fputs("Usage error\n", ttyout);
2167 #endif