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