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