newfs_msdos(8): Sync with FreeBSD.
[dragonfly.git] / contrib / tnftp / src / ftp.c
blobaf236acac1d83a7bb2da61f7563093e9d31d6045
1 /* $NetBSD: ftp.c,v 1.19 2013/05/05 11:17:31 lukem Exp $ */
2 /* from NetBSD: ftp.c,v 1.164 2012/07/04 06:09:37 is Exp */
4 /*-
5 * Copyright (c) 1996-2009 The NetBSD Foundation, Inc.
6 * All rights reserved.
8 * This code is derived from software contributed to The NetBSD Foundation
9 * by Luke Mewburn.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
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
39 * are met:
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
59 * SUCH DAMAGE.
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
68 * are met:
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
88 * SUCH DAMAGE.
91 #include "tnftp.h"
92 #include <arpa/telnet.h>
94 #if 0 /* tnftp */
96 #include <sys/cdefs.h>
97 #ifndef lint
98 #if 0
99 static char sccsid[] = "@(#)ftp.c 8.6 (Berkeley) 10/27/94";
100 #else
101 __RCSID(" NetBSD: ftp.c,v 1.164 2012/07/04 06:09:37 is Exp ");
102 #endif
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>
117 #include <assert.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 #endif /* tnftp */
132 #include "ftp_var.h"
134 volatile sig_atomic_t abrtflag;
135 volatile sig_atomic_t timeoutflag;
137 sigjmp_buf ptabort;
138 int ptabflg;
139 int ptflag = 0;
140 char pasv[BUFSIZ]; /* passive port for proxy data connection */
142 static int empty(FILE *, FILE *, int);
143 __dead static void abort_squared(int);
145 struct sockinet {
146 union sockunion {
147 struct sockaddr_in su_sin;
148 #ifdef INET6
149 struct sockaddr_in6 su_sin6;
150 #endif
151 } si_su;
152 #if !defined(HAVE_STRUCT_SOCKADDR_IN_SIN_LEN)
153 int si_len;
154 #endif
157 #if !defined(HAVE_STRUCT_SOCKADDR_IN_SIN_LEN)
158 # define su_len si_len
159 #else
160 # define su_len si_su.su_sin.sin_len
161 #endif
162 #define su_family si_su.su_sin.sin_family
163 #define su_port si_su.su_sin.sin_port
165 struct sockinet myctladdr, hisctladdr, data_addr;
167 char *
168 hookup(const char *host, const char *port)
170 int s = -1, error;
171 struct addrinfo hints, *res, *res0;
172 static char hostnamebuf[MAXHOSTNAMELEN];
173 socklen_t len;
174 int on = 1;
176 memset((char *)&hisctladdr, 0, sizeof (hisctladdr));
177 memset((char *)&myctladdr, 0, sizeof (myctladdr));
178 memset(&hints, 0, sizeof(hints));
179 hints.ai_flags = AI_CANONNAME;
180 hints.ai_family = family;
181 hints.ai_socktype = SOCK_STREAM;
182 hints.ai_protocol = 0;
183 error = getaddrinfo(host, port, &hints, &res0);
184 if (error) {
185 warnx("Can't lookup `%s:%s': %s", host, port,
186 (error == EAI_SYSTEM) ? strerror(errno)
187 : gai_strerror(error));
188 code = -1;
189 return (0);
192 if (res0->ai_canonname)
193 (void)strlcpy(hostnamebuf, res0->ai_canonname,
194 sizeof(hostnamebuf));
195 else
196 (void)strlcpy(hostnamebuf, host, sizeof(hostnamebuf));
197 hostname = hostnamebuf;
199 for (res = res0; res; res = res->ai_next) {
200 char hname[NI_MAXHOST], sname[NI_MAXSERV];
202 ai_unmapped(res);
203 if (getnameinfo(res->ai_addr, res->ai_addrlen,
204 hname, sizeof(hname), sname, sizeof(sname),
205 NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
206 strlcpy(hname, "?", sizeof(hname));
207 strlcpy(sname, "?", sizeof(sname));
209 if (verbose && res0->ai_next) {
210 /* if we have multiple possibilities */
211 fprintf(ttyout, "Trying %s:%s ...\n", hname, sname);
213 s = socket(res->ai_family, SOCK_STREAM, res->ai_protocol);
214 if (s < 0) {
215 warn("Can't create socket for connection to `%s:%s'",
216 hname, sname);
217 continue;
219 if (ftp_connect(s, res->ai_addr, res->ai_addrlen,
220 verbose || !res->ai_next) < 0) {
221 close(s);
222 s = -1;
223 continue;
226 /* finally we got one */
227 break;
229 if (s < 0) {
230 warnx("Can't connect to `%s:%s'", host, port);
231 code = -1;
232 freeaddrinfo(res0);
233 return 0;
235 memcpy(&hisctladdr.si_su, res->ai_addr, res->ai_addrlen);
236 hisctladdr.su_len = res->ai_addrlen;
237 freeaddrinfo(res0);
238 res0 = res = NULL;
240 len = hisctladdr.su_len;
241 if (getsockname(s, (struct sockaddr *)&myctladdr.si_su, &len) == -1) {
242 warn("Can't determine my address of connection to `%s:%s'",
243 host, port);
244 code = -1;
245 goto bad;
247 myctladdr.su_len = len;
249 #ifdef IPTOS_LOWDELAY
250 if (hisctladdr.su_family == AF_INET) {
251 int tos = IPTOS_LOWDELAY;
252 if (setsockopt(s, IPPROTO_IP, IP_TOS,
253 (void *)&tos, sizeof(tos)) == -1) {
254 DWARN("setsockopt %s (ignored)",
255 "IPTOS_LOWDELAY");
258 #endif
259 cin = fdopen(s, "r");
260 cout = fdopen(s, "w");
261 if (cin == NULL || cout == NULL) {
262 warnx("Can't fdopen socket");
263 if (cin)
264 (void)fclose(cin);
265 if (cout)
266 (void)fclose(cout);
267 code = -1;
268 goto bad;
270 if (verbose)
271 fprintf(ttyout, "Connected to %s.\n", hostname);
272 if (getreply(0) > 2) { /* read startup message from server */
273 if (cin)
274 (void)fclose(cin);
275 if (cout)
276 (void)fclose(cout);
277 code = -1;
278 goto bad;
281 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE,
282 (void *)&on, sizeof(on)) == -1) {
283 DWARN("setsockopt %s (ignored)", "SO_OOBINLINE");
286 return (hostname);
287 bad:
288 (void)close(s);
289 return (NULL);
292 void
293 cmdabort(int notused)
295 int oerrno = errno;
297 sigint_raised = 1;
298 alarmtimer(0);
299 if (fromatty)
300 write(fileno(ttyout), "\n", 1);
301 abrtflag++;
302 if (ptflag)
303 siglongjmp(ptabort, 1);
304 errno = oerrno;
307 void
308 cmdtimeout(int notused)
310 int oerrno = errno;
312 alarmtimer(0);
313 if (fromatty)
314 write(fileno(ttyout), "\n", 1);
315 timeoutflag++;
316 if (ptflag)
317 siglongjmp(ptabort, 1);
318 errno = oerrno;
321 /*VARARGS*/
323 command(const char *fmt, ...)
325 va_list ap;
326 int r;
327 sigfunc oldsigint;
329 #ifndef NO_DEBUG
330 if (ftp_debug) {
331 fputs("---> ", ttyout);
332 va_start(ap, fmt);
333 if (strncmp("PASS ", fmt, 5) == 0)
334 fputs("PASS XXXX", ttyout);
335 else if (strncmp("ACCT ", fmt, 5) == 0)
336 fputs("ACCT XXXX", ttyout);
337 else
338 vfprintf(ttyout, fmt, ap);
339 va_end(ap);
340 putc('\n', ttyout);
342 #endif
343 if (cout == NULL) {
344 warnx("No control connection for command");
345 code = -1;
346 return (0);
349 abrtflag = 0;
351 oldsigint = xsignal(SIGINT, cmdabort);
353 va_start(ap, fmt);
354 vfprintf(cout, fmt, ap);
355 va_end(ap);
356 fputs("\r\n", cout);
357 (void)fflush(cout);
358 cpend = 1;
359 r = getreply(!strcmp(fmt, "QUIT"));
360 if (abrtflag && oldsigint != SIG_IGN)
361 (*oldsigint)(SIGINT);
362 (void)xsignal(SIGINT, oldsigint);
363 return (r);
366 static const char *m421[] = {
367 "remote server timed out. Connection closed",
368 "user interrupt. Connection closed",
369 "remote server has closed connection",
373 getreply(int expecteof)
375 char current_line[BUFSIZ]; /* last line of previous reply */
376 int c, n, lineno;
377 int dig;
378 int originalcode = 0, continuation = 0;
379 sigfunc oldsigint, oldsigalrm;
380 int pflag = 0;
381 char *cp, *pt = pasv;
383 abrtflag = 0;
384 timeoutflag = 0;
386 oldsigint = xsignal(SIGINT, cmdabort);
387 oldsigalrm = xsignal(SIGALRM, cmdtimeout);
389 for (lineno = 0 ;; lineno++) {
390 dig = n = code = 0;
391 cp = current_line;
392 while (alarmtimer(quit_time ? quit_time : 60),
393 ((c = getc(cin)) != '\n')) {
394 if (c == IAC) { /* handle telnet commands */
395 switch (c = getc(cin)) {
396 case WILL:
397 case WONT:
398 c = getc(cin);
399 fprintf(cout, "%c%c%c", IAC, DONT, c);
400 (void)fflush(cout);
401 break;
402 case DO:
403 case DONT:
404 c = getc(cin);
405 fprintf(cout, "%c%c%c", IAC, WONT, c);
406 (void)fflush(cout);
407 break;
408 default:
409 break;
411 continue;
413 dig++;
414 if (c == EOF) {
416 * these will get trashed by pswitch()
417 * in lostpeer()
419 int reply_timeoutflag = timeoutflag;
420 int reply_abrtflag = abrtflag;
422 alarmtimer(0);
423 if (expecteof && feof(cin)) {
424 (void)xsignal(SIGINT, oldsigint);
425 (void)xsignal(SIGALRM, oldsigalrm);
426 code = 221;
427 return (0);
429 cpend = 0;
430 lostpeer(0);
431 if (verbose) {
432 size_t midx;
433 if (reply_timeoutflag)
434 midx = 0;
435 else if (reply_abrtflag)
436 midx = 1;
437 else
438 midx = 2;
439 (void)fprintf(ttyout,
440 "421 Service not available, %s.\n", m421[midx]);
441 (void)fflush(ttyout);
443 code = 421;
444 (void)xsignal(SIGINT, oldsigint);
445 (void)xsignal(SIGALRM, oldsigalrm);
446 return (4);
448 if (c != '\r' && (verbose > 0 ||
449 ((verbose > -1 && n == '5' && dig > 4) &&
450 (((!n && c < '5') || (n && n < '5'))
451 || !retry_connect)))) {
452 if (proxflag &&
453 (dig == 1 || (dig == 5 && verbose == 0)))
454 fprintf(ttyout, "%s:", hostname);
455 (void)putc(c, ttyout);
457 if (dig < 4 && isdigit(c))
458 code = code * 10 + (c - '0');
459 if (!pflag && (code == 227 || code == 228))
460 pflag = 1;
461 else if (!pflag && code == 229)
462 pflag = 100;
463 if (dig > 4 && pflag == 1 && isdigit(c))
464 pflag = 2;
465 if (pflag == 2) {
466 if (c != '\r' && c != ')') {
467 if (pt < &pasv[sizeof(pasv) - 1])
468 *pt++ = c;
469 } else {
470 *pt = '\0';
471 pflag = 3;
474 if (pflag == 100 && c == '(')
475 pflag = 2;
476 if (dig == 4 && c == '-') {
477 if (continuation)
478 code = 0;
479 continuation++;
481 if (n == 0)
482 n = c;
483 if (cp < &current_line[sizeof(current_line) - 1])
484 *cp++ = c;
486 if (verbose > 0 || ((verbose > -1 && n == '5') &&
487 (n < '5' || !retry_connect))) {
488 (void)putc(c, ttyout);
489 (void)fflush(ttyout);
491 if (cp[-1] == '\r')
492 cp[-1] = '\0';
493 *cp = '\0';
494 if (lineno == 0)
495 (void)strlcpy(reply_string, current_line,
496 sizeof(reply_string));
497 if (lineno > 0 && code == 0 && reply_callback != NULL)
498 (*reply_callback)(current_line);
499 if (continuation && code != originalcode) {
500 if (originalcode == 0)
501 originalcode = code;
502 continue;
504 if (n != '1')
505 cpend = 0;
506 alarmtimer(0);
507 (void)xsignal(SIGINT, oldsigint);
508 (void)xsignal(SIGALRM, oldsigalrm);
509 if (code == 421 || originalcode == 421)
510 lostpeer(0);
511 if (abrtflag && oldsigint != cmdabort && oldsigint != SIG_IGN)
512 (*oldsigint)(SIGINT);
513 if (timeoutflag && oldsigalrm != cmdtimeout &&
514 oldsigalrm != SIG_IGN)
515 (*oldsigalrm)(SIGINT);
516 return (n - '0');
520 static int
521 empty(FILE *ecin, FILE *din, int sec)
523 int nr, nfd;
524 struct pollfd pfd[2];
526 nfd = 0;
527 if (ecin) {
528 pfd[nfd].fd = fileno(ecin);
529 pfd[nfd++].events = POLLIN;
532 if (din) {
533 pfd[nfd].fd = fileno(din);
534 pfd[nfd++].events = POLLIN;
537 if ((nr = ftp_poll(pfd, nfd, sec * 1000)) <= 0)
538 return nr;
540 nr = 0;
541 nfd = 0;
542 if (ecin)
543 nr |= (pfd[nfd++].revents & POLLIN) ? 1 : 0;
544 if (din)
545 nr |= (pfd[nfd++].revents & POLLIN) ? 2 : 0;
546 return nr;
549 sigjmp_buf xferabort;
551 __dead static void
552 abortxfer(int notused)
554 char msgbuf[100];
555 size_t len;
557 sigint_raised = 1;
558 alarmtimer(0);
559 mflag = 0;
560 abrtflag = 0;
561 switch (direction[0]) {
562 case 'r':
563 strlcpy(msgbuf, "\nreceive", sizeof(msgbuf));
564 break;
565 case 's':
566 strlcpy(msgbuf, "\nsend", sizeof(msgbuf));
567 break;
568 default:
569 errx(1, "abortxfer: unknown direction `%s'", direction);
571 len = strlcat(msgbuf, " aborted. Waiting for remote to finish abort.\n",
572 sizeof(msgbuf));
573 write(fileno(ttyout), msgbuf, len);
574 siglongjmp(xferabort, 1);
578 * Read data from infd & write to outfd, using buf/bufsize as the temporary
579 * buffer, dealing with short writes.
580 * If rate_limit != 0, rate-limit the transfer.
581 * If hash_interval != 0, fputc('c', ttyout) every hash_interval bytes.
582 * Updates global variables: bytes.
583 * Returns 0 if ok, 1 if there was a read error, 2 if there was a write error.
584 * In the case of error, errno contains the appropriate error code.
586 static int
587 copy_bytes(int infd, int outfd, char *buf, size_t bufsize,
588 int rate_limit, int hash_interval)
590 volatile off_t hashc;
591 ssize_t inc, outc;
592 char *bufp;
593 struct timeval tvthen, tvnow, tvdiff;
594 off_t bufrem, bufchunk;
595 int serr;
597 hashc = hash_interval;
598 if (rate_limit)
599 bufchunk = rate_limit;
600 else
601 bufchunk = bufsize;
603 while (1) {
604 if (rate_limit) {
605 (void)gettimeofday(&tvthen, NULL);
607 errno = 0;
608 inc = outc = 0;
609 /* copy bufchunk at a time */
610 bufrem = bufchunk;
611 while (bufrem > 0) {
612 inc = read(infd, buf, MIN((off_t)bufsize, bufrem));
613 if (inc <= 0)
614 goto copy_done;
615 bytes += inc;
616 bufrem -= inc;
617 bufp = buf;
618 while (inc > 0) {
619 outc = write(outfd, bufp, inc);
620 if (outc < 0)
621 goto copy_done;
622 inc -= outc;
623 bufp += outc;
625 if (hash_interval) {
626 while (bytes >= hashc) {
627 (void)putc('#', ttyout);
628 hashc += hash_interval;
630 (void)fflush(ttyout);
633 if (rate_limit) { /* rate limited; wait if necessary */
634 while (1) {
635 (void)gettimeofday(&tvnow, NULL);
636 timersub(&tvnow, &tvthen, &tvdiff);
637 if (tvdiff.tv_sec > 0)
638 break;
639 usleep(1000000 - tvdiff.tv_usec);
644 copy_done:
645 serr = errno;
646 if (hash_interval && bytes > 0) {
647 if (bytes < hash_interval)
648 (void)putc('#', ttyout);
649 (void)putc('\n', ttyout);
650 (void)fflush(ttyout);
652 errno = serr;
653 if (inc == -1)
654 return 1;
655 if (outc == -1)
656 return 2;
658 return 0;
661 void
662 sendrequest(const char *cmd, const char *local, const char *remote,
663 int printnames)
665 struct stat st;
666 int c;
667 FILE *volatile fin;
668 FILE *volatile dout;
669 int (*volatile closefunc)(FILE *);
670 sigfunc volatile oldintr;
671 sigfunc volatile oldintp;
672 off_t volatile hashbytes;
673 int hash_interval;
674 const char *lmode;
675 static size_t bufsize;
676 static char *buf;
677 int oprogress;
679 hashbytes = mark;
680 direction = "sent";
681 dout = NULL;
682 bytes = 0;
683 filesize = -1;
684 oprogress = progress;
685 if (verbose && printnames) {
686 if (*local != '-')
687 fprintf(ttyout, "local: %s ", local);
688 if (remote)
689 fprintf(ttyout, "remote: %s\n", remote);
691 if (proxy) {
692 proxtrans(cmd, local, remote);
693 return;
695 if (curtype != type)
696 changetype(type, 0);
697 closefunc = NULL;
698 oldintr = NULL;
699 oldintp = NULL;
700 lmode = "w";
701 if (sigsetjmp(xferabort, 1)) {
702 while (cpend)
703 (void)getreply(0);
704 code = -1;
705 goto cleanupsend;
707 (void)xsignal(SIGQUIT, psummary);
708 oldintr = xsignal(SIGINT, abortxfer);
709 if (strcmp(local, "-") == 0) {
710 fin = stdin;
711 progress = 0;
712 } else if (*local == '|') {
713 oldintp = xsignal(SIGPIPE, SIG_IGN);
714 fin = popen(local + 1, "r");
715 if (fin == NULL) {
716 warn("Can't execute `%s'", local + 1);
717 code = -1;
718 goto cleanupsend;
720 progress = 0;
721 closefunc = pclose;
722 } else {
723 fin = fopen(local, "r");
724 if (fin == NULL) {
725 warn("Can't open `%s'", local);
726 code = -1;
727 goto cleanupsend;
729 closefunc = fclose;
730 if (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode)) {
731 fprintf(ttyout, "%s: not a plain file.\n", local);
732 code = -1;
733 goto cleanupsend;
735 filesize = st.st_size;
737 if (initconn()) {
738 code = -1;
739 goto cleanupsend;
741 if (sigsetjmp(xferabort, 1))
742 goto abort;
744 if (restart_point &&
745 (strcmp(cmd, "STOR") == 0 || strcmp(cmd, "APPE") == 0)) {
746 int rc;
748 rc = -1;
749 switch (curtype) {
750 case TYPE_A:
751 rc = fseeko(fin, restart_point, SEEK_SET);
752 break;
753 case TYPE_I:
754 case TYPE_L:
755 rc = lseek(fileno(fin), restart_point, SEEK_SET);
756 break;
758 if (rc < 0) {
759 warn("Can't seek to restart `%s'", local);
760 goto cleanupsend;
762 if (command("REST " LLF, (LLT)restart_point) != CONTINUE)
763 goto cleanupsend;
764 lmode = "r+";
766 if (remote) {
767 if (command("%s %s", cmd, remote) != PRELIM)
768 goto cleanupsend;
769 } else {
770 if (command("%s", cmd) != PRELIM)
771 goto cleanupsend;
773 dirchange = 1;
774 dout = dataconn(lmode);
775 if (dout == NULL)
776 goto abort;
778 assert(sndbuf_size > 0);
779 if ((size_t)sndbuf_size > bufsize) {
780 if (buf)
781 (void)free(buf);
782 bufsize = sndbuf_size;
783 buf = ftp_malloc(bufsize);
786 progressmeter(-1);
787 oldintp = xsignal(SIGPIPE, SIG_IGN);
788 hash_interval = (hash && (!progress || filesize < 0)) ? mark : 0;
790 switch (curtype) {
792 case TYPE_I:
793 case TYPE_L:
794 c = copy_bytes(fileno(fin), fileno(dout), buf, bufsize,
795 rate_put, hash_interval);
796 if (c == 1) {
797 warn("Reading `%s'", local);
798 } else if (c == 2) {
799 if (errno != EPIPE)
800 warn("Writing to network");
801 bytes = -1;
803 break;
805 case TYPE_A:
806 while ((c = getc(fin)) != EOF) {
807 if (c == '\n') {
808 while (hash_interval && bytes >= hashbytes) {
809 (void)putc('#', ttyout);
810 (void)fflush(ttyout);
811 hashbytes += mark;
813 if (ferror(dout))
814 break;
815 (void)putc('\r', dout);
816 bytes++;
818 (void)putc(c, dout);
819 bytes++;
820 #if 0 /* this violates RFC 959 */
821 if (c == '\r') {
822 (void)putc('\0', dout);
823 bytes++;
825 #endif
827 if (hash_interval) {
828 if (bytes < hashbytes)
829 (void)putc('#', ttyout);
830 (void)putc('\n', ttyout);
832 if (ferror(fin))
833 warn("Reading `%s'", local);
834 if (ferror(dout)) {
835 if (errno != EPIPE)
836 warn("Writing to network");
837 bytes = -1;
839 break;
842 progressmeter(1);
843 if (closefunc != NULL) {
844 (*closefunc)(fin);
845 fin = NULL;
847 (void)fclose(dout);
848 dout = NULL;
849 (void)getreply(0);
850 if (bytes > 0)
851 ptransfer(0);
852 goto cleanupsend;
854 abort:
855 (void)xsignal(SIGINT, oldintr);
856 oldintr = NULL;
857 if (!cpend) {
858 code = -1;
859 goto cleanupsend;
861 if (data >= 0) {
862 (void)close(data);
863 data = -1;
865 if (dout) {
866 (void)fclose(dout);
867 dout = NULL;
869 (void)getreply(0);
870 code = -1;
871 if (bytes > 0)
872 ptransfer(0);
874 cleanupsend:
875 if (oldintr)
876 (void)xsignal(SIGINT, oldintr);
877 if (oldintp)
878 (void)xsignal(SIGPIPE, oldintp);
879 if (data >= 0) {
880 (void)close(data);
881 data = -1;
883 if (closefunc != NULL && fin != NULL)
884 (*closefunc)(fin);
885 if (dout)
886 (void)fclose(dout);
887 progress = oprogress;
888 restart_point = 0;
889 bytes = 0;
892 void
893 recvrequest(const char *cmd, const char *volatile local, const char *remote,
894 const char *lmode, int printnames, int ignorespecial)
896 FILE *volatile fout;
897 FILE *volatile din;
898 int (*volatile closefunc)(FILE *);
899 sigfunc volatile oldintr;
900 sigfunc volatile oldintp;
901 int c, d;
902 int volatile is_retr;
903 int volatile tcrflag;
904 int volatile bare_lfs;
905 static size_t bufsize;
906 static char *buf;
907 off_t volatile hashbytes;
908 int hash_interval;
909 struct stat st;
910 time_t mtime;
911 struct timeval tval[2];
912 int oprogress;
913 int opreserve;
915 fout = NULL;
916 din = NULL;
917 hashbytes = mark;
918 direction = "received";
919 bytes = 0;
920 bare_lfs = 0;
921 filesize = -1;
922 oprogress = progress;
923 opreserve = preserve;
924 is_retr = (strcmp(cmd, "RETR") == 0);
925 if (is_retr && verbose && printnames) {
926 if (ignorespecial || *local != '-')
927 fprintf(ttyout, "local: %s ", local);
928 if (remote)
929 fprintf(ttyout, "remote: %s\n", remote);
931 if (proxy && is_retr) {
932 proxtrans(cmd, local, remote);
933 return;
935 closefunc = NULL;
936 oldintr = NULL;
937 oldintp = NULL;
938 tcrflag = !crflag && is_retr;
939 if (sigsetjmp(xferabort, 1)) {
940 while (cpend)
941 (void)getreply(0);
942 code = -1;
943 goto cleanuprecv;
945 (void)xsignal(SIGQUIT, psummary);
946 oldintr = xsignal(SIGINT, abortxfer);
947 if (ignorespecial || (strcmp(local, "-") && *local != '|')) {
948 if (access(local, W_OK) < 0) {
949 char *dir = strrchr(local, '/');
951 if (errno != ENOENT && errno != EACCES) {
952 warn("Can't access `%s'", local);
953 code = -1;
954 goto cleanuprecv;
956 if (dir != NULL)
957 *dir = 0;
958 d = access(dir == local ? "/" :
959 dir ? local : ".", W_OK);
960 if (dir != NULL)
961 *dir = '/';
962 if (d < 0) {
963 warn("Can't access `%s'", local);
964 code = -1;
965 goto cleanuprecv;
967 if (!runique && errno == EACCES &&
968 chmod(local, (S_IRUSR|S_IWUSR)) < 0) {
969 warn("Can't chmod `%s'", local);
970 code = -1;
971 goto cleanuprecv;
973 if (runique && errno == EACCES &&
974 (local = gunique(local)) == NULL) {
975 code = -1;
976 goto cleanuprecv;
979 else if (runique && (local = gunique(local)) == NULL) {
980 code = -1;
981 goto cleanuprecv;
984 if (!is_retr) {
985 if (curtype != TYPE_A)
986 changetype(TYPE_A, 0);
987 } else {
988 if (curtype != type)
989 changetype(type, 0);
990 filesize = remotesize(remote, 0);
991 if (code == 421 || code == -1)
992 goto cleanuprecv;
994 if (initconn()) {
995 code = -1;
996 goto cleanuprecv;
998 if (sigsetjmp(xferabort, 1))
999 goto abort;
1000 if (is_retr && restart_point &&
1001 command("REST " LLF, (LLT) restart_point) != CONTINUE)
1002 goto cleanuprecv;
1003 if (! EMPTYSTRING(remote)) {
1004 if (command("%s %s", cmd, remote) != PRELIM)
1005 goto cleanuprecv;
1006 } else {
1007 if (command("%s", cmd) != PRELIM)
1008 goto cleanuprecv;
1010 din = dataconn("r");
1011 if (din == NULL)
1012 goto abort;
1013 if (!ignorespecial && strcmp(local, "-") == 0) {
1014 fout = stdout;
1015 progress = 0;
1016 preserve = 0;
1017 } else if (!ignorespecial && *local == '|') {
1018 oldintp = xsignal(SIGPIPE, SIG_IGN);
1019 fout = popen(local + 1, "w");
1020 if (fout == NULL) {
1021 warn("Can't execute `%s'", local+1);
1022 goto abort;
1024 progress = 0;
1025 preserve = 0;
1026 closefunc = pclose;
1027 } else {
1028 fout = fopen(local, lmode);
1029 if (fout == NULL) {
1030 warn("Can't open `%s'", local);
1031 goto abort;
1033 closefunc = fclose;
1036 if (fstat(fileno(fout), &st) != -1 && !S_ISREG(st.st_mode)) {
1037 progress = 0;
1038 preserve = 0;
1040 assert(rcvbuf_size > 0);
1041 if ((size_t)rcvbuf_size > bufsize) {
1042 if (buf)
1043 (void)free(buf);
1044 bufsize = rcvbuf_size;
1045 buf = ftp_malloc(bufsize);
1048 progressmeter(-1);
1049 hash_interval = (hash && (!progress || filesize < 0)) ? mark : 0;
1051 switch (curtype) {
1053 case TYPE_I:
1054 case TYPE_L:
1055 if (is_retr && restart_point &&
1056 lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1057 warn("Can't seek to restart `%s'", local);
1058 goto cleanuprecv;
1060 c = copy_bytes(fileno(din), fileno(fout), buf, bufsize,
1061 rate_get, hash_interval);
1062 if (c == 1) {
1063 if (errno != EPIPE)
1064 warn("Reading from network");
1065 bytes = -1;
1066 } else if (c == 2) {
1067 warn("Writing `%s'", local);
1069 break;
1071 case TYPE_A:
1072 if (is_retr && restart_point) {
1073 int ch;
1074 off_t i;
1076 if (fseeko(fout, (off_t)0, SEEK_SET) < 0)
1077 goto done;
1078 for (i = 0; i++ < restart_point;) {
1079 if ((ch = getc(fout)) == EOF)
1080 goto done;
1081 if (ch == '\n')
1082 i++;
1084 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1085 done:
1086 warn("Can't seek to restart `%s'", local);
1087 goto cleanuprecv;
1090 while ((c = getc(din)) != EOF) {
1091 if (c == '\n')
1092 bare_lfs++;
1093 while (c == '\r') {
1094 while (hash_interval && bytes >= hashbytes) {
1095 (void)putc('#', ttyout);
1096 (void)fflush(ttyout);
1097 hashbytes += mark;
1099 bytes++;
1100 if ((c = getc(din)) != '\n' || tcrflag) {
1101 if (ferror(fout))
1102 goto break2;
1103 (void)putc('\r', fout);
1104 if (c == '\0') {
1105 bytes++;
1106 goto contin2;
1108 if (c == EOF)
1109 goto contin2;
1112 (void)putc(c, fout);
1113 bytes++;
1114 contin2: ;
1116 break2:
1117 if (hash_interval) {
1118 if (bytes < hashbytes)
1119 (void)putc('#', ttyout);
1120 (void)putc('\n', ttyout);
1122 if (ferror(din)) {
1123 if (errno != EPIPE)
1124 warn("Reading from network");
1125 bytes = -1;
1127 if (ferror(fout))
1128 warn("Writing `%s'", local);
1129 break;
1132 progressmeter(1);
1133 if (closefunc != NULL) {
1134 (*closefunc)(fout);
1135 fout = NULL;
1137 (void)fclose(din);
1138 din = NULL;
1139 (void)getreply(0);
1140 if (bare_lfs) {
1141 fprintf(ttyout,
1142 "WARNING! %d bare linefeeds received in ASCII mode.\n",
1143 bare_lfs);
1144 fputs("File may not have transferred correctly.\n", ttyout);
1146 if (bytes >= 0 && is_retr) {
1147 if (bytes > 0)
1148 ptransfer(0);
1149 if (preserve && (closefunc == fclose)) {
1150 mtime = remotemodtime(remote, 0);
1151 if (mtime != -1) {
1152 (void)gettimeofday(&tval[0], NULL);
1153 tval[1].tv_sec = mtime;
1154 tval[1].tv_usec = 0;
1155 if (utimes(local, tval) == -1) {
1156 fprintf(ttyout,
1157 "Can't change modification time on %s to %s",
1158 local,
1159 rfc2822time(localtime(&mtime)));
1164 goto cleanuprecv;
1166 abort:
1168 * abort using RFC 959 recommended IP,SYNC sequence
1170 if (! sigsetjmp(xferabort, 1)) {
1171 /* this is the first call */
1172 (void)xsignal(SIGINT, abort_squared);
1173 if (!cpend) {
1174 code = -1;
1175 goto cleanuprecv;
1177 abort_remote(din);
1179 code = -1;
1180 if (bytes > 0)
1181 ptransfer(0);
1183 cleanuprecv:
1184 if (oldintr)
1185 (void)xsignal(SIGINT, oldintr);
1186 if (oldintp)
1187 (void)xsignal(SIGPIPE, oldintp);
1188 if (data >= 0) {
1189 (void)close(data);
1190 data = -1;
1192 if (closefunc != NULL && fout != NULL)
1193 (*closefunc)(fout);
1194 if (din)
1195 (void)fclose(din);
1196 progress = oprogress;
1197 preserve = opreserve;
1198 bytes = 0;
1202 * Need to start a listen on the data channel before we send the command,
1203 * otherwise the server's connect may fail.
1206 initconn(void)
1208 char *p, *a;
1209 int result, tmpno = 0;
1210 int on = 1;
1211 int error;
1212 unsigned int addr[16], port[2];
1213 unsigned int af, hal, pal;
1214 socklen_t len;
1215 const char *pasvcmd = NULL;
1216 int overbose;
1218 #ifdef INET6
1219 #ifndef NO_DEBUG
1220 if (myctladdr.su_family == AF_INET6 && ftp_debug &&
1221 (IN6_IS_ADDR_LINKLOCAL(&myctladdr.si_su.su_sin6.sin6_addr) ||
1222 IN6_IS_ADDR_SITELOCAL(&myctladdr.si_su.su_sin6.sin6_addr))) {
1223 warnx("Use of scoped addresses can be troublesome");
1225 #endif
1226 #endif
1228 reinit:
1229 if (passivemode) {
1230 data_addr = myctladdr;
1231 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1232 if (data < 0) {
1233 warn("Can't create socket for data connection");
1234 return (1);
1236 if ((options & SO_DEBUG) &&
1237 setsockopt(data, SOL_SOCKET, SO_DEBUG,
1238 (void *)&on, sizeof(on)) == -1) {
1239 DWARN("setsockopt %s (ignored)", "SO_DEBUG");
1241 result = COMPLETE + 1;
1242 switch (data_addr.su_family) {
1243 case AF_INET:
1244 if (epsv4 && !epsv4bad) {
1245 pasvcmd = "EPSV";
1246 overbose = verbose;
1247 if (ftp_debug == 0)
1248 verbose = -1;
1249 result = command("EPSV");
1250 verbose = overbose;
1251 if (verbose > 0 &&
1252 (result == COMPLETE || !connected))
1253 fprintf(ttyout, "%s\n", reply_string);
1254 if (!connected)
1255 return (1);
1257 * this code is to be friendly with broken
1258 * BSDI ftpd
1260 if (code / 10 == 22 && code != 229) {
1261 fputs(
1262 "wrong server: return code must be 229\n",
1263 ttyout);
1264 result = COMPLETE + 1;
1266 if (result != COMPLETE) {
1267 epsv4bad = 1;
1268 DPRINTF("disabling epsv4 for this "
1269 "connection\n");
1272 if (result != COMPLETE) {
1273 pasvcmd = "PASV";
1274 result = command("PASV");
1275 if (!connected)
1276 return (1);
1278 break;
1279 #ifdef INET6
1280 case AF_INET6:
1281 if (epsv6 && !epsv6bad) {
1282 pasvcmd = "EPSV";
1283 overbose = verbose;
1284 if (ftp_debug == 0)
1285 verbose = -1;
1286 result = command("EPSV");
1287 verbose = overbose;
1288 if (verbose > 0 &&
1289 (result == COMPLETE || !connected))
1290 fprintf(ttyout, "%s\n", reply_string);
1291 if (!connected)
1292 return (1);
1294 * this code is to be friendly with
1295 * broken BSDI ftpd
1297 if (code / 10 == 22 && code != 229) {
1298 fputs(
1299 "wrong server: return code must be 229\n",
1300 ttyout);
1301 result = COMPLETE + 1;
1303 if (result != COMPLETE) {
1304 epsv6bad = 1;
1305 DPRINTF("disabling epsv6 for this "
1306 "connection\n");
1309 if (result != COMPLETE) {
1310 pasvcmd = "LPSV";
1311 result = command("LPSV");
1313 if (!connected)
1314 return (1);
1315 break;
1316 #endif
1317 default:
1318 result = COMPLETE + 1;
1319 break;
1321 if (result != COMPLETE) {
1322 if (activefallback) {
1323 (void)close(data);
1324 data = -1;
1325 passivemode = 0;
1326 #if 0
1327 activefallback = 0;
1328 #endif
1329 goto reinit;
1331 fputs("Passive mode refused.\n", ttyout);
1332 goto bad;
1335 #define pack2(var, off) \
1336 (((var[(off) + 0] & 0xff) << 8) | ((var[(off) + 1] & 0xff) << 0))
1337 #define pack4(var, off) \
1338 (((var[(off) + 0] & 0xff) << 24) | ((var[(off) + 1] & 0xff) << 16) | \
1339 ((var[(off) + 2] & 0xff) << 8) | ((var[(off) + 3] & 0xff) << 0))
1340 #define UC(b) (((int)b)&0xff)
1343 * What we've got at this point is a string of comma separated
1344 * one-byte unsigned integer values, separated by commas.
1346 if (strcmp(pasvcmd, "PASV") == 0) {
1347 if (data_addr.su_family != AF_INET) {
1348 fputs(
1349 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1350 error = 1;
1351 goto bad;
1353 if (code / 10 == 22 && code != 227) {
1354 fputs("wrong server: return code must be 227\n",
1355 ttyout);
1356 error = 1;
1357 goto bad;
1359 error = sscanf(pasv, "%u,%u,%u,%u,%u,%u",
1360 &addr[0], &addr[1], &addr[2], &addr[3],
1361 &port[0], &port[1]);
1362 if (error != 6) {
1363 fputs(
1364 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1365 error = 1;
1366 goto bad;
1368 error = 0;
1369 memset(&data_addr, 0, sizeof(data_addr));
1370 data_addr.su_family = AF_INET;
1371 data_addr.su_len = sizeof(struct sockaddr_in);
1372 data_addr.si_su.su_sin.sin_addr.s_addr =
1373 htonl(pack4(addr, 0));
1374 data_addr.su_port = htons(pack2(port, 0));
1375 } else if (strcmp(pasvcmd, "LPSV") == 0) {
1376 if (code / 10 == 22 && code != 228) {
1377 fputs("wrong server: return code must be 228\n",
1378 ttyout);
1379 error = 1;
1380 goto bad;
1382 switch (data_addr.su_family) {
1383 case AF_INET:
1384 error = sscanf(pasv,
1385 "%u,%u,%u,%u,%u,%u,%u,%u,%u",
1386 &af, &hal,
1387 &addr[0], &addr[1], &addr[2], &addr[3],
1388 &pal, &port[0], &port[1]);
1389 if (error != 9) {
1390 fputs(
1391 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1392 error = 1;
1393 goto bad;
1395 if (af != 4 || hal != 4 || pal != 2) {
1396 fputs(
1397 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1398 error = 1;
1399 goto bad;
1402 error = 0;
1403 memset(&data_addr, 0, sizeof(data_addr));
1404 data_addr.su_family = AF_INET;
1405 data_addr.su_len = sizeof(struct sockaddr_in);
1406 data_addr.si_su.su_sin.sin_addr.s_addr =
1407 htonl(pack4(addr, 0));
1408 data_addr.su_port = htons(pack2(port, 0));
1409 break;
1410 #ifdef INET6
1411 case AF_INET6:
1412 error = sscanf(pasv,
1413 "%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u",
1414 &af, &hal,
1415 &addr[0], &addr[1], &addr[2], &addr[3],
1416 &addr[4], &addr[5], &addr[6], &addr[7],
1417 &addr[8], &addr[9], &addr[10],
1418 &addr[11], &addr[12], &addr[13],
1419 &addr[14], &addr[15],
1420 &pal, &port[0], &port[1]);
1421 if (error != 21) {
1422 fputs(
1423 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1424 error = 1;
1425 goto bad;
1427 if (af != 6 || hal != 16 || pal != 2) {
1428 fputs(
1429 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1430 error = 1;
1431 goto bad;
1434 error = 0;
1435 memset(&data_addr, 0, sizeof(data_addr));
1436 data_addr.su_family = AF_INET6;
1437 data_addr.su_len = sizeof(struct sockaddr_in6);
1439 size_t i;
1440 for (i = 0; i < sizeof(struct in6_addr); i++) {
1441 data_addr.si_su.su_sin6.sin6_addr.s6_addr[i] =
1442 UC(addr[i]);
1445 data_addr.su_port = htons(pack2(port, 0));
1446 break;
1447 #endif
1448 default:
1449 error = 1;
1451 } else if (strcmp(pasvcmd, "EPSV") == 0) {
1452 char delim[4];
1454 port[0] = 0;
1455 if (code / 10 == 22 && code != 229) {
1456 fputs("wrong server: return code must be 229\n",
1457 ttyout);
1458 error = 1;
1459 goto bad;
1461 if (sscanf(pasv, "%c%c%c%d%c", &delim[0],
1462 &delim[1], &delim[2], &port[1],
1463 &delim[3]) != 5) {
1464 fputs("parse error!\n", ttyout);
1465 error = 1;
1466 goto bad;
1468 if (delim[0] != delim[1] || delim[0] != delim[2]
1469 || delim[0] != delim[3]) {
1470 fputs("parse error!\n", ttyout);
1471 error = 1;
1472 goto bad;
1474 data_addr = hisctladdr;
1475 data_addr.su_port = htons(port[1]);
1476 } else
1477 goto bad;
1479 if (ftp_connect(data, (struct sockaddr *)&data_addr.si_su,
1480 data_addr.su_len, 1) < 0) {
1481 if (activefallback) {
1482 (void)close(data);
1483 data = -1;
1484 passivemode = 0;
1485 #if 0
1486 activefallback = 0;
1487 #endif
1488 goto reinit;
1490 goto bad;
1492 #ifdef IPTOS_THROUGHPUT
1493 if (data_addr.su_family == AF_INET) {
1494 on = IPTOS_THROUGHPUT;
1495 if (setsockopt(data, IPPROTO_IP, IP_TOS,
1496 (void *)&on, sizeof(on)) == -1) {
1497 DWARN("setsockopt %s (ignored)",
1498 "IPTOS_THROUGHPUT");
1501 #endif
1502 return (0);
1505 noport:
1506 data_addr = myctladdr;
1507 if (sendport)
1508 data_addr.su_port = 0; /* let system pick one */
1509 if (data != -1)
1510 (void)close(data);
1511 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1512 if (data < 0) {
1513 warn("Can't create socket for data connection");
1514 if (tmpno)
1515 sendport = 1;
1516 return (1);
1518 if (!sendport)
1519 if (setsockopt(data, SOL_SOCKET, SO_REUSEADDR,
1520 (void *)&on, sizeof(on)) == -1) {
1521 warn("Can't set SO_REUSEADDR on data connection");
1522 goto bad;
1524 if (bind(data, (struct sockaddr *)&data_addr.si_su,
1525 data_addr.su_len) < 0) {
1526 warn("Can't bind for data connection");
1527 goto bad;
1529 if ((options & SO_DEBUG) &&
1530 setsockopt(data, SOL_SOCKET, SO_DEBUG,
1531 (void *)&on, sizeof(on)) == -1) {
1532 DWARN("setsockopt %s (ignored)", "SO_DEBUG");
1534 len = sizeof(data_addr.si_su);
1535 memset((char *)&data_addr, 0, sizeof (data_addr));
1536 if (getsockname(data, (struct sockaddr *)&data_addr.si_su, &len) == -1) {
1537 warn("Can't determine my address of data connection");
1538 goto bad;
1540 data_addr.su_len = len;
1541 if (ftp_listen(data, 1) < 0)
1542 warn("Can't listen to data connection");
1544 if (sendport) {
1545 char hname[NI_MAXHOST], sname[NI_MAXSERV];
1546 struct sockinet tmp;
1548 switch (data_addr.su_family) {
1549 case AF_INET:
1550 if (!epsv4 || epsv4bad) {
1551 result = COMPLETE + 1;
1552 break;
1554 /* FALLTHROUGH */
1555 #ifdef INET6
1556 case AF_INET6:
1557 if (!epsv6 || epsv6bad) {
1558 result = COMPLETE + 1;
1559 break;
1561 #endif
1562 af = (data_addr.su_family == AF_INET) ? 1 : 2;
1563 tmp = data_addr;
1564 #ifdef INET6
1565 if (tmp.su_family == AF_INET6)
1566 tmp.si_su.su_sin6.sin6_scope_id = 0;
1567 #endif
1568 if (getnameinfo((struct sockaddr *)&tmp.si_su,
1569 tmp.su_len, hname, sizeof(hname), sname,
1570 sizeof(sname), NI_NUMERICHOST | NI_NUMERICSERV)) {
1571 result = ERROR;
1572 } else {
1573 overbose = verbose;
1574 if (ftp_debug == 0)
1575 verbose = -1;
1576 result = command("EPRT |%u|%s|%s|", af, hname,
1577 sname);
1578 verbose = overbose;
1579 if (verbose > 0 &&
1580 (result == COMPLETE || !connected))
1581 fprintf(ttyout, "%s\n", reply_string);
1582 if (!connected)
1583 return (1);
1584 if (result != COMPLETE) {
1585 epsv4bad = 1;
1586 DPRINTF("disabling epsv4 for this "
1587 "connection\n");
1590 break;
1591 default:
1592 result = COMPLETE + 1;
1593 break;
1595 if (result == COMPLETE)
1596 goto skip_port;
1598 switch (data_addr.su_family) {
1599 case AF_INET:
1600 a = (char *)&data_addr.si_su.su_sin.sin_addr;
1601 p = (char *)&data_addr.su_port;
1602 result = command("PORT %d,%d,%d,%d,%d,%d",
1603 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
1604 UC(p[0]), UC(p[1]));
1605 break;
1606 #ifdef INET6
1607 case AF_INET6: {
1608 uint8_t ua[sizeof(data_addr.si_su.su_sin6.sin6_addr)];
1609 uint8_t up[sizeof(data_addr.su_port)];
1611 memcpy(ua, &data_addr.si_su.su_sin6.sin6_addr,
1612 sizeof(ua));
1613 memcpy(up, &data_addr.su_port, sizeof(up));
1615 result = command(
1616 "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
1617 6, 16,
1618 ua[0], ua[1], ua[2], ua[3],
1619 ua[4], ua[5], ua[6], ua[7],
1620 ua[8], ua[9], ua[10], ua[11],
1621 ua[12], ua[13], ua[14], ua[15],
1623 up[0], up[1]);
1624 break;
1626 #endif
1627 default:
1628 result = COMPLETE + 1; /* xxx */
1630 if (!connected)
1631 return (1);
1632 skip_port:
1634 if (result == ERROR && sendport == -1) {
1635 sendport = 0;
1636 tmpno = 1;
1637 goto noport;
1639 return (result != COMPLETE);
1641 if (tmpno)
1642 sendport = 1;
1643 #ifdef IPTOS_THROUGHPUT
1644 if (data_addr.su_family == AF_INET) {
1645 on = IPTOS_THROUGHPUT;
1646 if (setsockopt(data, IPPROTO_IP, IP_TOS,
1647 (void *)&on, sizeof(on)) == -1) {
1648 DWARN("setsockopt %s (ignored)", "IPTOS_THROUGHPUT");
1651 #endif
1652 return (0);
1653 bad:
1654 (void)close(data);
1655 data = -1;
1656 if (tmpno)
1657 sendport = 1;
1658 return (1);
1661 FILE *
1662 dataconn(const char *lmode)
1664 struct sockinet from;
1665 int s, flags, rv, timeout;
1666 struct timeval endtime, now, td;
1667 struct pollfd pfd[1];
1668 socklen_t fromlen;
1670 if (passivemode) /* passive data connection */
1671 return (fdopen(data, lmode));
1673 /* active mode data connection */
1675 if ((flags = fcntl(data, F_GETFL, 0)) == -1)
1676 goto dataconn_failed; /* get current socket flags */
1677 if (fcntl(data, F_SETFL, flags | O_NONBLOCK) == -1)
1678 goto dataconn_failed; /* set non-blocking connect */
1680 /* NOTE: we now must restore socket flags on successful exit */
1682 /* limit time waiting on listening socket */
1683 pfd[0].fd = data;
1684 pfd[0].events = POLLIN;
1685 (void)gettimeofday(&endtime, NULL); /* determine end time */
1686 endtime.tv_sec += (quit_time > 0) ? quit_time: 60;
1687 /* without -q, default to 60s */
1688 do {
1689 (void)gettimeofday(&now, NULL);
1690 timersub(&endtime, &now, &td);
1691 timeout = td.tv_sec * 1000 + td.tv_usec/1000;
1692 if (timeout < 0)
1693 timeout = 0;
1694 rv = ftp_poll(pfd, 1, timeout);
1695 } while (rv == -1 && errno == EINTR); /* loop until poll ! EINTR */
1696 if (rv == -1) {
1697 warn("Can't poll waiting before accept");
1698 goto dataconn_failed;
1700 if (rv == 0) {
1701 warnx("Poll timeout waiting before accept");
1702 goto dataconn_failed;
1705 /* (non-blocking) accept the connection */
1706 fromlen = myctladdr.su_len;
1707 do {
1708 s = accept(data, (struct sockaddr *) &from.si_su, &fromlen);
1709 } while (s == -1 && errno == EINTR); /* loop until accept ! EINTR */
1710 if (s == -1) {
1711 warn("Can't accept data connection");
1712 goto dataconn_failed;
1715 (void)close(data);
1716 data = s;
1717 if (fcntl(data, F_SETFL, flags) == -1) /* restore socket flags */
1718 goto dataconn_failed;
1720 #ifdef IPTOS_THROUGHPUT
1721 if (from.su_family == AF_INET) {
1722 int tos = IPTOS_THROUGHPUT;
1723 if (setsockopt(s, IPPROTO_IP, IP_TOS,
1724 (void *)&tos, sizeof(tos)) == -1) {
1725 DWARN("setsockopt %s (ignored)", "IPTOS_THROUGHPUT");
1728 #endif
1729 return (fdopen(data, lmode));
1731 dataconn_failed:
1732 (void)close(data);
1733 data = -1;
1734 return (NULL);
1737 void
1738 psabort(int notused)
1740 int oerrno = errno;
1742 sigint_raised = 1;
1743 alarmtimer(0);
1744 abrtflag++;
1745 errno = oerrno;
1748 void
1749 pswitch(int flag)
1751 sigfunc oldintr;
1752 static struct comvars {
1753 int connect;
1754 char name[MAXHOSTNAMELEN];
1755 struct sockinet mctl;
1756 struct sockinet hctl;
1757 FILE *in;
1758 FILE *out;
1759 int tpe;
1760 int curtpe;
1761 int cpnd;
1762 int sunqe;
1763 int runqe;
1764 int mcse;
1765 int ntflg;
1766 char nti[17];
1767 char nto[17];
1768 int mapflg;
1769 char mi[MAXPATHLEN];
1770 char mo[MAXPATHLEN];
1771 } proxstruct, tmpstruct;
1772 struct comvars *ip, *op;
1774 abrtflag = 0;
1775 oldintr = xsignal(SIGINT, psabort);
1776 if (flag) {
1777 if (proxy)
1778 return;
1779 ip = &tmpstruct;
1780 op = &proxstruct;
1781 proxy++;
1782 } else {
1783 if (!proxy)
1784 return;
1785 ip = &proxstruct;
1786 op = &tmpstruct;
1787 proxy = 0;
1789 ip->connect = connected;
1790 connected = op->connect;
1791 if (hostname)
1792 (void)strlcpy(ip->name, hostname, sizeof(ip->name));
1793 else
1794 ip->name[0] = '\0';
1795 hostname = op->name;
1796 ip->hctl = hisctladdr;
1797 hisctladdr = op->hctl;
1798 ip->mctl = myctladdr;
1799 myctladdr = op->mctl;
1800 ip->in = cin;
1801 cin = op->in;
1802 ip->out = cout;
1803 cout = op->out;
1804 ip->tpe = type;
1805 type = op->tpe;
1806 ip->curtpe = curtype;
1807 curtype = op->curtpe;
1808 ip->cpnd = cpend;
1809 cpend = op->cpnd;
1810 ip->sunqe = sunique;
1811 sunique = op->sunqe;
1812 ip->runqe = runique;
1813 runique = op->runqe;
1814 ip->mcse = mcase;
1815 mcase = op->mcse;
1816 ip->ntflg = ntflag;
1817 ntflag = op->ntflg;
1818 (void)strlcpy(ip->nti, ntin, sizeof(ip->nti));
1819 (void)strlcpy(ntin, op->nti, sizeof(ntin));
1820 (void)strlcpy(ip->nto, ntout, sizeof(ip->nto));
1821 (void)strlcpy(ntout, op->nto, sizeof(ntout));
1822 ip->mapflg = mapflag;
1823 mapflag = op->mapflg;
1824 (void)strlcpy(ip->mi, mapin, sizeof(ip->mi));
1825 (void)strlcpy(mapin, op->mi, sizeof(mapin));
1826 (void)strlcpy(ip->mo, mapout, sizeof(ip->mo));
1827 (void)strlcpy(mapout, op->mo, sizeof(mapout));
1828 (void)xsignal(SIGINT, oldintr);
1829 if (abrtflag) {
1830 abrtflag = 0;
1831 (*oldintr)(SIGINT);
1835 __dead static void
1836 abortpt(int notused)
1839 sigint_raised = 1;
1840 alarmtimer(0);
1841 if (fromatty)
1842 write(fileno(ttyout), "\n", 1);
1843 ptabflg++;
1844 mflag = 0;
1845 abrtflag = 0;
1846 siglongjmp(ptabort, 1);
1849 void
1850 proxtrans(const char *cmd, const char *local, const char *remote)
1852 sigfunc volatile oldintr;
1853 int prox_type, nfnd;
1854 int volatile secndflag;
1855 const char *volatile cmd2;
1857 oldintr = NULL;
1858 secndflag = 0;
1859 if (strcmp(cmd, "RETR"))
1860 cmd2 = "RETR";
1861 else
1862 cmd2 = runique ? "STOU" : "STOR";
1863 if ((prox_type = type) == 0) {
1864 if (unix_server && unix_proxy)
1865 prox_type = TYPE_I;
1866 else
1867 prox_type = TYPE_A;
1869 if (curtype != prox_type)
1870 changetype(prox_type, 1);
1871 if (command("PASV") != COMPLETE) {
1872 fputs("proxy server does not support third party transfers.\n",
1873 ttyout);
1874 return;
1876 pswitch(0);
1877 if (!connected) {
1878 fputs("No primary connection.\n", ttyout);
1879 pswitch(1);
1880 code = -1;
1881 return;
1883 if (curtype != prox_type)
1884 changetype(prox_type, 1);
1885 if (command("PORT %s", pasv) != COMPLETE) {
1886 pswitch(1);
1887 return;
1889 if (sigsetjmp(ptabort, 1))
1890 goto abort;
1891 oldintr = xsignal(SIGINT, abortpt);
1892 if ((restart_point &&
1893 (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1894 || (command("%s %s", cmd, remote) != PRELIM)) {
1895 (void)xsignal(SIGINT, oldintr);
1896 pswitch(1);
1897 return;
1899 sleep(2);
1900 pswitch(1);
1901 secndflag++;
1902 if ((restart_point &&
1903 (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1904 || (command("%s %s", cmd2, local) != PRELIM))
1905 goto abort;
1906 ptflag++;
1907 (void)getreply(0);
1908 pswitch(0);
1909 (void)getreply(0);
1910 (void)xsignal(SIGINT, oldintr);
1911 pswitch(1);
1912 ptflag = 0;
1913 fprintf(ttyout, "local: %s remote: %s\n", local, remote);
1914 return;
1915 abort:
1916 if (sigsetjmp(xferabort, 1)) {
1917 (void)xsignal(SIGINT, oldintr);
1918 return;
1920 (void)xsignal(SIGINT, abort_squared);
1921 ptflag = 0;
1922 if (strcmp(cmd, "RETR") && !proxy)
1923 pswitch(1);
1924 else if (!strcmp(cmd, "RETR") && proxy)
1925 pswitch(0);
1926 if (!cpend && !secndflag) { /* only here if cmd = "STOR" (proxy=1) */
1927 if (command("%s %s", cmd2, local) != PRELIM) {
1928 pswitch(0);
1929 if (cpend)
1930 abort_remote(NULL);
1932 pswitch(1);
1933 if (ptabflg)
1934 code = -1;
1935 (void)xsignal(SIGINT, oldintr);
1936 return;
1938 if (cpend)
1939 abort_remote(NULL);
1940 pswitch(!proxy);
1941 if (!cpend && !secndflag) { /* only if cmd = "RETR" (proxy=1) */
1942 if (command("%s %s", cmd2, local) != PRELIM) {
1943 pswitch(0);
1944 if (cpend)
1945 abort_remote(NULL);
1946 pswitch(1);
1947 if (ptabflg)
1948 code = -1;
1949 (void)xsignal(SIGINT, oldintr);
1950 return;
1953 if (cpend)
1954 abort_remote(NULL);
1955 pswitch(!proxy);
1956 if (cpend) {
1957 if ((nfnd = empty(cin, NULL, 10)) <= 0) {
1958 if (nfnd < 0)
1959 warn("Error aborting proxy command");
1960 if (ptabflg)
1961 code = -1;
1962 lostpeer(0);
1964 (void)getreply(0);
1965 (void)getreply(0);
1967 if (proxy)
1968 pswitch(0);
1969 pswitch(1);
1970 if (ptabflg)
1971 code = -1;
1972 (void)xsignal(SIGINT, oldintr);
1975 void
1976 reset(int argc, char *argv[])
1978 int nfnd = 1;
1980 if (argc == 0 && argv != NULL) {
1981 UPRINTF("usage: %s\n", argv[0]);
1982 code = -1;
1983 return;
1985 while (nfnd > 0) {
1986 if ((nfnd = empty(cin, NULL, 0)) < 0) {
1987 warn("Error resetting connection");
1988 code = -1;
1989 lostpeer(0);
1990 } else if (nfnd)
1991 (void)getreply(0);
1995 char *
1996 gunique(const char *local)
1998 static char new[MAXPATHLEN];
1999 char *cp = strrchr(local, '/');
2000 int d, count=0, len;
2001 char ext = '1';
2003 if (cp)
2004 *cp = '\0';
2005 d = access(cp == local ? "/" : cp ? local : ".", W_OK);
2006 if (cp)
2007 *cp = '/';
2008 if (d < 0) {
2009 warn("Can't access `%s'", local);
2010 return (NULL);
2012 len = strlcpy(new, local, sizeof(new));
2013 cp = &new[len];
2014 *cp++ = '.';
2015 while (!d) {
2016 if (++count == 100) {
2017 fputs("runique: can't find unique file name.\n",
2018 ttyout);
2019 return (NULL);
2021 *cp++ = ext;
2022 *cp = '\0';
2023 if (ext == '9')
2024 ext = '0';
2025 else
2026 ext++;
2027 if ((d = access(new, F_OK)) < 0)
2028 break;
2029 if (ext != '0')
2030 cp--;
2031 else if (*(cp - 2) == '.')
2032 *(cp - 1) = '1';
2033 else {
2034 *(cp - 2) = *(cp - 2) + 1;
2035 cp--;
2038 return (new);
2042 * abort_squared --
2043 * aborts abort_remote(). lostpeer() is called because if the user is
2044 * too impatient to wait or there's another problem then ftp really
2045 * needs to get back to a known state.
2047 static void
2048 abort_squared(int dummy)
2050 char msgbuf[100];
2051 size_t len;
2053 sigint_raised = 1;
2054 alarmtimer(0);
2055 len = strlcpy(msgbuf, "\nremote abort aborted; closing connection.\n",
2056 sizeof(msgbuf));
2057 write(fileno(ttyout), msgbuf, len);
2058 lostpeer(0);
2059 siglongjmp(xferabort, 1);
2062 void
2063 abort_remote(FILE *din)
2065 char buf[BUFSIZ];
2066 int nfnd;
2068 if (cout == NULL) {
2069 warnx("Lost control connection for abort");
2070 if (ptabflg)
2071 code = -1;
2072 lostpeer(0);
2073 return;
2076 * send IAC in urgent mode instead of DM because 4.3BSD places oob mark
2077 * after urgent byte rather than before as is protocol now
2079 buf[0] = IAC;
2080 buf[1] = IP;
2081 buf[2] = IAC;
2082 if (send(fileno(cout), buf, 3, MSG_OOB) != 3)
2083 warn("Can't send abort message");
2084 fprintf(cout, "%cABOR\r\n", DM);
2085 (void)fflush(cout);
2086 if ((nfnd = empty(cin, din, 10)) <= 0) {
2087 if (nfnd < 0)
2088 warn("Can't send abort message");
2089 if (ptabflg)
2090 code = -1;
2091 lostpeer(0);
2093 if (din && (nfnd & 2)) {
2094 while (read(fileno(din), buf, BUFSIZ) > 0)
2095 continue;
2097 if (getreply(0) == ERROR && code == 552) {
2098 /* 552 needed for nic style abort */
2099 (void)getreply(0);
2101 (void)getreply(0);
2105 * Ensure that ai->ai_addr is NOT an IPv4 mapped address.
2106 * IPv4 mapped address complicates too many things in FTP
2107 * protocol handling, as FTP protocol is defined differently
2108 * between IPv4 and IPv6.
2110 * This may not be the best way to handle this situation,
2111 * since the semantics of IPv4 mapped address is defined in
2112 * the kernel. There are configurations where we should use
2113 * IPv4 mapped address as native IPv6 address, not as
2114 * "an IPv6 address that embeds IPv4 address" (namely, SIIT).
2116 * More complete solution would be to have an additional
2117 * getsockopt to grab "real" peername/sockname. "real"
2118 * peername/sockname will be AF_INET if IPv4 mapped address
2119 * is used to embed IPv4 address, and will be AF_INET6 if
2120 * we use it as native. What a mess!
2122 void
2123 ai_unmapped(struct addrinfo *ai)
2125 #ifdef INET6
2126 struct sockaddr_in6 *sin6;
2127 struct sockaddr_in sin;
2128 socklen_t len;
2130 if (ai->ai_family != AF_INET6)
2131 return;
2132 if (ai->ai_addrlen != sizeof(struct sockaddr_in6) ||
2133 sizeof(sin) > ai->ai_addrlen)
2134 return;
2135 sin6 = (struct sockaddr_in6 *)ai->ai_addr;
2136 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
2137 return;
2139 memset(&sin, 0, sizeof(sin));
2140 sin.sin_family = AF_INET;
2141 len = sizeof(struct sockaddr_in);
2142 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
2143 sizeof(sin.sin_addr));
2144 sin.sin_port = sin6->sin6_port;
2146 ai->ai_family = AF_INET;
2147 #if defined(HAVE_STRUCT_SOCKADDR_IN_SIN_LEN)
2148 sin.sin_len = len;
2149 #endif
2150 memcpy(ai->ai_addr, &sin, len);
2151 ai->ai_addrlen = len;
2152 #endif
2155 #ifdef NO_USAGE
2156 void
2157 xusage(void)
2159 fputs("Usage error\n", ttyout);
2161 #endif