Sync with NetBSD:
[dragonfly.git] / contrib / tnftp / ftp.c
1 /*      $NetBSD: ftp.c,v 1.152 2007/07/22 05:02:50 lukem Exp $  */
2
3 /*-
4  * Copyright (c) 1996-2007 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Luke Mewburn.
9  *
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.
25  *
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.
37  */
38
39 /*
40  * Copyright (c) 1985, 1989, 1993, 1994
41  *      The Regents of the University of California.  All rights reserved.
42  *
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.
54  *
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.
66  */
67
68 /*
69  * Copyright (C) 1997 and 1998 WIDE Project.
70  * All rights reserved.
71  *
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.
83  *
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.
95  */
96
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.152 2007/07/22 05:02:50 lukem Exp $");
103 #endif
104 #endif /* not lint */
105
106 #include <sys/types.h>
107 #include <sys/stat.h>
108 #include <sys/socket.h>
109 #include <sys/time.h>
110
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>
117
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>
129
130 #include "ftp_var.h"
131
132 volatile sig_atomic_t   abrtflag;
133 volatile sig_atomic_t   timeoutflag;
134
135 sigjmp_buf      ptabort;
136 int     ptabflg;
137 int     ptflag = 0;
138 char    pasv[BUFSIZ];   /* passive port for proxy data connection */
139
140 static int empty(FILE *, FILE *, int);
141
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 !defined(HAVE_STRUCT_SOCKADDR_SA_LEN)
150         int     si_len;
151 #endif
152 };
153
154 #if !defined(HAVE_STRUCT_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
161
162 struct sockinet myctladdr, hisctladdr, data_addr;
163
164 char *
165 hookup(char *host, char *port)
166 {
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;
173
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);
189         }
190
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;
197
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);
206                 }
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;
213                 }
214                 if (ftp_connect(s, res->ai_addr, res->ai_addrlen) < 0) {
215                         close(s);
216                         s = -1;
217                         continue;
218                 }
219
220                 /* finally we got one */
221                 break;
222         }
223         if (s < 0) {
224                 warnx("Can't connect to `%s'", host);
225                 code = -1;
226                 freeaddrinfo(res0);
227                 return 0;
228         }
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;
233
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;
239         }
240         myctladdr.su_len = len;
241
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");
249                 }
250         }
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;
262         }
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;
272         }
273
274         if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE,
275                         (void *)&on, sizeof(on)) == -1) {
276                 DWARN("setsockopt %s (ignored)", "SO_OOBINLINE");
277         }
278
279         return (hostname);
280  bad:
281         (void)close(s);
282         return (NULL);
283 }
284
285 void
286 cmdabort(int notused)
287 {
288         int oerrno = errno;
289
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;
298 }
299
300 void
301 cmdtimeout(int notused)
302 {
303         int oerrno = errno;
304
305         alarmtimer(0);
306         if (fromatty)
307                 write(fileno(ttyout), "\n", 1);
308         timeoutflag++;
309         if (ptflag)
310                 siglongjmp(ptabort, 1);
311         errno = oerrno;
312 }
313
314 /*VARARGS*/
315 int
316 command(const char *fmt, ...)
317 {
318         va_list ap;
319         int r;
320         sigfunc oldsigint;
321
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);
334         }
335 #endif
336         if (cout == NULL) {
337                 warnx("No control connection for command");
338                 code = -1;
339                 return (0);
340         }
341
342         abrtflag = 0;
343
344         oldsigint = xsignal(SIGINT, cmdabort);
345
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);
357 }
358
359 static const char *m421[] = {
360         "remote server timed out. Connection closed",
361         "user interrupt. Connection closed",
362         "remote server has closed connection",
363 };
364
365 int
366 getreply(int expecteof)
367 {
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;
375
376         abrtflag = 0;
377         timeoutflag = 0;
378
379         oldsigint = xsignal(SIGINT, cmdabort);
380         oldsigalrm = xsignal(SIGALRM, cmdtimeout);
381
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;
403                                 }
404                                 continue;
405                         }
406                         dig++;
407                         if (c == EOF) {
408                                 /*
409                                  * these will get trashed by pswitch()
410                                  * in lostpeer()
411                                  */
412                                 int reply_timeoutflag = timeoutflag;
413                                 int reply_abrtflag = abrtflag;
414
415                                 alarmtimer(0);
416                                 if (expecteof && feof(cin)) {
417                                         (void)xsignal(SIGINT, oldsigint);
418                                         (void)xsignal(SIGALRM, oldsigalrm);
419                                         code = 221;
420                                         return (0);
421                                 }
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);
435                                 }
436                                 code = 421;
437                                 (void)xsignal(SIGINT, oldsigint);
438                                 (void)xsignal(SIGALRM, oldsigalrm);
439                                 return (4);
440                         }
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);
449                         }
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;
465                                 }
466                         }
467                         if (pflag == 100 && c == '(')
468                                 pflag = 2;
469                         if (dig == 4 && c == '-') {
470                                 if (continuation)
471                                         code = 0;
472                                 continuation++;
473                         }
474                         if (n == 0)
475                                 n = c;
476                         if (cp < &current_line[sizeof(current_line) - 1])
477                                 *cp++ = c;
478                 }
479                 if (verbose > 0 || ((verbose > -1 && n == '5') &&
480                     (n < '5' || !retry_connect))) {
481                         (void)putc(c, ttyout);
482                         (void)fflush(ttyout);
483                 }
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;
496                 }
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');
510         }
511 }
512
513 static int
514 empty(FILE *cin, FILE *din, int sec)
515 {
516         int             nr, nfd;
517         struct pollfd   pfd[2];
518
519         nfd = 0;
520         if (cin) {
521                 pfd[nfd].fd = fileno(cin);
522                 pfd[nfd++].events = POLLIN;
523         }
524
525         if (din) {
526                 pfd[nfd].fd = fileno(din);
527                 pfd[nfd++].events = POLLIN;
528         }
529
530         if ((nr = ftp_poll(pfd, nfd, sec * 1000)) <= 0)
531                 return nr;
532
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;
540 }
541
542 sigjmp_buf      xferabort;
543
544 void
545 abortxfer(int notused)
546 {
547         char msgbuf[100];
548         size_t len;
549
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);
563         }
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);
568 }
569
570 /*
571  * Read data from infd & write to outfd, using buf/bufsize as the temporary
572  * buffer, dealing with short writes.
573  * If rate_limit != 0, rate-limit the transfer.
574  * If hash_interval != 0, fputc('c', ttyout) every hash_interval bytes.
575  * Updates global variables: bytes.
576  * Returns 0 if ok, 1 if there was a read error, 2 if there was a write error.
577  * In the case of error, errno contains the appropriate error code.
578  */
579 static int
580 copy_bytes(int infd, int outfd, char *buf, size_t bufsize,
581         int rate_limit, int hash_interval)
582 {
583         volatile off_t  hashc;
584         ssize_t         inc, outc;
585         char            *bufp;
586         struct timeval  tvthen, tvnow, tvdiff;
587         off_t           bufrem, bufchunk;
588         int             serr;
589
590         hashc = hash_interval;
591         if (rate_limit)
592                 bufchunk = rate_limit;
593         else
594                 bufchunk = bufsize;
595
596         while (1) {
597                 if (rate_limit) {
598                         (void)gettimeofday(&tvthen, NULL);
599                 }
600                 errno = 0;
601                 inc = outc = 0;
602                                         /* copy bufchunk at a time */
603                 bufrem = bufchunk;
604                 while (bufrem > 0) {
605                         inc = read(infd, buf, MIN(bufsize, bufrem));
606                         if (inc <= 0)
607                                 goto copy_done;
608                         bytes += inc;
609                         bufrem -= inc;
610                         bufp = buf;
611                         while (inc > 0) {
612                                 outc = write(outfd, bufp, inc);
613                                 if (outc < 0)
614                                         goto copy_done;
615                                 inc -= outc;
616                                 bufp += outc;
617                         }
618                         if (hash_interval) {
619                                 while (bytes >= hashc) {
620                                         (void)putc('#', ttyout);
621                                         hashc += hash_interval;
622                                 }
623                                 (void)fflush(ttyout);
624                         }
625                 }
626                 if (rate_limit) {       /* rate limited; wait if necessary */
627                         while (1) {
628                                 (void)gettimeofday(&tvnow, NULL);
629                                 timersub(&tvnow, &tvthen, &tvdiff);
630                                 if (tvdiff.tv_sec > 0)
631                                         break;
632                                 usleep(1000000 - tvdiff.tv_usec);
633                         }
634                 }
635         }
636
637  copy_done:
638         serr = errno;
639         if (hash_interval && bytes > 0) {
640                 if (bytes < hash_interval)
641                         (void)putc('#', ttyout);
642                 (void)putc('\n', ttyout);
643                 (void)fflush(ttyout);
644         }
645         errno = serr;
646         if (inc == -1)
647                 return 1;
648         if (outc == -1)
649                 return 2;
650
651         return 0;
652 }
653
654 void
655 sendrequest(const char *cmd, const char *local, const char *remote,
656             int printnames)
657 {
658         struct stat st;
659         int c;
660         FILE *volatile fin;
661         FILE *volatile dout;
662         int (*volatile closefunc)(FILE *);
663         sigfunc volatile oldintr;
664         sigfunc volatile oldintp;
665         off_t volatile hashbytes;
666         int hash_interval;
667         char *volatile lmode;
668         static size_t bufsize;
669         static char *buf;
670         int oprogress;
671
672         hashbytes = mark;
673         direction = "sent";
674         dout = NULL;
675         bytes = 0;
676         filesize = -1;
677         oprogress = progress;
678         if (verbose && printnames) {
679                 if (*local != '-')
680                         fprintf(ttyout, "local: %s ", local);
681                 if (remote)
682                         fprintf(ttyout, "remote: %s\n", remote);
683         }
684         if (proxy) {
685                 proxtrans(cmd, local, remote);
686                 return;
687         }
688         if (curtype != type)
689                 changetype(type, 0);
690         closefunc = NULL;
691         oldintr = NULL;
692         oldintp = NULL;
693         lmode = "w";
694         if (sigsetjmp(xferabort, 1)) {
695                 while (cpend)
696                         (void)getreply(0);
697                 code = -1;
698                 goto cleanupsend;
699         }
700         (void)xsignal(SIGQUIT, psummary);
701         oldintr = xsignal(SIGINT, abortxfer);
702         if (strcmp(local, "-") == 0) {
703                 fin = stdin;
704                 progress = 0;
705         } else if (*local == '|') {
706                 oldintp = xsignal(SIGPIPE, SIG_IGN);
707                 fin = popen(local + 1, "r");
708                 if (fin == NULL) {
709                         warn("Can't execute `%s'", local + 1);
710                         code = -1;
711                         goto cleanupsend;
712                 }
713                 progress = 0;
714                 closefunc = pclose;
715         } else {
716                 fin = fopen(local, "r");
717                 if (fin == NULL) {
718                         warn("Can't open `%s'", local);
719                         code = -1;
720                         goto cleanupsend;
721                 }
722                 closefunc = fclose;
723                 if (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode)) {
724                         fprintf(ttyout, "%s: not a plain file.\n", local);
725                         code = -1;
726                         goto cleanupsend;
727                 }
728                 filesize = st.st_size;
729         }
730         if (initconn()) {
731                 code = -1;
732                 goto cleanupsend;
733         }
734         if (sigsetjmp(xferabort, 1))
735                 goto abort;
736
737         if (restart_point &&
738             (strcmp(cmd, "STOR") == 0 || strcmp(cmd, "APPE") == 0)) {
739                 int rc;
740
741                 rc = -1;
742                 switch (curtype) {
743                 case TYPE_A:
744                         rc = fseeko(fin, restart_point, SEEK_SET);
745                         break;
746                 case TYPE_I:
747                 case TYPE_L:
748                         rc = lseek(fileno(fin), restart_point, SEEK_SET);
749                         break;
750                 }
751                 if (rc < 0) {
752                         warn("Can't seek to restart `%s'", local);
753                         goto cleanupsend;
754                 }
755                 if (command("REST " LLF, (LLT)restart_point) != CONTINUE)
756                         goto cleanupsend;
757                 lmode = "r+";
758         }
759         if (remote) {
760                 if (command("%s %s", cmd, remote) != PRELIM)
761                         goto cleanupsend;
762         } else {
763                 if (command("%s", cmd) != PRELIM)
764                         goto cleanupsend;
765         }
766         dirchange = 1;
767         dout = dataconn(lmode);
768         if (dout == NULL)
769                 goto abort;
770
771         if (sndbuf_size > bufsize) {
772                 if (buf)
773                         (void)free(buf);
774                 bufsize = sndbuf_size;
775                 buf = ftp_malloc(bufsize);
776         }
777
778         progressmeter(-1);
779         oldintp = xsignal(SIGPIPE, SIG_IGN);
780         hash_interval = (hash && (!progress || filesize < 0)) ? mark : 0;
781
782         switch (curtype) {
783
784         case TYPE_I:
785         case TYPE_L:
786                 c = copy_bytes(fileno(fin), fileno(dout), buf, bufsize,
787                                rate_put, hash_interval);
788                 if (c == 1) {
789                         warn("Reading `%s'", local);
790                 } else if (c == 2) {
791                         if (errno != EPIPE)
792                                 warn("Writing to network");
793                         bytes = -1;
794                 }
795                 break;
796
797         case TYPE_A:
798                 while ((c = getc(fin)) != EOF) {
799                         if (c == '\n') {
800                                 while (hash_interval && bytes >= hashbytes) {
801                                         (void)putc('#', ttyout);
802                                         (void)fflush(ttyout);
803                                         hashbytes += mark;
804                                 }
805                                 if (ferror(dout))
806                                         break;
807                                 (void)putc('\r', dout);
808                                 bytes++;
809                         }
810                         (void)putc(c, dout);
811                         bytes++;
812 #if 0   /* this violates RFC0959 */
813                         if (c == '\r') {
814                                 (void)putc('\0', dout);
815                                 bytes++;
816                         }
817 #endif
818                 }
819                 if (hash_interval) {
820                         if (bytes < hashbytes)
821                                 (void)putc('#', ttyout);
822                         (void)putc('\n', ttyout);
823                 }
824                 if (ferror(fin))
825                         warn("Reading `%s'", local);
826                 if (ferror(dout)) {
827                         if (errno != EPIPE)
828                                 warn("Writing to network");
829                         bytes = -1;
830                 }
831                 break;
832         }
833
834         progressmeter(1);
835         if (closefunc != NULL) {
836                 (*closefunc)(fin);
837                 fin = NULL;
838         }
839         (void)fclose(dout);
840         dout = NULL;
841         (void)getreply(0);
842         if (bytes > 0)
843                 ptransfer(0);
844         goto cleanupsend;
845
846  abort:
847         (void)xsignal(SIGINT, oldintr);
848         oldintr = NULL;
849         if (!cpend) {
850                 code = -1;
851                 goto cleanupsend;
852         }
853         if (data >= 0) {
854                 (void)close(data);
855                 data = -1;
856         }
857         if (dout) {
858                 (void)fclose(dout);
859                 dout = NULL;
860         }
861         (void)getreply(0);
862         code = -1;
863         if (bytes > 0)
864                 ptransfer(0);
865
866  cleanupsend:
867         if (oldintr)
868                 (void)xsignal(SIGINT, oldintr);
869         if (oldintp)
870                 (void)xsignal(SIGPIPE, oldintp);
871         if (data >= 0) {
872                 (void)close(data);
873                 data = -1;
874         }
875         if (closefunc != NULL && fin != NULL)
876                 (*closefunc)(fin);
877         if (dout)
878                 (void)fclose(dout);
879         progress = oprogress;
880         restart_point = 0;
881         bytes = 0;
882 }
883
884 void
885 recvrequest(const char *cmd, const char *volatile local, const char *remote,
886             const char *lmode, int printnames, int ignorespecial)
887 {
888         FILE *volatile fout;
889         FILE *volatile din;
890         int (*volatile closefunc)(FILE *);
891         sigfunc volatile oldintr;
892         sigfunc volatile oldintp;
893         int c, d;
894         int volatile is_retr;
895         int volatile tcrflag;
896         int volatile bare_lfs;
897         static size_t bufsize;
898         static char *buf;
899         off_t volatile hashbytes;
900         int hash_interval;
901         struct stat st;
902         time_t mtime;
903         struct timeval tval[2];
904         int oprogress;
905         int opreserve;
906
907         fout = NULL;
908         din = NULL;
909         hashbytes = mark;
910         direction = "received";
911         bytes = 0;
912         bare_lfs = 0;
913         filesize = -1;
914         oprogress = progress;
915         opreserve = preserve;
916         is_retr = (strcmp(cmd, "RETR") == 0);
917         if (is_retr && verbose && printnames) {
918                 if (ignorespecial || *local != '-')
919                         fprintf(ttyout, "local: %s ", local);
920                 if (remote)
921                         fprintf(ttyout, "remote: %s\n", remote);
922         }
923         if (proxy && is_retr) {
924                 proxtrans(cmd, local, remote);
925                 return;
926         }
927         closefunc = NULL;
928         oldintr = NULL;
929         oldintp = NULL;
930         tcrflag = !crflag && is_retr;
931         if (sigsetjmp(xferabort, 1)) {
932                 while (cpend)
933                         (void)getreply(0);
934                 code = -1;
935                 goto cleanuprecv;
936         }
937         (void)xsignal(SIGQUIT, psummary);
938         oldintr = xsignal(SIGINT, abortxfer);
939         if (ignorespecial || (strcmp(local, "-") && *local != '|')) {
940                 if (access(local, W_OK) < 0) {
941                         char *dir = strrchr(local, '/');
942
943                         if (errno != ENOENT && errno != EACCES) {
944                                 warn("Can't access `%s'", local);
945                                 code = -1;
946                                 goto cleanuprecv;
947                         }
948                         if (dir != NULL)
949                                 *dir = 0;
950                         d = access(dir == local ? "/" :
951                             dir ? local : ".", W_OK);
952                         if (dir != NULL)
953                                 *dir = '/';
954                         if (d < 0) {
955                                 warn("Can't access `%s'", local);
956                                 code = -1;
957                                 goto cleanuprecv;
958                         }
959                         if (!runique && errno == EACCES &&
960                             chmod(local, (S_IRUSR|S_IWUSR)) < 0) {
961                                 warn("Can't chmod `%s'", local);
962                                 code = -1;
963                                 goto cleanuprecv;
964                         }
965                         if (runique && errno == EACCES &&
966                            (local = gunique(local)) == NULL) {
967                                 code = -1;
968                                 goto cleanuprecv;
969                         }
970                 }
971                 else if (runique && (local = gunique(local)) == NULL) {
972                         code = -1;
973                         goto cleanuprecv;
974                 }
975         }
976         if (!is_retr) {
977                 if (curtype != TYPE_A)
978                         changetype(TYPE_A, 0);
979         } else {
980                 if (curtype != type)
981                         changetype(type, 0);
982                 filesize = remotesize(remote, 0);
983                 if (code == 421 || code == -1)
984                         goto cleanuprecv;
985         }
986         if (initconn()) {
987                 code = -1;
988                 goto cleanuprecv;
989         }
990         if (sigsetjmp(xferabort, 1))
991                 goto abort;
992         if (is_retr && restart_point &&
993             command("REST " LLF, (LLT) restart_point) != CONTINUE)
994                 goto cleanuprecv;
995         if (! EMPTYSTRING(remote)) {
996                 if (command("%s %s", cmd, remote) != PRELIM)
997                         goto cleanuprecv;
998         } else {
999                 if (command("%s", cmd) != PRELIM)
1000                         goto cleanuprecv;
1001         }
1002         din = dataconn("r");
1003         if (din == NULL)
1004                 goto abort;
1005         if (!ignorespecial && strcmp(local, "-") == 0) {
1006                 fout = stdout;
1007                 progress = 0;
1008                 preserve = 0;
1009         } else if (!ignorespecial && *local == '|') {
1010                 oldintp = xsignal(SIGPIPE, SIG_IGN);
1011                 fout = popen(local + 1, "w");
1012                 if (fout == NULL) {
1013                         warn("Can't execute `%s'", local+1);
1014                         goto abort;
1015                 }
1016                 progress = 0;
1017                 preserve = 0;
1018                 closefunc = pclose;
1019         } else {
1020                 fout = fopen(local, lmode);
1021                 if (fout == NULL) {
1022                         warn("Can't open `%s'", local);
1023                         goto abort;
1024                 }
1025                 closefunc = fclose;
1026         }
1027
1028         if (fstat(fileno(fout), &st) != -1 && !S_ISREG(st.st_mode)) {
1029                 progress = 0;
1030                 preserve = 0;
1031         }
1032         if (rcvbuf_size > bufsize) {
1033                 if (buf)
1034                         (void)free(buf);
1035                 bufsize = rcvbuf_size;
1036                 buf = ftp_malloc(bufsize);
1037         }
1038
1039         progressmeter(-1);
1040         hash_interval = (hash && (!progress || filesize < 0)) ? mark : 0;
1041
1042         switch (curtype) {
1043
1044         case TYPE_I:
1045         case TYPE_L:
1046                 if (is_retr && restart_point &&
1047                     lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1048                         warn("Can't seek to restart `%s'", local);
1049                         goto cleanuprecv;
1050                 }
1051                 c = copy_bytes(fileno(din), fileno(fout), buf, bufsize,
1052                                rate_get, hash_interval);
1053                 if (c == 1) {
1054                         if (errno != EPIPE)
1055                                 warn("Reading from network");
1056                         bytes = -1;
1057                 } else if (c == 2) {
1058                         warn("Writing `%s'", local);
1059                 }
1060                 break;
1061
1062         case TYPE_A:
1063                 if (is_retr && restart_point) {
1064                         int ch;
1065                         off_t i;
1066
1067                         if (fseeko(fout, (off_t)0, SEEK_SET) < 0)
1068                                 goto done;
1069                         for (i = 0; i++ < restart_point;) {
1070                                 if ((ch = getc(fout)) == EOF)
1071                                         goto done;
1072                                 if (ch == '\n')
1073                                         i++;
1074                         }
1075                         if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1076  done:
1077                                 warn("Can't seek to restart `%s'", local);
1078                                 goto cleanuprecv;
1079                         }
1080                 }
1081                 while ((c = getc(din)) != EOF) {
1082                         if (c == '\n')
1083                                 bare_lfs++;
1084                         while (c == '\r') {
1085                                 while (hash_interval && bytes >= hashbytes) {
1086                                         (void)putc('#', ttyout);
1087                                         (void)fflush(ttyout);
1088                                         hashbytes += mark;
1089                                 }
1090                                 bytes++;
1091                                 if ((c = getc(din)) != '\n' || tcrflag) {
1092                                         if (ferror(fout))
1093                                                 goto break2;
1094                                         (void)putc('\r', fout);
1095                                         if (c == '\0') {
1096                                                 bytes++;
1097                                                 goto contin2;
1098                                         }
1099                                         if (c == EOF)
1100                                                 goto contin2;
1101                                 }
1102                         }
1103                         (void)putc(c, fout);
1104                         bytes++;
1105         contin2:        ;
1106                 }
1107  break2:
1108                 if (hash_interval) {
1109                         if (bytes < hashbytes)
1110                                 (void)putc('#', ttyout);
1111                         (void)putc('\n', ttyout);
1112                 }
1113                 if (ferror(din)) {
1114                         if (errno != EPIPE)
1115                                 warn("Reading from network");
1116                         bytes = -1;
1117                 }
1118                 if (ferror(fout))
1119                         warn("Writing `%s'", local);
1120                 break;
1121         }
1122
1123         progressmeter(1);
1124         if (closefunc != NULL) {
1125                 (*closefunc)(fout);
1126                 fout = NULL;
1127         }
1128         (void)fclose(din);
1129         din = NULL;
1130         (void)getreply(0);
1131         if (bare_lfs) {
1132                 fprintf(ttyout,
1133                     "WARNING! %d bare linefeeds received in ASCII mode.\n",
1134                     bare_lfs);
1135                 fputs("File may not have transferred correctly.\n", ttyout);
1136         }
1137         if (bytes >= 0 && is_retr) {
1138                 if (bytes > 0)
1139                         ptransfer(0);
1140                 if (preserve && (closefunc == fclose)) {
1141                         mtime = remotemodtime(remote, 0);
1142                         if (mtime != -1) {
1143                                 (void)gettimeofday(&tval[0], NULL);
1144                                 tval[1].tv_sec = mtime;
1145                                 tval[1].tv_usec = 0;
1146                                 if (utimes(local, tval) == -1) {
1147                                         fprintf(ttyout,
1148                                 "Can't change modification time on %s to %s",
1149                                             local,
1150                                             rfc2822time(localtime(&mtime)));
1151                                 }
1152                         }
1153                 }
1154         }
1155         goto cleanuprecv;
1156
1157  abort:
1158                         /*
1159                          * abort using RFC0959 recommended IP,SYNC sequence
1160                          */
1161         if (! sigsetjmp(xferabort, 1)) {
1162                         /* this is the first call */
1163                 (void)xsignal(SIGINT, abort_squared);
1164                 if (!cpend) {
1165                         code = -1;
1166                         goto cleanuprecv;
1167                 }
1168                 abort_remote(din);
1169         }
1170         code = -1;
1171         if (bytes > 0)
1172                 ptransfer(0);
1173
1174  cleanuprecv:
1175         if (oldintr)
1176                 (void)xsignal(SIGINT, oldintr);
1177         if (oldintp)
1178                 (void)xsignal(SIGPIPE, oldintp);
1179         if (data >= 0) {
1180                 (void)close(data);
1181                 data = -1;
1182         }
1183         if (closefunc != NULL && fout != NULL)
1184                 (*closefunc)(fout);
1185         if (din)
1186                 (void)fclose(din);
1187         progress = oprogress;
1188         preserve = opreserve;
1189         bytes = 0;
1190 }
1191
1192 /*
1193  * Need to start a listen on the data channel before we send the command,
1194  * otherwise the server's connect may fail.
1195  */
1196 int
1197 initconn(void)
1198 {
1199         char *p, *a;
1200         int result, tmpno = 0;
1201         int on = 1;
1202         int error;
1203         unsigned int addr[16], port[2];
1204         unsigned int af, hal, pal;
1205         socklen_t len;
1206         char *pasvcmd = NULL;
1207         int overbose;
1208
1209 #ifdef INET6
1210 #ifndef NO_DEBUG
1211         if (myctladdr.su_family == AF_INET6 && ftp_debug &&
1212             (IN6_IS_ADDR_LINKLOCAL(&myctladdr.si_su.su_sin6.sin6_addr) ||
1213              IN6_IS_ADDR_SITELOCAL(&myctladdr.si_su.su_sin6.sin6_addr))) {
1214                 warnx("Use of scoped addresses can be troublesome");
1215         }
1216 #endif
1217 #endif
1218
1219  reinit:
1220         if (passivemode) {
1221                 data_addr = myctladdr;
1222                 data = socket(data_addr.su_family, SOCK_STREAM, 0);
1223                 if (data < 0) {
1224                         warn("Can't create socket for data connection");
1225                         return (1);
1226                 }
1227                 if ((options & SO_DEBUG) &&
1228                     setsockopt(data, SOL_SOCKET, SO_DEBUG,
1229                                 (void *)&on, sizeof(on)) == -1) {
1230                         DWARN("setsockopt %s (ignored)", "SO_DEBUG");
1231                 }
1232                 result = COMPLETE + 1;
1233                 switch (data_addr.su_family) {
1234                 case AF_INET:
1235                         if (epsv4 && !epsv4bad) {
1236                                 pasvcmd = "EPSV";
1237                                 overbose = verbose;
1238                                 if (ftp_debug == 0)
1239                                         verbose = -1;
1240                                 result = command("EPSV");
1241                                 verbose = overbose;
1242                                 if (verbose > 0 &&
1243                                     (result == COMPLETE || !connected))
1244                                         fprintf(ttyout, "%s\n", reply_string);
1245                                 if (!connected)
1246                                         return (1);
1247                                 /*
1248                                  * this code is to be friendly with broken
1249                                  * BSDI ftpd
1250                                  */
1251                                 if (code / 10 == 22 && code != 229) {
1252                                         fputs(
1253 "wrong server: return code must be 229\n",
1254                                                 ttyout);
1255                                         result = COMPLETE + 1;
1256                                 }
1257                                 if (result != COMPLETE) {
1258                                         epsv4bad = 1;
1259                                         DPRINTF("disabling epsv4 for this "
1260                                             "connection\n");
1261                                 }
1262                         }
1263                         if (result != COMPLETE) {
1264                                 pasvcmd = "PASV";
1265                                 result = command("PASV");
1266                                 if (!connected)
1267                                         return (1);
1268                         }
1269                         break;
1270 #ifdef INET6
1271                 case AF_INET6:
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);
1283                         /* this code is to be friendly with broken BSDI ftpd */
1284                         if (code / 10 == 22 && code != 229) {
1285                                 fputs(
1286 "wrong server: return code must be 229\n",
1287                                         ttyout);
1288                                 result = COMPLETE + 1;
1289                         }
1290                         if (result != COMPLETE) {
1291                                 pasvcmd = "LPSV";
1292                                 result = command("LPSV");
1293                         }
1294                         if (!connected)
1295                                 return (1);
1296                         break;
1297 #endif
1298                 default:
1299                         result = COMPLETE + 1;
1300                         break;
1301                 }
1302                 if (result != COMPLETE) {
1303                         if (activefallback) {
1304                                 (void)close(data);
1305                                 data = -1;
1306                                 passivemode = 0;
1307 #if 0
1308                                 activefallback = 0;
1309 #endif
1310                                 goto reinit;
1311                         }
1312                         fputs("Passive mode refused.\n", ttyout);
1313                         goto bad;
1314                 }
1315
1316 #define pack2(var, off) \
1317         (((var[(off) + 0] & 0xff) << 8) | ((var[(off) + 1] & 0xff) << 0))
1318 #define pack4(var, off) \
1319         (((var[(off) + 0] & 0xff) << 24) | ((var[(off) + 1] & 0xff) << 16) | \
1320          ((var[(off) + 2] & 0xff) << 8) | ((var[(off) + 3] & 0xff) << 0))
1321 #define UC(b)   (((int)b)&0xff)
1322
1323                 /*
1324                  * What we've got at this point is a string of comma separated
1325                  * one-byte unsigned integer values, separated by commas.
1326                  */
1327                 if (strcmp(pasvcmd, "PASV") == 0) {
1328                         if (data_addr.su_family != AF_INET) {
1329                                 fputs(
1330     "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1331                                 error = 1;
1332                                 goto bad;
1333                         }
1334                         if (code / 10 == 22 && code != 227) {
1335                                 fputs("wrong server: return code must be 227\n",
1336                                         ttyout);
1337                                 error = 1;
1338                                 goto bad;
1339                         }
1340                         error = sscanf(pasv, "%u,%u,%u,%u,%u,%u",
1341                                         &addr[0], &addr[1], &addr[2], &addr[3],
1342                                         &port[0], &port[1]);
1343                         if (error != 6) {
1344                                 fputs(
1345 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1346                                 error = 1;
1347                                 goto bad;
1348                         }
1349                         error = 0;
1350                         memset(&data_addr, 0, sizeof(data_addr));
1351                         data_addr.su_family = AF_INET;
1352                         data_addr.su_len = sizeof(struct sockaddr_in);
1353                         data_addr.si_su.su_sin.sin_addr.s_addr =
1354                             htonl(pack4(addr, 0));
1355                         data_addr.su_port = htons(pack2(port, 0));
1356                 } else if (strcmp(pasvcmd, "LPSV") == 0) {
1357                         if (code / 10 == 22 && code != 228) {
1358                                 fputs("wrong server: return code must be 228\n",
1359                                         ttyout);
1360                                 error = 1;
1361                                 goto bad;
1362                         }
1363                         switch (data_addr.su_family) {
1364                         case AF_INET:
1365                                 error = sscanf(pasv,
1366 "%u,%u,%u,%u,%u,%u,%u,%u,%u",
1367                                         &af, &hal,
1368                                         &addr[0], &addr[1], &addr[2], &addr[3],
1369                                         &pal, &port[0], &port[1]);
1370                                 if (error != 9) {
1371                                         fputs(
1372 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1373                                         error = 1;
1374                                         goto bad;
1375                                 }
1376                                 if (af != 4 || hal != 4 || pal != 2) {
1377                                         fputs(
1378 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1379                                         error = 1;
1380                                         goto bad;
1381                                 }
1382
1383                                 error = 0;
1384                                 memset(&data_addr, 0, sizeof(data_addr));
1385                                 data_addr.su_family = AF_INET;
1386                                 data_addr.su_len = sizeof(struct sockaddr_in);
1387                                 data_addr.si_su.su_sin.sin_addr.s_addr =
1388                                     htonl(pack4(addr, 0));
1389                                 data_addr.su_port = htons(pack2(port, 0));
1390                                 break;
1391 #ifdef INET6
1392                         case AF_INET6:
1393                                 error = sscanf(pasv,
1394 "%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u",
1395                                         &af, &hal,
1396                                         &addr[0], &addr[1], &addr[2], &addr[3],
1397                                         &addr[4], &addr[5], &addr[6], &addr[7],
1398                                         &addr[8], &addr[9], &addr[10],
1399                                         &addr[11], &addr[12], &addr[13],
1400                                         &addr[14], &addr[15],
1401                                         &pal, &port[0], &port[1]);
1402                                 if (error != 21) {
1403                                         fputs(
1404 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
1405                                         error = 1;
1406                                         goto bad;
1407                                 }
1408                                 if (af != 6 || hal != 16 || pal != 2) {
1409                                         fputs(
1410 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
1411                                         error = 1;
1412                                         goto bad;
1413                                 }
1414
1415                                 error = 0;
1416                                 memset(&data_addr, 0, sizeof(data_addr));
1417                                 data_addr.su_family = AF_INET6;
1418                                 data_addr.su_len = sizeof(struct sockaddr_in6);
1419                             {
1420                                 int i;
1421                                 for (i = 0; i < sizeof(struct in6_addr); i++) {
1422                                         data_addr.si_su.su_sin6.sin6_addr.s6_addr[i] =
1423                                             UC(addr[i]);
1424                                 }
1425                             }
1426                                 data_addr.su_port = htons(pack2(port, 0));
1427                                 break;
1428 #endif
1429                         default:
1430                                 error = 1;
1431                         }
1432                 } else if (strcmp(pasvcmd, "EPSV") == 0) {
1433                         char delim[4];
1434
1435                         port[0] = 0;
1436                         if (code / 10 == 22 && code != 229) {
1437                                 fputs("wrong server: return code must be 229\n",
1438                                         ttyout);
1439                                 error = 1;
1440                                 goto bad;
1441                         }
1442                         if (sscanf(pasv, "%c%c%c%d%c", &delim[0],
1443                                         &delim[1], &delim[2], &port[1],
1444                                         &delim[3]) != 5) {
1445                                 fputs("parse error!\n", ttyout);
1446                                 error = 1;
1447                                 goto bad;
1448                         }
1449                         if (delim[0] != delim[1] || delim[0] != delim[2]
1450                          || delim[0] != delim[3]) {
1451                                 fputs("parse error!\n", ttyout);
1452                                 error = 1;
1453                                 goto bad;
1454                         }
1455                         data_addr = hisctladdr;
1456                         data_addr.su_port = htons(port[1]);
1457                 } else
1458                         goto bad;
1459
1460                 if (ftp_connect(data, (struct sockaddr *)&data_addr.si_su,
1461                     data_addr.su_len) < 0) {
1462                         if (activefallback) {
1463                                 (void)close(data);
1464                                 data = -1;
1465                                 passivemode = 0;
1466 #if 0
1467                                 activefallback = 0;
1468 #endif
1469                                 goto reinit;
1470                         }
1471                         goto bad;
1472                 }
1473 #ifdef IPTOS_THROUGHPUT
1474                 if (data_addr.su_family == AF_INET) {
1475                         on = IPTOS_THROUGHPUT;
1476                         if (setsockopt(data, IPPROTO_IP, IP_TOS,
1477                                         (void *)&on, sizeof(on)) == -1) {
1478                                 DWARN("setsockopt %s (ignored)",
1479                                     "IPTOS_THROUGHPUT");
1480                         }
1481                 }
1482 #endif
1483                 return (0);
1484         }
1485
1486  noport:
1487         data_addr = myctladdr;
1488         if (sendport)
1489                 data_addr.su_port = 0;  /* let system pick one */
1490         if (data != -1)
1491                 (void)close(data);
1492         data = socket(data_addr.su_family, SOCK_STREAM, 0);
1493         if (data < 0) {
1494                 warn("Can't create socket for data connection");
1495                 if (tmpno)
1496                         sendport = 1;
1497                 return (1);
1498         }
1499         if (!sendport)
1500                 if (setsockopt(data, SOL_SOCKET, SO_REUSEADDR,
1501                                 (void *)&on, sizeof(on)) == -1) {
1502                         warn("Can't set SO_REUSEADDR on data connection");
1503                         goto bad;
1504                 }
1505         if (bind(data, (struct sockaddr *)&data_addr.si_su,
1506             data_addr.su_len) < 0) {
1507                 warn("Can't bind for data connection");
1508                 goto bad;
1509         }
1510         if ((options & SO_DEBUG) &&
1511             setsockopt(data, SOL_SOCKET, SO_DEBUG,
1512                         (void *)&on, sizeof(on)) == -1) {
1513                 DWARN("setsockopt %s (ignored)", "SO_DEBUG");
1514         }
1515         len = sizeof(data_addr.si_su);
1516         memset((char *)&data_addr, 0, sizeof (data_addr));
1517         if (getsockname(data, (struct sockaddr *)&data_addr.si_su, &len) == -1) {
1518                 warn("Can't determine my address of data connection");
1519                 goto bad;
1520         }
1521         data_addr.su_len = len;
1522         if (ftp_listen(data, 1) < 0)
1523                 warn("Can't listen to data connection");
1524
1525         if (sendport) {
1526                 char hname[NI_MAXHOST], sname[NI_MAXSERV];
1527                 int af;
1528                 struct sockinet tmp;
1529
1530                 switch (data_addr.su_family) {
1531                 case AF_INET:
1532                         if (!epsv4 || epsv4bad) {
1533                                 result = COMPLETE + 1;
1534                                 break;
1535                         }
1536                         /* FALLTHROUGH */
1537 #ifdef INET6
1538                 case AF_INET6:
1539 #endif
1540                         af = (data_addr.su_family == AF_INET) ? 1 : 2;
1541                         tmp = data_addr;
1542 #ifdef INET6
1543                         if (tmp.su_family == AF_INET6)
1544                                 tmp.si_su.su_sin6.sin6_scope_id = 0;
1545 #endif
1546                         if (getnameinfo((struct sockaddr *)&tmp.si_su,
1547                             tmp.su_len, hname, sizeof(hname), sname,
1548                             sizeof(sname), NI_NUMERICHOST | NI_NUMERICSERV)) {
1549                                 result = ERROR;
1550                         } else {
1551                                 overbose = verbose;
1552                                 if (ftp_debug == 0)
1553                                         verbose = -1;
1554                                 result = command("EPRT |%d|%s|%s|", af, hname,
1555                                     sname);
1556                                 verbose = overbose;
1557                                 if (verbose > 0 &&
1558                                     (result == COMPLETE || !connected))
1559                                         fprintf(ttyout, "%s\n", reply_string);
1560                                 if (!connected)
1561                                         return (1);
1562                                 if (result != COMPLETE) {
1563                                         epsv4bad = 1;
1564                                         DPRINTF("disabling epsv4 for this "
1565                                             "connection\n");
1566                                 }
1567                         }
1568                         break;
1569                 default:
1570                         result = COMPLETE + 1;
1571                         break;
1572                 }
1573                 if (result == COMPLETE)
1574                         goto skip_port;
1575
1576                 switch (data_addr.su_family) {
1577                 case AF_INET:
1578                         a = (char *)&data_addr.si_su.su_sin.sin_addr;
1579                         p = (char *)&data_addr.su_port;
1580                         result = command("PORT %d,%d,%d,%d,%d,%d",
1581                                  UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
1582                                  UC(p[0]), UC(p[1]));
1583                         break;
1584 #ifdef INET6
1585                 case AF_INET6:
1586                         a = (char *)&data_addr.si_su.su_sin6.sin6_addr;
1587                         p = (char *)&data_addr.su_port;
1588                         result = command(
1589         "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
1590                                  6, 16,
1591                                  UC(a[0]),UC(a[1]),UC(a[2]),UC(a[3]),
1592                                  UC(a[4]),UC(a[5]),UC(a[6]),UC(a[7]),
1593                                  UC(a[8]),UC(a[9]),UC(a[10]),UC(a[11]),
1594                                  UC(a[12]),UC(a[13]),UC(a[14]),UC(a[15]),
1595                                  2, UC(p[0]), UC(p[1]));
1596                         break;
1597 #endif
1598                 default:
1599                         result = COMPLETE + 1; /* xxx */
1600                 }
1601                 if (!connected)
1602                         return (1);
1603         skip_port:
1604
1605                 if (result == ERROR && sendport == -1) {
1606                         sendport = 0;
1607                         tmpno = 1;
1608                         goto noport;
1609                 }
1610                 return (result != COMPLETE);
1611         }
1612         if (tmpno)
1613                 sendport = 1;
1614 #ifdef IPTOS_THROUGHPUT
1615         if (data_addr.su_family == AF_INET) {
1616                 on = IPTOS_THROUGHPUT;
1617                 if (setsockopt(data, IPPROTO_IP, IP_TOS,
1618                                 (void *)&on, sizeof(on)) == -1)
1619                         DWARN("setsockopt %s (ignored)", "IPTOS_THROUGHPUT");
1620         }
1621 #endif
1622         return (0);
1623  bad:
1624         (void)close(data);
1625         data = -1;
1626         if (tmpno)
1627                 sendport = 1;
1628         return (1);
1629 }
1630
1631 FILE *
1632 dataconn(const char *lmode)
1633 {
1634         struct sockinet from;
1635         int             s, flags, rv, timeout;
1636         struct timeval  endtime, now, td;
1637         struct pollfd   pfd[1];
1638         socklen_t       fromlen;
1639
1640         if (passivemode)        /* passive data connection */
1641                 return (fdopen(data, lmode));
1642
1643                                 /* active mode data connection */
1644
1645         if ((flags = fcntl(data, F_GETFL, 0)) == -1)
1646                 goto dataconn_failed;           /* get current socket flags  */
1647         if (fcntl(data, F_SETFL, flags | O_NONBLOCK) == -1)
1648                 goto dataconn_failed;           /* set non-blocking connect */
1649
1650                 /* NOTE: we now must restore socket flags on successful exit */
1651
1652                                 /* limit time waiting on listening socket */
1653         pfd[0].fd = data;
1654         pfd[0].events = POLLIN;
1655         (void)gettimeofday(&endtime, NULL);     /* determine end time */
1656         endtime.tv_sec += (quit_time > 0) ? quit_time: 60;
1657                                                 /* without -q, default to 60s */
1658         do {
1659                 (void)gettimeofday(&now, NULL);
1660                 timersub(&endtime, &now, &td);
1661                 timeout = td.tv_sec * 1000 + td.tv_usec/1000;
1662                 if (timeout < 0)
1663                         timeout = 0;
1664                 rv = ftp_poll(pfd, 1, timeout);
1665         } while (rv == -1 && errno == EINTR);   /* loop until poll ! EINTR */
1666         if (rv == -1) {
1667                 warn("Can't poll waiting before accept");
1668                 goto dataconn_failed;
1669         }
1670         if (rv == 0) {
1671                 warnx("Poll timeout waiting before accept");
1672                 goto dataconn_failed;
1673         }
1674
1675                                 /* (non-blocking) accept the connection */
1676         fromlen = myctladdr.su_len;
1677         do {
1678                 s = accept(data, (struct sockaddr *) &from.si_su, &fromlen);
1679         } while (s == -1 && errno == EINTR);    /* loop until accept ! EINTR */
1680         if (s == -1) {
1681                 warn("Can't accept data connection");
1682                 goto dataconn_failed;
1683         }
1684
1685         (void)close(data);
1686         data = s;
1687         if (fcntl(data, F_SETFL, flags) == -1)  /* restore socket flags */
1688                 goto dataconn_failed;
1689
1690 #ifdef IPTOS_THROUGHPUT
1691         if (from.su_family == AF_INET) {
1692                 int tos = IPTOS_THROUGHPUT;
1693                 if (setsockopt(s, IPPROTO_IP, IP_TOS,
1694                                 (void *)&tos, sizeof(tos)) == -1) {
1695                         DWARN("setsockopt %s (ignored)", "IPTOS_THROUGHPUT");
1696                 }
1697         }
1698 #endif
1699         return (fdopen(data, lmode));
1700
1701  dataconn_failed:
1702         (void)close(data);
1703         data = -1;
1704         return (NULL);
1705 }
1706
1707 void
1708 psabort(int notused)
1709 {
1710         int oerrno = errno;
1711
1712         sigint_raised = 1;
1713         alarmtimer(0);
1714         abrtflag++;
1715         errno = oerrno;
1716 }
1717
1718 void
1719 pswitch(int flag)
1720 {
1721         sigfunc oldintr;
1722         static struct comvars {
1723                 int connect;
1724                 char name[MAXHOSTNAMELEN];
1725                 struct sockinet mctl;
1726                 struct sockinet hctl;
1727                 FILE *in;
1728                 FILE *out;
1729                 int tpe;
1730                 int curtpe;
1731                 int cpnd;
1732                 int sunqe;
1733                 int runqe;
1734                 int mcse;
1735                 int ntflg;
1736                 char nti[17];
1737                 char nto[17];
1738                 int mapflg;
1739                 char mi[MAXPATHLEN];
1740                 char mo[MAXPATHLEN];
1741         } proxstruct, tmpstruct;
1742         struct comvars *ip, *op;
1743
1744         abrtflag = 0;
1745         oldintr = xsignal(SIGINT, psabort);
1746         if (flag) {
1747                 if (proxy)
1748                         return;
1749                 ip = &tmpstruct;
1750                 op = &proxstruct;
1751                 proxy++;
1752         } else {
1753                 if (!proxy)
1754                         return;
1755                 ip = &proxstruct;
1756                 op = &tmpstruct;
1757                 proxy = 0;
1758         }
1759         ip->connect = connected;
1760         connected = op->connect;
1761         if (hostname)
1762                 (void)strlcpy(ip->name, hostname, sizeof(ip->name));
1763         else
1764                 ip->name[0] = '\0';
1765         hostname = op->name;
1766         ip->hctl = hisctladdr;
1767         hisctladdr = op->hctl;
1768         ip->mctl = myctladdr;
1769         myctladdr = op->mctl;
1770         ip->in = cin;
1771         cin = op->in;
1772         ip->out = cout;
1773         cout = op->out;
1774         ip->tpe = type;
1775         type = op->tpe;
1776         ip->curtpe = curtype;
1777         curtype = op->curtpe;
1778         ip->cpnd = cpend;
1779         cpend = op->cpnd;
1780         ip->sunqe = sunique;
1781         sunique = op->sunqe;
1782         ip->runqe = runique;
1783         runique = op->runqe;
1784         ip->mcse = mcase;
1785         mcase = op->mcse;
1786         ip->ntflg = ntflag;
1787         ntflag = op->ntflg;
1788         (void)strlcpy(ip->nti, ntin, sizeof(ip->nti));
1789         (void)strlcpy(ntin, op->nti, sizeof(ntin));
1790         (void)strlcpy(ip->nto, ntout, sizeof(ip->nto));
1791         (void)strlcpy(ntout, op->nto, sizeof(ntout));
1792         ip->mapflg = mapflag;
1793         mapflag = op->mapflg;
1794         (void)strlcpy(ip->mi, mapin, sizeof(ip->mi));
1795         (void)strlcpy(mapin, op->mi, sizeof(mapin));
1796         (void)strlcpy(ip->mo, mapout, sizeof(ip->mo));
1797         (void)strlcpy(mapout, op->mo, sizeof(mapout));
1798         (void)xsignal(SIGINT, oldintr);
1799         if (abrtflag) {
1800                 abrtflag = 0;
1801                 (*oldintr)(SIGINT);
1802         }
1803 }
1804
1805 void
1806 abortpt(int notused)
1807 {
1808
1809         sigint_raised = 1;
1810         alarmtimer(0);
1811         if (fromatty)
1812                 write(fileno(ttyout), "\n", 1);
1813         ptabflg++;
1814         mflag = 0;
1815         abrtflag = 0;
1816         siglongjmp(ptabort, 1);
1817 }
1818
1819 void
1820 proxtrans(const char *cmd, const char *local, const char *remote)
1821 {
1822         sigfunc volatile oldintr;
1823         int prox_type, nfnd;
1824         int volatile secndflag;
1825         char *volatile cmd2;
1826
1827         oldintr = NULL;
1828         secndflag = 0;
1829         if (strcmp(cmd, "RETR"))
1830                 cmd2 = "RETR";
1831         else
1832                 cmd2 = runique ? "STOU" : "STOR";
1833         if ((prox_type = type) == 0) {
1834                 if (unix_server && unix_proxy)
1835                         prox_type = TYPE_I;
1836                 else
1837                         prox_type = TYPE_A;
1838         }
1839         if (curtype != prox_type)
1840                 changetype(prox_type, 1);
1841         if (command("PASV") != COMPLETE) {
1842                 fputs("proxy server does not support third party transfers.\n",
1843                     ttyout);
1844                 return;
1845         }
1846         pswitch(0);
1847         if (!connected) {
1848                 fputs("No primary connection.\n", ttyout);
1849                 pswitch(1);
1850                 code = -1;
1851                 return;
1852         }
1853         if (curtype != prox_type)
1854                 changetype(prox_type, 1);
1855         if (command("PORT %s", pasv) != COMPLETE) {
1856                 pswitch(1);
1857                 return;
1858         }
1859         if (sigsetjmp(ptabort, 1))
1860                 goto abort;
1861         oldintr = xsignal(SIGINT, abortpt);
1862         if ((restart_point &&
1863             (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1864             || (command("%s %s", cmd, remote) != PRELIM)) {
1865                 (void)xsignal(SIGINT, oldintr);
1866                 pswitch(1);
1867                 return;
1868         }
1869         sleep(2);
1870         pswitch(1);
1871         secndflag++;
1872         if ((restart_point &&
1873             (command("REST " LLF, (LLT) restart_point) != CONTINUE))
1874             || (command("%s %s", cmd2, local) != PRELIM))
1875                 goto abort;
1876         ptflag++;
1877         (void)getreply(0);
1878         pswitch(0);
1879         (void)getreply(0);
1880         (void)xsignal(SIGINT, oldintr);
1881         pswitch(1);
1882         ptflag = 0;
1883         fprintf(ttyout, "local: %s remote: %s\n", local, remote);
1884         return;
1885  abort:
1886         if (sigsetjmp(xferabort, 1)) {
1887                 (void)xsignal(SIGINT, oldintr);
1888                 return;
1889         }
1890         (void)xsignal(SIGINT, abort_squared);
1891         ptflag = 0;
1892         if (strcmp(cmd, "RETR") && !proxy)
1893                 pswitch(1);
1894         else if (!strcmp(cmd, "RETR") && proxy)
1895                 pswitch(0);
1896         if (!cpend && !secndflag) {  /* only here if cmd = "STOR" (proxy=1) */
1897                 if (command("%s %s", cmd2, local) != PRELIM) {
1898                         pswitch(0);
1899                         if (cpend)
1900                                 abort_remote(NULL);
1901                 }
1902                 pswitch(1);
1903                 if (ptabflg)
1904                         code = -1;
1905                 (void)xsignal(SIGINT, oldintr);
1906                 return;
1907         }
1908         if (cpend)
1909                 abort_remote(NULL);
1910         pswitch(!proxy);
1911         if (!cpend && !secndflag) {  /* only if cmd = "RETR" (proxy=1) */
1912                 if (command("%s %s", cmd2, local) != PRELIM) {
1913                         pswitch(0);
1914                         if (cpend)
1915                                 abort_remote(NULL);
1916                         pswitch(1);
1917                         if (ptabflg)
1918                                 code = -1;
1919                         (void)xsignal(SIGINT, oldintr);
1920                         return;
1921                 }
1922         }
1923         if (cpend)
1924                 abort_remote(NULL);
1925         pswitch(!proxy);
1926         if (cpend) {
1927                 if ((nfnd = empty(cin, NULL, 10)) <= 0) {
1928                         if (nfnd < 0)
1929                                 warn("Error aborting proxy command");
1930                         if (ptabflg)
1931                                 code = -1;
1932                         lostpeer(0);
1933                 }
1934                 (void)getreply(0);
1935                 (void)getreply(0);
1936         }
1937         if (proxy)
1938                 pswitch(0);
1939         pswitch(1);
1940         if (ptabflg)
1941                 code = -1;
1942         (void)xsignal(SIGINT, oldintr);
1943 }
1944
1945 void
1946 reset(int argc, char *argv[])
1947 {
1948         int nfnd = 1;
1949
1950         if (argc == 0 && argv != NULL) {
1951                 UPRINTF("usage: %s\n", argv[0]);
1952                 code = -1;
1953                 return;
1954         }
1955         while (nfnd > 0) {
1956                 if ((nfnd = empty(cin, NULL, 0)) < 0) {
1957                         warn("Error resetting connection");
1958                         code = -1;
1959                         lostpeer(0);
1960                 } else if (nfnd)
1961                         (void)getreply(0);
1962         }
1963 }
1964
1965 char *
1966 gunique(const char *local)
1967 {
1968         static char new[MAXPATHLEN];
1969         char *cp = strrchr(local, '/');
1970         int d, count=0, len;
1971         char ext = '1';
1972
1973         if (cp)
1974                 *cp = '\0';
1975         d = access(cp == local ? "/" : cp ? local : ".", W_OK);
1976         if (cp)
1977                 *cp = '/';
1978         if (d < 0) {
1979                 warn("Can't access `%s'", local);
1980                 return (NULL);
1981         }
1982         len = strlcpy(new, local, sizeof(new));
1983         cp = &new[len];
1984         *cp++ = '.';
1985         while (!d) {
1986                 if (++count == 100) {
1987                         fputs("runique: can't find unique file name.\n",
1988                             ttyout);
1989                         return (NULL);
1990                 }
1991                 *cp++ = ext;
1992                 *cp = '\0';
1993                 if (ext == '9')
1994                         ext = '0';
1995                 else
1996                         ext++;
1997                 if ((d = access(new, F_OK)) < 0)
1998                         break;
1999                 if (ext != '0')
2000                         cp--;
2001                 else if (*(cp - 2) == '.')
2002                         *(cp - 1) = '1';
2003                 else {
2004                         *(cp - 2) = *(cp - 2) + 1;
2005                         cp--;
2006                 }
2007         }
2008         return (new);
2009 }
2010
2011 /*
2012  * abort_squared --
2013  *      aborts abort_remote(). lostpeer() is called because if the user is
2014  *      too impatient to wait or there's another problem then ftp really
2015  *      needs to get back to a known state.
2016  */
2017 void
2018 abort_squared(int dummy)
2019 {
2020         char msgbuf[100];
2021         size_t len;
2022
2023         sigint_raised = 1;
2024         alarmtimer(0);
2025         len = strlcpy(msgbuf, "\nremote abort aborted; closing connection.\n",
2026             sizeof(msgbuf));
2027         write(fileno(ttyout), msgbuf, len);
2028         lostpeer(0);
2029         siglongjmp(xferabort, 1);
2030 }
2031
2032 void
2033 abort_remote(FILE *din)
2034 {
2035         char buf[BUFSIZ];
2036         int nfnd;
2037
2038         if (cout == NULL) {
2039                 warnx("Lost control connection for abort");
2040                 if (ptabflg)
2041                         code = -1;
2042                 lostpeer(0);
2043                 return;
2044         }
2045         /*
2046          * send IAC in urgent mode instead of DM because 4.3BSD places oob mark
2047          * after urgent byte rather than before as is protocol now
2048          */
2049         buf[0] = IAC;
2050         buf[1] = IP;
2051         buf[2] = IAC;
2052         if (send(fileno(cout), buf, 3, MSG_OOB) != 3)
2053                 warn("Can't send abort message");
2054         fprintf(cout, "%cABOR\r\n", DM);
2055         (void)fflush(cout);
2056         if ((nfnd = empty(cin, din, 10)) <= 0) {
2057                 if (nfnd < 0)
2058                         warn("Can't send abort message");
2059                 if (ptabflg)
2060                         code = -1;
2061                 lostpeer(0);
2062         }
2063         if (din && (nfnd & 2)) {
2064                 while (read(fileno(din), buf, BUFSIZ) > 0)
2065                         continue;
2066         }
2067         if (getreply(0) == ERROR && code == 552) {
2068                 /* 552 needed for nic style abort */
2069                 (void)getreply(0);
2070         }
2071         (void)getreply(0);
2072 }
2073
2074 /*
2075  * Ensure that ai->ai_addr is NOT an IPv4 mapped address.
2076  * IPv4 mapped address complicates too many things in FTP
2077  * protocol handling, as FTP protocol is defined differently
2078  * between IPv4 and IPv6.
2079  *
2080  * This may not be the best way to handle this situation,
2081  * since the semantics of IPv4 mapped address is defined in
2082  * the kernel.  There are configurations where we should use
2083  * IPv4 mapped address as native IPv6 address, not as
2084  * "an IPv6 address that embeds IPv4 address" (namely, SIIT).
2085  *
2086  * More complete solution would be to have an additional
2087  * getsockopt to grab "real" peername/sockname.  "real"
2088  * peername/sockname will be AF_INET if IPv4 mapped address
2089  * is used to embed IPv4 address, and will be AF_INET6 if
2090  * we use it as native.  What a mess!
2091  */
2092 void
2093 ai_unmapped(struct addrinfo *ai)
2094 {
2095 #ifdef INET6
2096         struct sockaddr_in6 *sin6;
2097         struct sockaddr_in sin;
2098         socklen_t len;
2099
2100         if (ai->ai_family != AF_INET6)
2101                 return;
2102         if (ai->ai_addrlen != sizeof(struct sockaddr_in6) ||
2103             sizeof(sin) > ai->ai_addrlen)
2104                 return;
2105         sin6 = (struct sockaddr_in6 *)ai->ai_addr;
2106         if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
2107                 return;
2108
2109         memset(&sin, 0, sizeof(sin));
2110         sin.sin_family = AF_INET;
2111         len = sizeof(struct sockaddr_in);
2112         memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
2113             sizeof(sin.sin_addr));
2114         sin.sin_port = sin6->sin6_port;
2115
2116         ai->ai_family = AF_INET;
2117 #if defined(HAVE_STRUCT_SOCKADDR_SA_LEN)
2118         sin.sin_len = len;
2119 #endif
2120         memcpy(ai->ai_addr, &sin, len);
2121         ai->ai_addrlen = len;
2122 #endif
2123 }
2124
2125 #ifdef NO_USAGE
2126 void
2127 xusage(void)
2128 {
2129         fputs("Usage error\n", ttyout);
2130 }
2131 #endif