1 /*- 2 * Copyright (c) 1998-2004 Dag-Erling Co�dan Sm�rgrav 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer 10 * in this position and unchanged. 11 * 2. Redistributions in binary form must reproduce the above copyright 12 * notice, this list of conditions and the following disclaimer in the 13 * documentation and/or other materials provided with the distribution. 14 * 3. The name of the author may not be used to endorse or promote products 15 * derived from this software without specific prior written permission 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 */ 28 29 #include <sys/cdefs.h> 30 __FBSDID("$FreeBSD$"); 31 32 /* 33 * Portions of this code were taken from or based on ftpio.c: 34 * 35 * ---------------------------------------------------------------------------- 36 * "THE BEER-WARE LICENSE" (Revision 42): 37 * <phk@FreeBSD.org> wrote this file. As long as you retain this notice you 38 * can do whatever you want with this stuff. If we meet some day, and you think 39 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp 40 * ---------------------------------------------------------------------------- 41 * 42 * Major Changelog: 43 * 44 * Dag-Erling Co�dan Sm�rgrav 45 * 9 Jun 1998 46 * 47 * Incorporated into libfetch 48 * 49 * Jordan K. Hubbard 50 * 17 Jan 1996 51 * 52 * Turned inside out. Now returns xfers as new file ids, not as a special 53 * `state' of FTP_t 54 * 55 * $ftpioId: ftpio.c,v 1.30 1998/04/11 07:28:53 phk Exp $ 56 * 57 */ 58 59 #include <sys/param.h> 60 #include <sys/socket.h> 61 #include <netinet/in.h> 62 63 #include <ctype.h> 64 #include <err.h> 65 #include <errno.h> 66 #include <fcntl.h> 67 #include <netdb.h> 68 #include <stdarg.h> 69 #include <stdint.h> 70 #include <stdio.h> 71 #include <stdlib.h> 72 #include <string.h> 73 #include <time.h> 74 #include <unistd.h> 75 76 #include "fetch.h" 77 #include "common.h" 78 #include "ftperr.h" 79 80 #define FTP_ANONYMOUS_USER "anonymous" 81 82 #define FTP_CONNECTION_ALREADY_OPEN 125 83 #define FTP_OPEN_DATA_CONNECTION 150 84 #define FTP_OK 200 85 #define FTP_FILE_STATUS 213 86 #define FTP_SERVICE_READY 220 87 #define FTP_TRANSFER_COMPLETE 226 88 #define FTP_PASSIVE_MODE 227 89 #define FTP_LPASSIVE_MODE 228 90 #define FTP_EPASSIVE_MODE 229 91 #define FTP_LOGGED_IN 230 92 #define FTP_FILE_ACTION_OK 250 93 #define FTP_DIRECTORY_CREATED 257 /* multiple meanings */ 94 #define FTP_FILE_CREATED 257 /* multiple meanings */ 95 #define FTP_WORKING_DIRECTORY 257 /* multiple meanings */ 96 #define FTP_NEED_PASSWORD 331 97 #define FTP_NEED_ACCOUNT 332 98 #define FTP_FILE_OK 350 99 #define FTP_SYNTAX_ERROR 500 100 #define FTP_PROTOCOL_ERROR 999 101 102 static struct url cached_host; 103 static conn_t *cached_connection; 104 105 #define isftpreply(foo) \ 106 (isdigit((unsigned char)foo[0]) && \ 107 isdigit((unsigned char)foo[1]) && \ 108 isdigit((unsigned char)foo[2]) && \ 109 (foo[3] == ' ' || foo[3] == '\0')) 110 #define isftpinfo(foo) \ 111 (isdigit((unsigned char)foo[0]) && \ 112 isdigit((unsigned char)foo[1]) && \ 113 isdigit((unsigned char)foo[2]) && \ 114 foo[3] == '-') 115 116 /* 117 * Translate IPv4 mapped IPv6 address to IPv4 address 118 */ 119 static void 120 unmappedaddr(struct sockaddr_in6 *sin6) 121 { 122 struct sockaddr_in *sin4; 123 u_int32_t addr; 124 int port; 125 126 if (sin6->sin6_family != AF_INET6 || 127 !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) 128 return; 129 sin4 = (struct sockaddr_in *)sin6; 130 addr = *(u_int32_t *)&sin6->sin6_addr.s6_addr[12]; 131 port = sin6->sin6_port; 132 memset(sin4, 0, sizeof(struct sockaddr_in)); 133 sin4->sin_addr.s_addr = addr; 134 sin4->sin_port = port; 135 sin4->sin_family = AF_INET; 136 sin4->sin_len = sizeof(struct sockaddr_in); 137 } 138 139 /* 140 * Get server response 141 */ 142 static int 143 ftp_chkerr(conn_t *conn) 144 { 145 if (fetch_getln(conn) == -1) { 146 fetch_syserr(); 147 return (-1); 148 } 149 if (isftpinfo(conn->buf)) { 150 while (conn->buflen && !isftpreply(conn->buf)) { 151 if (fetch_getln(conn) == -1) { 152 fetch_syserr(); 153 return (-1); 154 } 155 } 156 } 157 158 while (conn->buflen && 159 isspace((unsigned char)conn->buf[conn->buflen - 1])) 160 conn->buflen--; 161 conn->buf[conn->buflen] = '\0'; 162 163 if (!isftpreply(conn->buf)) { 164 ftp_seterr(FTP_PROTOCOL_ERROR); 165 return (-1); 166 } 167 168 conn->err = (conn->buf[0] - '0') * 100 169 + (conn->buf[1] - '0') * 10 170 + (conn->buf[2] - '0'); 171 172 return (conn->err); 173 } 174 175 /* 176 * Send a command and check reply 177 */ 178 static int 179 ftp_cmd(conn_t *conn, const char *fmt, ...) 180 { 181 va_list ap; 182 size_t len; 183 char *msg; 184 int r; 185 186 va_start(ap, fmt); 187 len = vasprintf(&msg, fmt, ap); 188 va_end(ap); 189 190 if (msg == NULL) { 191 errno = ENOMEM; 192 fetch_syserr(); 193 return (-1); 194 } 195 196 r = fetch_putln(conn, msg, len); 197 free(msg); 198 199 if (r == -1) { 200 fetch_syserr(); 201 return (-1); 202 } 203 204 return (ftp_chkerr(conn)); 205 } 206 207 /* 208 * Return a pointer to the filename part of a path 209 */ 210 static const char * 211 ftp_filename(const char *file, int *len, int *type) 212 { 213 const char *s; 214 215 if ((s = strrchr(file, '/')) == NULL) 216 s = file; 217 else 218 s = s + 1; 219 *len = strlen(s); 220 if (*len > 7 && strncmp(s + *len - 7, ";type=", 6) == 0) { 221 *type = s[*len - 1]; 222 *len -= 7; 223 } else { 224 *type = '\0'; 225 } 226 return (s); 227 } 228 229 /* 230 * Get current working directory from the reply to a CWD, PWD or CDUP 231 * command. 232 */ 233 static int 234 ftp_pwd(conn_t *conn, char *pwd, size_t pwdlen) 235 { 236 char *src, *dst, *end; 237 int q; 238 239 if (conn->err != FTP_WORKING_DIRECTORY && 240 conn->err != FTP_FILE_ACTION_OK) 241 return (FTP_PROTOCOL_ERROR); 242 end = conn->buf + conn->buflen; 243 src = conn->buf + 4; 244 if (src >= end || *src++ != '"') 245 return (FTP_PROTOCOL_ERROR); 246 for (q = 0, dst = pwd; src < end && pwdlen--; ++src) { 247 if (!q && *src == '"') 248 q = 1; 249 else if (q && *src != '"') 250 break; 251 else if (q) 252 *dst++ = '"', q = 0; 253 else 254 *dst++ = *src; 255 } 256 if (!pwdlen) 257 return (FTP_PROTOCOL_ERROR); 258 *dst = '\0'; 259 #if 0 260 DEBUG(fprintf(stderr, "pwd: [%s]\n", pwd)); 261 #endif 262 return (FTP_OK); 263 } 264 265 /* 266 * Change working directory to the directory that contains the specified 267 * file. 268 */ 269 static int 270 ftp_cwd(conn_t *conn, const char *file) 271 { 272 const char *beg, *end; 273 char pwd[PATH_MAX]; 274 int e, i, len; 275 276 /* If no slashes in name, no need to change dirs. */ 277 if ((end = strrchr(file, '/')) == NULL) 278 return (0); 279 if ((e = ftp_cmd(conn, "PWD")) != FTP_WORKING_DIRECTORY || 280 (e = ftp_pwd(conn, pwd, sizeof(pwd))) != FTP_OK) { 281 ftp_seterr(e); 282 return (-1); 283 } 284 for (;;) { 285 len = strlen(pwd); 286 287 /* Look for a common prefix between PWD and dir to fetch. */ 288 for (i = 0; i <= len && i <= end - file; ++i) 289 if (pwd[i] != file[i]) 290 break; 291 #if 0 292 DEBUG(fprintf(stderr, "have: [%.*s|%s]\n", i, pwd, pwd + i)); 293 DEBUG(fprintf(stderr, "want: [%.*s|%s]\n", i, file, file + i)); 294 #endif 295 /* Keep going up a dir until we have a matching prefix. */ 296 if (pwd[i] == '\0' && (file[i - 1] == '/' || file[i] == '/')) 297 break; 298 if ((e = ftp_cmd(conn, "CDUP")) != FTP_FILE_ACTION_OK || 299 (e = ftp_cmd(conn, "PWD")) != FTP_WORKING_DIRECTORY || 300 (e = ftp_pwd(conn, pwd, sizeof(pwd))) != FTP_OK) { 301 ftp_seterr(e); 302 return (-1); 303 } 304 } 305 306 #ifdef FTP_COMBINE_CWDS 307 /* Skip leading slashes, even "////". */ 308 for (beg = file + i; beg < end && *beg == '/'; ++beg, ++i) 309 /* nothing */ ; 310 311 /* If there is no trailing dir, we're already there. */ 312 if (beg >= end) 313 return (0); 314 315 /* Change to the directory all in one chunk (e.g., foo/bar/baz). */ 316 e = ftp_cmd(conn, "CWD %.*s", (int)(end - beg), beg); 317 if (e == FTP_FILE_ACTION_OK) 318 return (0); 319 #endif /* FTP_COMBINE_CWDS */ 320 321 /* That didn't work so go back to legacy behavior (multiple CWDs). */ 322 for (beg = file + i; beg < end; beg = file + i + 1) { 323 while (*beg == '/') 324 ++beg, ++i; 325 for (++i; file + i < end && file[i] != '/'; ++i) 326 /* nothing */ ; 327 e = ftp_cmd(conn, "CWD %.*s", file + i - beg, beg); 328 if (e != FTP_FILE_ACTION_OK) { 329 ftp_seterr(e); 330 return (-1); 331 } 332 } 333 return (0); 334 } 335 336 /* 337 * Set transfer mode and data type 338 */ 339 static int 340 ftp_mode_type(conn_t *conn, int mode, int type) 341 { 342 int e; 343 344 switch (mode) { 345 case 0: 346 case 's': 347 mode = 'S'; 348 case 'S': 349 break; 350 default: 351 return (FTP_PROTOCOL_ERROR); 352 } 353 if ((e = ftp_cmd(conn, "MODE %c", mode)) != FTP_OK) { 354 if (mode == 'S') { 355 /* 356 * Stream mode is supposed to be the default - so 357 * much so that some servers not only do not 358 * support any other mode, but do not support the 359 * MODE command at all. 360 * 361 * If "MODE S" fails, it is unlikely that we 362 * previously succeeded in setting a different 363 * mode. Therefore, we simply hope that the 364 * server is already in the correct mode, and 365 * silently ignore the failure. 366 */ 367 } else { 368 return (e); 369 } 370 } 371 372 switch (type) { 373 case 0: 374 case 'i': 375 type = 'I'; 376 case 'I': 377 break; 378 case 'a': 379 type = 'A'; 380 case 'A': 381 break; 382 case 'd': 383 type = 'D'; 384 case 'D': 385 /* can't handle yet */ 386 default: 387 return (FTP_PROTOCOL_ERROR); 388 } 389 if ((e = ftp_cmd(conn, "TYPE %c", type)) != FTP_OK) 390 return (e); 391 392 return (FTP_OK); 393 } 394 395 /* 396 * Request and parse file stats 397 */ 398 static int 399 ftp_stat(conn_t *conn, const char *file, struct url_stat *us) 400 { 401 char *ln; 402 const char *filename; 403 int filenamelen, type; 404 struct tm tm; 405 time_t t; 406 int e; 407 408 us->size = -1; 409 us->atime = us->mtime = 0; 410 411 filename = ftp_filename(file, &filenamelen, &type); 412 413 if ((e = ftp_mode_type(conn, 0, type)) != FTP_OK) { 414 ftp_seterr(e); 415 return (-1); 416 } 417 418 e = ftp_cmd(conn, "SIZE %.*s", filenamelen, filename); 419 if (e != FTP_FILE_STATUS) { 420 ftp_seterr(e); 421 return (-1); 422 } 423 for (ln = conn->buf + 4; *ln && isspace((unsigned char)*ln); ln++) 424 /* nothing */ ; 425 for (us->size = 0; *ln && isdigit((unsigned char)*ln); ln++) 426 us->size = us->size * 10 + *ln - '0'; 427 if (*ln && !isspace((unsigned char)*ln)) { 428 ftp_seterr(FTP_PROTOCOL_ERROR); 429 us->size = -1; 430 return (-1); 431 } 432 if (us->size == 0) 433 us->size = -1; 434 DEBUG(fprintf(stderr, "size: [%lld]\n", (long long)us->size)); 435 436 e = ftp_cmd(conn, "MDTM %.*s", filenamelen, filename); 437 if (e != FTP_FILE_STATUS) { 438 ftp_seterr(e); 439 return (-1); 440 } 441 for (ln = conn->buf + 4; *ln && isspace((unsigned char)*ln); ln++) 442 /* nothing */ ; 443 switch (strspn(ln, "0123456789")) { 444 case 14: 445 break; 446 case 15: 447 ln++; 448 ln[0] = '2'; 449 ln[1] = '0'; 450 break; 451 default: 452 ftp_seterr(FTP_PROTOCOL_ERROR); 453 return (-1); 454 } 455 if (sscanf(ln, "%04d%02d%02d%02d%02d%02d", 456 &tm.tm_year, &tm.tm_mon, &tm.tm_mday, 457 &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) { 458 ftp_seterr(FTP_PROTOCOL_ERROR); 459 return (-1); 460 } 461 tm.tm_mon--; 462 tm.tm_year -= 1900; 463 tm.tm_isdst = -1; 464 t = timegm(&tm); 465 if (t == (time_t)-1) 466 t = time(NULL); 467 us->mtime = t; 468 us->atime = t; 469 DEBUG(fprintf(stderr, 470 "last modified: [%04d-%02d-%02d %02d:%02d:%02d]\n", 471 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, 472 tm.tm_hour, tm.tm_min, tm.tm_sec)); 473 return (0); 474 } 475 476 /* 477 * I/O functions for FTP 478 */ 479 struct ftpio { 480 conn_t *cconn; /* Control connection */ 481 conn_t *dconn; /* Data connection */ 482 int dir; /* Direction */ 483 int eof; /* EOF reached */ 484 int err; /* Error code */ 485 }; 486 487 static int ftp_readfn(void *, char *, int); 488 static int ftp_writefn(void *, const char *, int); 489 static fpos_t ftp_seekfn(void *, fpos_t, int); 490 static int ftp_closefn(void *); 491 492 static int 493 ftp_readfn(void *v, char *buf, int len) 494 { 495 struct ftpio *io; 496 int r; 497 498 io = (struct ftpio *)v; 499 if (io == NULL) { 500 errno = EBADF; 501 return (-1); 502 } 503 if (io->cconn == NULL || io->dconn == NULL || io->dir == O_WRONLY) { 504 errno = EBADF; 505 return (-1); 506 } 507 if (io->err) { 508 errno = io->err; 509 return (-1); 510 } 511 if (io->eof) 512 return (0); 513 r = fetch_read(io->dconn, buf, len); 514 if (r > 0) 515 return (r); 516 if (r == 0) { 517 io->eof = 1; 518 return (0); 519 } 520 if (errno != EINTR) 521 io->err = errno; 522 return (-1); 523 } 524 525 static int 526 ftp_writefn(void *v, const char *buf, int len) 527 { 528 struct ftpio *io; 529 int w; 530 531 io = (struct ftpio *)v; 532 if (io == NULL) { 533 errno = EBADF; 534 return (-1); 535 } 536 if (io->cconn == NULL || io->dconn == NULL || io->dir == O_RDONLY) { 537 errno = EBADF; 538 return (-1); 539 } 540 if (io->err) { 541 errno = io->err; 542 return (-1); 543 } 544 w = fetch_write(io->dconn, buf, len); 545 if (w >= 0) 546 return (w); 547 if (errno != EINTR) 548 io->err = errno; 549 return (-1); 550 } 551 552 static fpos_t 553 ftp_seekfn(void *v, fpos_t pos __unused, int whence __unused) 554 { 555 struct ftpio *io; 556 557 io = (struct ftpio *)v; 558 if (io == NULL) { 559 errno = EBADF; 560 return (-1); 561 } 562 errno = ESPIPE; 563 return (-1); 564 } 565 566 static int 567 ftp_closefn(void *v) 568 { 569 struct ftpio *io; 570 int r; 571 572 io = (struct ftpio *)v; 573 if (io == NULL) { 574 errno = EBADF; 575 return (-1); 576 } 577 if (io->dir == -1) 578 return (0); 579 if (io->cconn == NULL || io->dconn == NULL) { 580 errno = EBADF; 581 return (-1); 582 } 583 fetch_close(io->dconn); 584 io->dir = -1; 585 io->dconn = NULL; 586 DEBUG(fprintf(stderr, "Waiting for final status\n")); 587 r = ftp_chkerr(io->cconn); 588 if (io->cconn == cached_connection && io->cconn->ref == 1) 589 cached_connection = NULL; 590 fetch_close(io->cconn); 591 free(io); 592 return (r == FTP_TRANSFER_COMPLETE) ? 0 : -1; 593 } 594 595 static FILE * 596 ftp_setup(conn_t *cconn, conn_t *dconn, int mode) 597 { 598 struct ftpio *io; 599 FILE *f; 600 601 if (cconn == NULL || dconn == NULL) 602 return (NULL); 603 if ((io = malloc(sizeof(*io))) == NULL) 604 return (NULL); 605 io->cconn = cconn; 606 io->dconn = dconn; 607 io->dir = mode; 608 io->eof = io->err = 0; 609 f = funopen(io, ftp_readfn, ftp_writefn, ftp_seekfn, ftp_closefn); 610 if (f == NULL) 611 free(io); 612 return (f); 613 } 614 615 /* 616 * Transfer file 617 */ 618 static FILE * 619 ftp_transfer(conn_t *conn, const char *oper, const char *file, 620 int mode, off_t offset, const char *flags) 621 { 622 struct sockaddr_storage sa; 623 struct sockaddr_in6 *sin6; 624 struct sockaddr_in *sin4; 625 const char *bindaddr; 626 const char *filename; 627 int filenamelen, type; 628 int low, pasv, verbose; 629 int e, sd = -1; 630 socklen_t l; 631 char *s; 632 FILE *df; 633 634 /* check flags */ 635 low = CHECK_FLAG('l'); 636 pasv = CHECK_FLAG('p'); 637 verbose = CHECK_FLAG('v'); 638 639 /* passive mode */ 640 if (!pasv) 641 pasv = ((s = getenv("FTP_PASSIVE_MODE")) != NULL && 642 strncasecmp(s, "no", 2) != 0); 643 644 /* isolate filename */ 645 filename = ftp_filename(file, &filenamelen, &type); 646 647 /* set transfer mode and data type */ 648 if ((e = ftp_mode_type(conn, 0, type)) != FTP_OK) 649 goto ouch; 650 651 /* find our own address, bind, and listen */ 652 l = sizeof(sa); 653 if (getsockname(conn->sd, (struct sockaddr *)&sa, &l) == -1) 654 goto sysouch; 655 if (sa.ss_family == AF_INET6) 656 unmappedaddr((struct sockaddr_in6 *)&sa); 657 658 /* open data socket */ 659 if ((sd = socket(sa.ss_family, SOCK_STREAM, IPPROTO_TCP)) == -1) { 660 fetch_syserr(); 661 return (NULL); 662 } 663 664 if (pasv) { 665 u_char addr[64]; 666 char *ln, *p; 667 unsigned int i; 668 int port; 669 670 /* send PASV command */ 671 if (verbose) 672 fetch_info("setting passive mode"); 673 switch (sa.ss_family) { 674 case AF_INET: 675 if ((e = ftp_cmd(conn, "PASV")) != FTP_PASSIVE_MODE) 676 goto ouch; 677 break; 678 case AF_INET6: 679 if ((e = ftp_cmd(conn, "EPSV")) != FTP_EPASSIVE_MODE) { 680 if (e == -1) 681 goto ouch; 682 if ((e = ftp_cmd(conn, "LPSV")) != 683 FTP_LPASSIVE_MODE) 684 goto ouch; 685 } 686 break; 687 default: 688 e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */ 689 goto ouch; 690 } 691 692 /* 693 * Find address and port number. The reply to the PASV command 694 * is IMHO the one and only weak point in the FTP protocol. 695 */ 696 ln = conn->buf; 697 switch (e) { 698 case FTP_PASSIVE_MODE: 699 case FTP_LPASSIVE_MODE: 700 for (p = ln + 3; *p && !isdigit((unsigned char)*p); p++) 701 /* nothing */ ; 702 if (!*p) { 703 e = FTP_PROTOCOL_ERROR; 704 goto ouch; 705 } 706 l = (e == FTP_PASSIVE_MODE ? 6 : 21); 707 for (i = 0; *p && i < l; i++, p++) 708 addr[i] = strtol(p, &p, 10); 709 if (i < l) { 710 e = FTP_PROTOCOL_ERROR; 711 goto ouch; 712 } 713 break; 714 case FTP_EPASSIVE_MODE: 715 for (p = ln + 3; *p && *p != '('; p++) 716 /* nothing */ ; 717 if (!*p) { 718 e = FTP_PROTOCOL_ERROR; 719 goto ouch; 720 } 721 ++p; 722 if (sscanf(p, "%c%c%c%d%c", &addr[0], &addr[1], &addr[2], 723 &port, &addr[3]) != 5 || 724 addr[0] != addr[1] || 725 addr[0] != addr[2] || addr[0] != addr[3]) { 726 e = FTP_PROTOCOL_ERROR; 727 goto ouch; 728 } 729 break; 730 } 731 732 /* seek to required offset */ 733 if (offset) 734 if (ftp_cmd(conn, "REST %lu", (u_long)offset) != FTP_FILE_OK) 735 goto sysouch; 736 737 /* construct sockaddr for data socket */ 738 l = sizeof(sa); 739 if (getpeername(conn->sd, (struct sockaddr *)&sa, &l) == -1) 740 goto sysouch; 741 if (sa.ss_family == AF_INET6) 742 unmappedaddr((struct sockaddr_in6 *)&sa); 743 switch (sa.ss_family) { 744 case AF_INET6: 745 sin6 = (struct sockaddr_in6 *)&sa; 746 if (e == FTP_EPASSIVE_MODE) 747 sin6->sin6_port = htons(port); 748 else { 749 memcpy(&sin6->sin6_addr, addr + 2, 16); 750 memcpy(&sin6->sin6_port, addr + 19, 2); 751 } 752 break; 753 case AF_INET: 754 sin4 = (struct sockaddr_in *)&sa; 755 if (e == FTP_EPASSIVE_MODE) 756 sin4->sin_port = htons(port); 757 else { 758 memcpy(&sin4->sin_addr, addr, 4); 759 memcpy(&sin4->sin_port, addr + 4, 2); 760 } 761 break; 762 default: 763 e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */ 764 break; 765 } 766 767 /* connect to data port */ 768 if (verbose) 769 fetch_info("opening data connection"); 770 bindaddr = getenv("FETCH_BIND_ADDRESS"); 771 if (bindaddr != NULL && *bindaddr != '\0' && 772 fetch_bind(sd, sa.ss_family, bindaddr) != 0) 773 goto sysouch; 774 if (connect(sd, (struct sockaddr *)&sa, sa.ss_len) == -1) 775 goto sysouch; 776 777 /* make the server initiate the transfer */ 778 if (verbose) 779 fetch_info("initiating transfer"); 780 e = ftp_cmd(conn, "%s %.*s", oper, filenamelen, filename); 781 if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION) 782 goto ouch; 783 784 } else { 785 u_int32_t a; 786 u_short p; 787 int arg, d; 788 char *ap; 789 char hname[INET6_ADDRSTRLEN]; 790 791 switch (sa.ss_family) { 792 case AF_INET6: 793 ((struct sockaddr_in6 *)&sa)->sin6_port = 0; 794 #ifdef IPV6_PORTRANGE 795 arg = low ? IPV6_PORTRANGE_DEFAULT : IPV6_PORTRANGE_HIGH; 796 if (setsockopt(sd, IPPROTO_IPV6, IPV6_PORTRANGE, 797 (char *)&arg, sizeof(arg)) == -1) 798 goto sysouch; 799 #endif 800 break; 801 case AF_INET: 802 ((struct sockaddr_in *)&sa)->sin_port = 0; 803 arg = low ? IP_PORTRANGE_DEFAULT : IP_PORTRANGE_HIGH; 804 if (setsockopt(sd, IPPROTO_IP, IP_PORTRANGE, 805 (char *)&arg, sizeof(arg)) == -1) 806 goto sysouch; 807 break; 808 } 809 if (verbose) 810 fetch_info("binding data socket"); 811 if (bind(sd, (struct sockaddr *)&sa, sa.ss_len) == -1) 812 goto sysouch; 813 if (listen(sd, 1) == -1) 814 goto sysouch; 815 816 /* find what port we're on and tell the server */ 817 if (getsockname(sd, (struct sockaddr *)&sa, &l) == -1) 818 goto sysouch; 819 switch (sa.ss_family) { 820 case AF_INET: 821 sin4 = (struct sockaddr_in *)&sa; 822 a = ntohl(sin4->sin_addr.s_addr); 823 p = ntohs(sin4->sin_port); 824 e = ftp_cmd(conn, "PORT %d,%d,%d,%d,%d,%d", 825 (a >> 24) & 0xff, (a >> 16) & 0xff, 826 (a >> 8) & 0xff, a & 0xff, 827 (p >> 8) & 0xff, p & 0xff); 828 break; 829 case AF_INET6: 830 #define UC(b) (((int)b)&0xff) 831 e = -1; 832 sin6 = (struct sockaddr_in6 *)&sa; 833 sin6->sin6_scope_id = 0; 834 if (getnameinfo((struct sockaddr *)&sa, sa.ss_len, 835 hname, sizeof(hname), 836 NULL, 0, NI_NUMERICHOST) == 0) { 837 e = ftp_cmd(conn, "EPRT |%d|%s|%d|", 2, hname, 838 htons(sin6->sin6_port)); 839 if (e == -1) 840 goto ouch; 841 } 842 if (e != FTP_OK) { 843 ap = (char *)&sin6->sin6_addr; 844 e = ftp_cmd(conn, 845 "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d", 846 6, 16, 847 UC(ap[0]), UC(ap[1]), UC(ap[2]), UC(ap[3]), 848 UC(ap[4]), UC(ap[5]), UC(ap[6]), UC(ap[7]), 849 UC(ap[8]), UC(ap[9]), UC(ap[10]), UC(ap[11]), 850 UC(ap[12]), UC(ap[13]), UC(ap[14]), UC(ap[15]), 851 2, 852 (ntohs(sin6->sin6_port) >> 8) & 0xff, 853 ntohs(sin6->sin6_port) & 0xff); 854 } 855 break; 856 default: 857 e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */ 858 goto ouch; 859 } 860 if (e != FTP_OK) 861 goto ouch; 862 863 /* seek to required offset */ 864 if (offset) 865 if (ftp_cmd(conn, "REST %ju", (uintmax_t)offset) != FTP_FILE_OK) 866 goto sysouch; 867 868 /* make the server initiate the transfer */ 869 if (verbose) 870 fetch_info("initiating transfer"); 871 e = ftp_cmd(conn, "%s %.*s", oper, filenamelen, filename); 872 if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION) 873 goto ouch; 874 875 /* accept the incoming connection and go to town */ 876 if ((d = accept(sd, NULL, NULL)) == -1) 877 goto sysouch; 878 close(sd); 879 sd = d; 880 } 881 882 if ((df = ftp_setup(conn, fetch_reopen(sd), mode)) == NULL) 883 goto sysouch; 884 return (df); 885 886 sysouch: 887 fetch_syserr(); 888 if (sd >= 0) 889 close(sd); 890 return (NULL); 891 892 ouch: 893 if (e != -1) 894 ftp_seterr(e); 895 if (sd >= 0) 896 close(sd); 897 return (NULL); 898 } 899 900 /* 901 * Authenticate 902 */ 903 static int 904 ftp_authenticate(conn_t *conn, struct url *url, struct url *purl) 905 { 906 const char *user, *pwd, *logname; 907 char pbuf[MAXHOSTNAMELEN + MAXLOGNAME + 1]; 908 int e, len; 909 910 /* XXX FTP_AUTH, and maybe .netrc */ 911 912 /* send user name and password */ 913 if (url->user[0] == '\0') 914 fetch_netrc_auth(url); 915 user = url->user; 916 if (*user == '\0') 917 user = getenv("FTP_LOGIN"); 918 if (user == NULL || *user == '\0') 919 user = FTP_ANONYMOUS_USER; 920 if (purl && url->port == fetch_default_port(url->scheme)) 921 e = ftp_cmd(conn, "USER %s@%s", user, url->host); 922 else if (purl) 923 e = ftp_cmd(conn, "USER %s@%s@%d", user, url->host, url->port); 924 else 925 e = ftp_cmd(conn, "USER %s", user); 926 927 /* did the server request a password? */ 928 if (e == FTP_NEED_PASSWORD) { 929 pwd = url->pwd; 930 if (*pwd == '\0') 931 pwd = getenv("FTP_PASSWORD"); 932 if (pwd == NULL || *pwd == '\0') { 933 if ((logname = getlogin()) == 0) 934 logname = FTP_ANONYMOUS_USER; 935 if ((len = snprintf(pbuf, MAXLOGNAME + 1, "%s@", logname)) < 0) 936 len = 0; 937 else if (len > MAXLOGNAME) 938 len = MAXLOGNAME; 939 gethostname(pbuf + len, sizeof(pbuf) - len); 940 pwd = pbuf; 941 } 942 e = ftp_cmd(conn, "PASS %s", pwd); 943 } 944 945 return (e); 946 } 947 948 /* 949 * Log on to FTP server 950 */ 951 static conn_t * 952 ftp_connect(struct url *url, struct url *purl, const char *flags) 953 { 954 conn_t *conn; 955 int e, direct, verbose; 956 #ifdef INET6 957 int af = AF_UNSPEC; 958 #else 959 int af = AF_INET; 960 #endif 961 962 direct = CHECK_FLAG('d'); 963 verbose = CHECK_FLAG('v'); 964 if (CHECK_FLAG('4')) 965 af = AF_INET; 966 else if (CHECK_FLAG('6')) 967 af = AF_INET6; 968 969 if (direct) 970 purl = NULL; 971 972 /* check for proxy */ 973 if (purl) { 974 /* XXX proxy authentication! */ 975 conn = fetch_connect(purl->host, purl->port, af, verbose); 976 } else { 977 /* no proxy, go straight to target */ 978 conn = fetch_connect(url->host, url->port, af, verbose); 979 purl = NULL; 980 } 981 982 /* check connection */ 983 if (conn == NULL) 984 /* fetch_connect() has already set an error code */ 985 return (NULL); 986 987 /* expect welcome message */ 988 if ((e = ftp_chkerr(conn)) != FTP_SERVICE_READY) 989 goto fouch; 990 991 /* authenticate */ 992 if ((e = ftp_authenticate(conn, url, purl)) != FTP_LOGGED_IN) 993 goto fouch; 994 995 /* TODO: Request extended features supported, if any (RFC 3659). */ 996 997 /* done */ 998 return (conn); 999 1000 fouch: 1001 if (e != -1) 1002 ftp_seterr(e); 1003 fetch_close(conn); 1004 return (NULL); 1005 } 1006 1007 /* 1008 * Disconnect from server 1009 */ 1010 static void 1011 ftp_disconnect(conn_t *conn) 1012 { 1013 (void)ftp_cmd(conn, "QUIT"); 1014 if (conn == cached_connection && conn->ref == 1) 1015 cached_connection = NULL; 1016 fetch_close(conn); 1017 } 1018 1019 /* 1020 * Check if we're already connected 1021 */ 1022 static int 1023 ftp_isconnected(struct url *url) 1024 { 1025 return (cached_connection 1026 && (strcmp(url->host, cached_host.host) == 0) 1027 && (strcmp(url->user, cached_host.user) == 0) 1028 && (strcmp(url->pwd, cached_host.pwd) == 0) 1029 && (url->port == cached_host.port)); 1030 } 1031 1032 /* 1033 * Check the cache, reconnect if no luck 1034 */ 1035 static conn_t * 1036 ftp_cached_connect(struct url *url, struct url *purl, const char *flags) 1037 { 1038 conn_t *conn; 1039 int e; 1040 1041 /* set default port */ 1042 if (!url->port) 1043 url->port = fetch_default_port(url->scheme); 1044 1045 /* try to use previously cached connection */ 1046 if (ftp_isconnected(url)) { 1047 e = ftp_cmd(cached_connection, "NOOP"); 1048 if (e == FTP_OK || e == FTP_SYNTAX_ERROR) 1049 return (fetch_ref(cached_connection)); 1050 } 1051 1052 /* connect to server */ 1053 if ((conn = ftp_connect(url, purl, flags)) == NULL) 1054 return (NULL); 1055 if (cached_connection) 1056 ftp_disconnect(cached_connection); 1057 cached_connection = fetch_ref(conn); 1058 memcpy(&cached_host, url, sizeof(*url)); 1059 return (conn); 1060 } 1061 1062 /* 1063 * Check the proxy settings 1064 */ 1065 static struct url * 1066 ftp_get_proxy(struct url * url, const char *flags) 1067 { 1068 struct url *purl; 1069 char *p; 1070 1071 if (flags != NULL && strchr(flags, 'd') != NULL) 1072 return (NULL); 1073 if (fetch_no_proxy_match(url->host)) 1074 return (NULL); 1075 if (((p = getenv("FTP_PROXY")) || (p = getenv("ftp_proxy")) || 1076 (p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) && 1077 *p && (purl = fetchParseURL(p)) != NULL) { 1078 if (!*purl->scheme) { 1079 if (getenv("FTP_PROXY") || getenv("ftp_proxy")) 1080 strcpy(purl->scheme, SCHEME_FTP); 1081 else 1082 strcpy(purl->scheme, SCHEME_HTTP); 1083 } 1084 if (!purl->port) 1085 purl->port = fetch_default_proxy_port(purl->scheme); 1086 if (strcasecmp(purl->scheme, SCHEME_FTP) == 0 || 1087 strcasecmp(purl->scheme, SCHEME_HTTP) == 0) 1088 return (purl); 1089 fetchFreeURL(purl); 1090 } 1091 return (NULL); 1092 } 1093 1094 /* 1095 * Process an FTP request 1096 */ 1097 FILE * 1098 ftp_request(struct url *url, const char *op, struct url_stat *us, 1099 struct url *purl, const char *flags) 1100 { 1101 conn_t *conn; 1102 int oflag; 1103 1104 /* check if we should use HTTP instead */ 1105 if (purl && strcasecmp(purl->scheme, SCHEME_HTTP) == 0) { 1106 if (strcmp(op, "STAT") == 0) 1107 return (http_request(url, "HEAD", us, purl, flags)); 1108 else if (strcmp(op, "RETR") == 0) 1109 return (http_request(url, "GET", us, purl, flags)); 1110 /* 1111 * Our HTTP code doesn't support PUT requests yet, so try 1112 * a direct connection. 1113 */ 1114 } 1115 1116 /* connect to server */ 1117 conn = ftp_cached_connect(url, purl, flags); 1118 if (purl) 1119 fetchFreeURL(purl); 1120 if (conn == NULL) 1121 return (NULL); 1122 1123 /* change directory */ 1124 if (ftp_cwd(conn, url->doc) == -1) 1125 goto errsock; 1126 1127 /* stat file */ 1128 if (us && ftp_stat(conn, url->doc, us) == -1 1129 && fetchLastErrCode != FETCH_PROTO 1130 && fetchLastErrCode != FETCH_UNAVAIL) 1131 goto errsock; 1132 1133 /* just a stat */ 1134 if (strcmp(op, "STAT") == 0) { 1135 --conn->ref; 1136 ftp_disconnect(conn); 1137 return (FILE *)1; /* bogus return value */ 1138 } 1139 if (strcmp(op, "STOR") == 0 || strcmp(op, "APPE") == 0) 1140 oflag = O_WRONLY; 1141 else 1142 oflag = O_RDONLY; 1143 1144 /* initiate the transfer */ 1145 return (ftp_transfer(conn, op, url->doc, oflag, url->offset, flags)); 1146 1147 errsock: 1148 ftp_disconnect(conn); 1149 return (NULL); 1150 } 1151 1152 /* 1153 * Get and stat file 1154 */ 1155 FILE * 1156 fetchXGetFTP(struct url *url, struct url_stat *us, const char *flags) 1157 { 1158 return (ftp_request(url, "RETR", us, ftp_get_proxy(url, flags), flags)); 1159 } 1160 1161 /* 1162 * Get file 1163 */ 1164 FILE * 1165 fetchGetFTP(struct url *url, const char *flags) 1166 { 1167 return (fetchXGetFTP(url, NULL, flags)); 1168 } 1169 1170 /* 1171 * Put file 1172 */ 1173 FILE * 1174 fetchPutFTP(struct url *url, const char *flags) 1175 { 1176 return (ftp_request(url, CHECK_FLAG('a') ? "APPE" : "STOR", NULL, 1177 ftp_get_proxy(url, flags), flags)); 1178 } 1179 1180 /* 1181 * Get file stats 1182 */ 1183 int 1184 fetchStatFTP(struct url *url, struct url_stat *us, const char *flags) 1185 { 1186 FILE *f; 1187 1188 f = ftp_request(url, "STAT", us, ftp_get_proxy(url, flags), flags); 1189 if (f == NULL) 1190 return (-1); 1191 /* 1192 * When op is "STAT", ftp_request() will return either NULL or 1193 * (FILE *)1, never a valid FILE *, so we mustn't fclose(f) before 1194 * returning, as it would cause a segfault. 1195 */ 1196 return (0); 1197 } 1198 1199 /* 1200 * List a directory 1201 */ 1202 struct url_ent * 1203 fetchListFTP(struct url *url __unused, const char *flags __unused) 1204 { 1205 warnx("fetchListFTP(): not implemented"); 1206 return (NULL); 1207 } 1208