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