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