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