1 /* 2 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994 3 * The Regents of the University of California. 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 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. All advertising materials mentioning features or use of this software 14 * must display the following acknowledgement: 15 * This product includes software developed by the University of 16 * California, Berkeley and its contributors. 17 * 4. Neither the name of the University nor the names of its contributors 18 * may be used to endorse or promote products derived from this software 19 * without specific prior written permission. 20 * 21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 */ 33 34 #if 0 35 #ifndef lint 36 static char copyright[] = 37 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\ 38 The Regents of the University of California. All rights reserved.\n"; 39 #endif /* not lint */ 40 #endif 41 42 #ifndef lint 43 #if 0 44 static char sccsid[] = "@(#)ftpd.c 8.4 (Berkeley) 4/16/94"; 45 #endif 46 #endif /* not lint */ 47 48 #include <sys/cdefs.h> 49 __FBSDID("$FreeBSD: src/libexec/ftpd/ftpd.c,v 1.212 2007/04/18 22:43:39 yar Exp $"); 50 51 /* 52 * FTP server. 53 */ 54 #include <sys/param.h> 55 #include <sys/ioctl.h> 56 //#include <sys/mman.h> 57 #include <sys/socket.h> 58 #include <sys/stat.h> 59 #include <sys/time.h> 60 #include <sys/wait.h> 61 62 #include <netinet/in.h> 63 #include <netinet/in_systm.h> 64 #include <netinet/ip.h> 65 #include <netinet/tcp.h> 66 67 #define FTP_NAMES 68 #include <arpa/ftp.h> 69 #include <arpa/inet.h> 70 #include <arpa/telnet.h> 71 72 #include <ctype.h> 73 #include <dirent.h> 74 #include <err.h> 75 #include <errno.h> 76 #include <fcntl.h> 77 #include <glob.h> 78 #include <limits.h> 79 #include <netdb.h> 80 #include <pwd.h> 81 #include <grp.h> 82 #ifdef HAVE_LIBOPIE 83 #include <opie.h> 84 #endif 85 #include <signal.h> 86 #include <stdint.h> 87 #include <stdio.h> 88 #include <stdlib.h> 89 #include <string.h> 90 #include <syslog.h> 91 #include <time.h> 92 #include <unistd.h> 93 #include <libutil.h> 94 #ifdef LOGIN_CAP 95 #include <login_cap.h> 96 #endif 97 98 #ifdef USE_PAM 99 #include <security/pam_appl.h> 100 #endif 101 102 #ifdef __HAIKU__ 103 #include <shadow.h> 104 #endif 105 106 #include "pathnames.h" 107 #include "extern.h" 108 109 #include <stdarg.h> 110 111 static char version[] = "Version 6.00LS"; 112 #undef main 113 114 extern off_t restart_point; 115 extern char cbuf[]; 116 117 union sockunion ctrl_addr; 118 union sockunion data_source; 119 union sockunion data_dest; 120 union sockunion his_addr; 121 union sockunion pasv_addr; 122 123 int daemon_mode; 124 int data; 125 int dataport; 126 int hostinfo = 1; /* print host-specific info in messages */ 127 int logged_in; 128 struct passwd *pw; 129 char *homedir; 130 int ftpdebug; 131 int timeout = 900; /* timeout after 15 minutes of inactivity */ 132 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */ 133 int logging; 134 int restricted_data_ports = 1; 135 int paranoid = 1; /* be extra careful about security */ 136 int anon_only = 0; /* Only anonymous ftp allowed */ 137 int assumeutf8 = 0; /* Assume that server file names are in UTF-8 */ 138 int guest; 139 int dochroot; 140 char *chrootdir; 141 int dowtmp = 1; 142 int stats; 143 int statfd = -1; 144 int type; 145 int form; 146 int stru; /* avoid C keyword */ 147 int mode; 148 int usedefault = 1; /* for data transfers */ 149 int pdata = -1; /* for passive mode */ 150 int readonly = 0; /* Server is in readonly mode. */ 151 int noepsv = 0; /* EPSV command is disabled. */ 152 int noretr = 0; /* RETR command is disabled. */ 153 int noguestretr = 0; /* RETR command is disabled for anon users. */ 154 int noguestmkd = 0; /* MKD command is disabled for anon users. */ 155 int noguestmod = 1; /* anon users may not modify existing files. */ 156 157 off_t file_size; 158 off_t byte_count; 159 #if !defined(CMASK) || CMASK == 0 160 #undef CMASK 161 #define CMASK 027 162 #endif 163 int defumask = CMASK; /* default umask value */ 164 char tmpline[7]; 165 char *hostname; 166 int epsvall = 0; 167 168 #ifdef VIRTUAL_HOSTING 169 char *ftpuser; 170 171 static struct ftphost { 172 struct ftphost *next; 173 struct addrinfo *hostinfo; 174 char *hostname; 175 char *anonuser; 176 char *statfile; 177 char *welcome; 178 char *loginmsg; 179 } *thishost, *firsthost; 180 181 #endif 182 char remotehost[NI_MAXHOST]; 183 char *ident = NULL; 184 185 static char ttyline[20]; 186 char *tty = ttyline; /* for klogin */ 187 188 #ifdef USE_PAM 189 static int auth_pam(struct passwd**, const char*); 190 pam_handle_t *pamh = NULL; 191 #endif 192 193 #ifdef HAVE_LIBOPIE 194 static struct opie opiedata; 195 static char opieprompt[OPIE_CHALLENGE_MAX+1]; 196 #endif 197 static int pwok; 198 199 char *pid_file = NULL; /* means default location to pidfile(3) */ 200 201 /* 202 * Limit number of pathnames that glob can return. 203 * A limit of 0 indicates the number of pathnames is unlimited. 204 */ 205 #define MAXGLOBARGS 16384 206 # 207 208 /* 209 * Timeout intervals for retrying connections 210 * to hosts that don't accept PORT cmds. This 211 * is a kludge, but given the problems with TCP... 212 */ 213 #define SWAITMAX 90 /* wait at most 90 seconds */ 214 #define SWAITINT 5 /* interval between retries */ 215 216 int swaitmax = SWAITMAX; 217 int swaitint = SWAITINT; 218 219 #ifdef SETPROCTITLE 220 char proctitle[LINE_MAX]; /* initial part of title */ 221 #endif /* SETPROCTITLE */ 222 223 #define LOGCMD(cmd, file) logcmd((cmd), (file), NULL, -1) 224 #define LOGCMD2(cmd, file1, file2) logcmd((cmd), (file1), (file2), -1) 225 #define LOGBYTES(cmd, file, cnt) logcmd((cmd), (file), NULL, (cnt)) 226 227 static volatile sig_atomic_t recvurg; 228 static int transflag; /* NB: for debugging only */ 229 230 #define STARTXFER flagxfer(1) 231 #define ENDXFER flagxfer(0) 232 233 #define START_UNSAFE maskurg(1) 234 #define END_UNSAFE maskurg(0) 235 236 /* It's OK to put an `else' clause after this macro. */ 237 #define CHECKOOB(action) \ 238 if (recvurg) { \ 239 recvurg = 0; \ 240 if (myoob()) { \ 241 ENDXFER; \ 242 action; \ 243 } \ 244 } 245 246 #ifdef VIRTUAL_HOSTING 247 static void inithosts(int); 248 static void selecthost(union sockunion *); 249 #endif 250 static void ack(char *); 251 static void sigurg(int); 252 static void maskurg(int); 253 static void flagxfer(int); 254 static int myoob(void); 255 static int checkuser(char *, char *, int, char **); 256 static FILE *dataconn(char *, off_t, char *); 257 static void dolog(struct sockaddr *); 258 static void end_login(void); 259 static FILE *getdatasock(char *); 260 static int guniquefd(char *, char **); 261 static void lostconn(int); 262 static void sigquit(int); 263 static int receive_data(FILE *, FILE *); 264 static int send_data(FILE *, FILE *, size_t, off_t, int); 265 static struct passwd * 266 sgetpwnam(char *); 267 static char *sgetsave(char *); 268 static void reapchild(int); 269 static void appendf(char **, char *, ...) __printflike(2, 3); 270 static void logcmd(char *, char *, char *, off_t); 271 static void logxfer(char *, off_t, time_t); 272 static char *doublequote(char *); 273 static int *socksetup(int, char *, const char *); 274 275 int 276 main(int argc, char *argv[], char **envp) 277 { 278 socklen_t addrlen; 279 int ch, on = 1, tos; 280 char *cp, line[LINE_MAX]; 281 FILE *fd; 282 char *bindname = NULL; 283 const char *bindport = "ftp"; 284 int family = AF_UNSPEC; 285 struct sigaction sa; 286 287 tzset(); /* in case no timezone database in ~ftp */ 288 sigemptyset(&sa.sa_mask); 289 sa.sa_flags = SA_RESTART; 290 291 /* 292 * Prevent diagnostic messages from appearing on stderr. 293 * We run as a daemon or from inetd; in both cases, there's 294 * more reason in logging to syslog. 295 */ 296 (void) freopen(_PATH_DEVNULL, "w", stderr); 297 opterr = 0; 298 299 /* 300 * LOG_NDELAY sets up the logging connection immediately, 301 * necessary for anonymous ftp's that chroot and can't do it later. 302 */ 303 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP); 304 305 while ((ch = getopt(argc, argv, 306 "468a:AdDEhlmMoOp:P:rRSt:T:u:UvW")) != -1) { 307 switch (ch) { 308 case '4': 309 family = (family == AF_INET6) ? AF_UNSPEC : AF_INET; 310 break; 311 312 case '6': 313 family = (family == AF_INET) ? AF_UNSPEC : AF_INET6; 314 break; 315 316 case '8': 317 assumeutf8 = 1; 318 break; 319 320 case 'a': 321 bindname = optarg; 322 break; 323 324 case 'A': 325 anon_only = 1; 326 break; 327 328 case 'd': 329 ftpdebug++; 330 break; 331 332 case 'D': 333 daemon_mode++; 334 break; 335 336 case 'E': 337 noepsv = 1; 338 break; 339 340 case 'h': 341 hostinfo = 0; 342 break; 343 344 case 'l': 345 logging++; /* > 1 == extra logging */ 346 break; 347 348 case 'm': 349 noguestmod = 0; 350 break; 351 352 case 'M': 353 noguestmkd = 1; 354 break; 355 356 case 'o': 357 noretr = 1; 358 break; 359 360 case 'O': 361 noguestretr = 1; 362 break; 363 364 case 'p': 365 pid_file = optarg; 366 break; 367 368 case 'P': 369 bindport = optarg; 370 break; 371 372 case 'r': 373 readonly = 1; 374 break; 375 376 case 'R': 377 paranoid = 0; 378 break; 379 380 case 'S': 381 stats++; 382 break; 383 384 case 't': 385 timeout = atoi(optarg); 386 if (maxtimeout < timeout) 387 maxtimeout = timeout; 388 break; 389 390 case 'T': 391 maxtimeout = atoi(optarg); 392 if (timeout > maxtimeout) 393 timeout = maxtimeout; 394 break; 395 396 case 'u': 397 { 398 long val = 0; 399 400 val = strtol(optarg, &optarg, 8); 401 if (*optarg != '\0' || val < 0) 402 syslog(LOG_WARNING, "bad value for -u"); 403 else 404 defumask = val; 405 break; 406 } 407 case 'U': 408 restricted_data_ports = 0; 409 break; 410 411 case 'v': 412 ftpdebug++; 413 break; 414 415 case 'W': 416 dowtmp = 0; 417 break; 418 419 default: 420 syslog(LOG_WARNING, "unknown flag -%c ignored", optopt); 421 break; 422 } 423 } 424 425 if (daemon_mode) { 426 int *ctl_sock, fd, maxfd = -1, nfds, i; 427 fd_set defreadfds, readfds; 428 pid_t pid; 429 struct pidfh *pfh; 430 431 if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) { 432 if (errno == EEXIST) { 433 syslog(LOG_ERR, "%s already running, pid %d", 434 getprogname(), (int)pid); 435 exit(1); 436 } 437 syslog(LOG_WARNING, "pidfile_open: %m"); 438 } 439 440 /* 441 * Detach from parent. 442 */ 443 if (daemon(1, 1) < 0) { 444 syslog(LOG_ERR, "failed to become a daemon"); 445 exit(1); 446 } 447 448 if (pfh != NULL && pidfile_write(pfh) == -1) 449 syslog(LOG_WARNING, "pidfile_write: %m"); 450 451 sa.sa_handler = reapchild; 452 (void)sigaction(SIGCHLD, &sa, NULL); 453 454 #ifdef VIRTUAL_HOSTING 455 inithosts(family); 456 #endif 457 458 /* 459 * Open a socket, bind it to the FTP port, and start 460 * listening. 461 */ 462 ctl_sock = socksetup(family, bindname, bindport); 463 if (ctl_sock == NULL) 464 exit(1); 465 466 FD_ZERO(&defreadfds); 467 for (i = 1; i <= *ctl_sock; i++) { 468 FD_SET(ctl_sock[i], &defreadfds); 469 if (listen(ctl_sock[i], 32) < 0) { 470 syslog(LOG_ERR, "control listen: %m"); 471 exit(1); 472 } 473 if (maxfd < ctl_sock[i]) 474 maxfd = ctl_sock[i]; 475 } 476 477 /* 478 * Loop forever accepting connection requests and forking off 479 * children to handle them. 480 */ 481 while (1) { 482 FD_COPY(&defreadfds, &readfds); 483 nfds = select(maxfd + 1, &readfds, NULL, NULL, 0); 484 if (nfds <= 0) { 485 if (nfds < 0 && errno != EINTR) 486 syslog(LOG_WARNING, "select: %m"); 487 continue; 488 } 489 490 pid = -1; 491 for (i = 1; i <= *ctl_sock; i++) 492 if (FD_ISSET(ctl_sock[i], &readfds)) { 493 addrlen = sizeof(his_addr); 494 fd = accept(ctl_sock[i], 495 (struct sockaddr *)&his_addr, 496 &addrlen); 497 if (fd == -1) { 498 syslog(LOG_WARNING, 499 "accept: %m"); 500 continue; 501 } 502 switch (pid = fork()) { 503 case 0: 504 /* child */ 505 (void) dup2(fd, 0); 506 (void) dup2(fd, 1); 507 (void) close(fd); 508 for (i = 1; i <= *ctl_sock; i++) 509 close(ctl_sock[i]); 510 if (pfh != NULL) 511 pidfile_close(pfh); 512 goto gotchild; 513 case -1: 514 syslog(LOG_WARNING, "fork: %m"); 515 /* FALLTHROUGH */ 516 default: 517 close(fd); 518 } 519 } 520 } 521 } else { 522 addrlen = sizeof(his_addr); 523 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) { 524 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]); 525 exit(1); 526 } 527 528 #ifdef VIRTUAL_HOSTING 529 if (his_addr.su_family == AF_INET6 && 530 IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr)) 531 family = AF_INET; 532 else 533 family = his_addr.su_family; 534 inithosts(family); 535 #endif 536 } 537 538 gotchild: 539 sa.sa_handler = SIG_DFL; 540 (void)sigaction(SIGCHLD, &sa, NULL); 541 542 sa.sa_handler = sigurg; 543 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */ 544 (void)sigaction(SIGURG, &sa, NULL); 545 546 sigfillset(&sa.sa_mask); /* block all signals in handler */ 547 sa.sa_flags = SA_RESTART; 548 sa.sa_handler = sigquit; 549 (void)sigaction(SIGHUP, &sa, NULL); 550 (void)sigaction(SIGINT, &sa, NULL); 551 (void)sigaction(SIGQUIT, &sa, NULL); 552 (void)sigaction(SIGTERM, &sa, NULL); 553 554 sa.sa_handler = lostconn; 555 (void)sigaction(SIGPIPE, &sa, NULL); 556 557 addrlen = sizeof(ctrl_addr); 558 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) { 559 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]); 560 exit(1); 561 } 562 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */ 563 #ifdef VIRTUAL_HOSTING 564 /* select our identity from virtual host table */ 565 selecthost(&ctrl_addr); 566 #endif 567 #ifdef IP_TOS 568 if (ctrl_addr.su_family == AF_INET) 569 { 570 tos = IPTOS_LOWDELAY; 571 if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0) 572 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m"); 573 } 574 #endif 575 /* 576 * Disable Nagle on the control channel so that we don't have to wait 577 * for peer's ACK before issuing our next reply. 578 */ 579 if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0) 580 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m"); 581 582 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1); 583 584 /* set this here so klogin can use it... */ 585 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", (int)getpid()); 586 587 /* Try to handle urgent data inline */ 588 #ifdef SO_OOBINLINE 589 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0) 590 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m"); 591 #endif 592 593 #ifdef F_SETOWN 594 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1) 595 syslog(LOG_ERR, "fcntl F_SETOWN: %m"); 596 #endif 597 dolog((struct sockaddr *)&his_addr); 598 /* 599 * Set up default state 600 */ 601 data = -1; 602 type = TYPE_A; 603 form = FORM_N; 604 stru = STRU_F; 605 mode = MODE_S; 606 tmpline[0] = '\0'; 607 608 /* If logins are disabled, print out the message. */ 609 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) { 610 while (fgets(line, sizeof(line), fd) != NULL) { 611 if ((cp = strchr(line, '\n')) != NULL) 612 *cp = '\0'; 613 lreply(530, "%s", line); 614 } 615 (void) fflush(stdout); 616 (void) fclose(fd); 617 reply(530, "System not available."); 618 exit(0); 619 } 620 #ifdef VIRTUAL_HOSTING 621 fd = fopen(thishost->welcome, "r"); 622 #else 623 fd = fopen(_PATH_FTPWELCOME, "r"); 624 #endif 625 if (fd != NULL) { 626 while (fgets(line, sizeof(line), fd) != NULL) { 627 if ((cp = strchr(line, '\n')) != NULL) 628 *cp = '\0'; 629 lreply(220, "%s", line); 630 } 631 (void) fflush(stdout); 632 (void) fclose(fd); 633 /* reply(220,) must follow */ 634 } 635 #ifndef VIRTUAL_HOSTING 636 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL) 637 fatalerror("Ran out of memory."); 638 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0) 639 hostname[0] = '\0'; 640 hostname[MAXHOSTNAMELEN - 1] = '\0'; 641 #endif 642 if (hostinfo) 643 reply(220, "%s FTP server (%s) ready.", hostname, version); 644 else 645 reply(220, "FTP server ready."); 646 for (;;) 647 (void) yyparse(); 648 /* NOTREACHED */ 649 } 650 651 static void 652 lostconn(int signo) 653 { 654 655 if (ftpdebug) 656 syslog(LOG_DEBUG, "lost connection"); 657 dologout(1); 658 } 659 660 static void 661 sigquit(int signo) 662 { 663 664 syslog(LOG_ERR, "got signal %d", signo); 665 dologout(1); 666 } 667 668 #ifdef VIRTUAL_HOSTING 669 /* 670 * read in virtual host tables (if they exist) 671 */ 672 673 static void 674 inithosts(int family) 675 { 676 int insert; 677 size_t len; 678 FILE *fp; 679 char *cp, *mp, *line; 680 char *hostname; 681 char *vhost, *anonuser, *statfile, *welcome, *loginmsg; 682 struct ftphost *hrp, *lhrp; 683 struct addrinfo hints, *res, *ai; 684 685 /* 686 * Fill in the default host information 687 */ 688 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL) 689 fatalerror("Ran out of memory."); 690 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0) 691 hostname[0] = '\0'; 692 hostname[MAXHOSTNAMELEN - 1] = '\0'; 693 if ((hrp = malloc(sizeof(struct ftphost))) == NULL) 694 fatalerror("Ran out of memory."); 695 hrp->hostname = hostname; 696 hrp->hostinfo = NULL; 697 698 memset(&hints, 0, sizeof(hints)); 699 hints.ai_flags = AI_PASSIVE; 700 hints.ai_family = family; 701 hints.ai_socktype = SOCK_STREAM; 702 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0) 703 hrp->hostinfo = res; 704 hrp->statfile = _PATH_FTPDSTATFILE; 705 hrp->welcome = _PATH_FTPWELCOME; 706 hrp->loginmsg = _PATH_FTPLOGINMESG; 707 hrp->anonuser = "ftp"; 708 hrp->next = NULL; 709 thishost = firsthost = lhrp = hrp; 710 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) { 711 int addrsize, gothost; 712 void *addr; 713 struct hostent *hp; 714 715 while ((line = fgetln(fp, &len)) != NULL) { 716 int i, hp_error; 717 718 /* skip comments */ 719 if (line[0] == '#') 720 continue; 721 if (line[len - 1] == '\n') { 722 line[len - 1] = '\0'; 723 mp = NULL; 724 } else { 725 if ((mp = malloc(len + 1)) == NULL) 726 fatalerror("Ran out of memory."); 727 memcpy(mp, line, len); 728 mp[len] = '\0'; 729 line = mp; 730 } 731 cp = strtok(line, " \t"); 732 /* skip empty lines */ 733 if (cp == NULL) 734 goto nextline; 735 vhost = cp; 736 737 /* set defaults */ 738 anonuser = "ftp"; 739 statfile = _PATH_FTPDSTATFILE; 740 welcome = _PATH_FTPWELCOME; 741 loginmsg = _PATH_FTPLOGINMESG; 742 743 /* 744 * Preparse the line so we can use its info 745 * for all the addresses associated with 746 * the virtual host name. 747 * Field 0, the virtual host name, is special: 748 * it's already parsed off and will be strdup'ed 749 * later, after we know its canonical form. 750 */ 751 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++) 752 if (*cp != '-' && (cp = strdup(cp))) 753 switch (i) { 754 case 1: /* anon user permissions */ 755 anonuser = cp; 756 break; 757 case 2: /* statistics file */ 758 statfile = cp; 759 break; 760 case 3: /* welcome message */ 761 welcome = cp; 762 break; 763 case 4: /* login message */ 764 loginmsg = cp; 765 break; 766 default: /* programming error */ 767 abort(); 768 /* NOTREACHED */ 769 } 770 771 hints.ai_flags = AI_PASSIVE; 772 hints.ai_family = family; 773 hints.ai_socktype = SOCK_STREAM; 774 if (getaddrinfo(vhost, NULL, &hints, &res) != 0) 775 goto nextline; 776 for (ai = res; ai != NULL && ai->ai_addr != NULL; 777 ai = ai->ai_next) { 778 779 gothost = 0; 780 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) { 781 struct addrinfo *hi; 782 783 for (hi = hrp->hostinfo; hi != NULL; 784 hi = hi->ai_next) 785 if (hi->ai_addrlen == ai->ai_addrlen && 786 memcmp(hi->ai_addr, 787 ai->ai_addr, 788 ai->ai_addr->sa_len) == 0) { 789 gothost++; 790 break; 791 } 792 if (gothost) 793 break; 794 } 795 if (hrp == NULL) { 796 if ((hrp = malloc(sizeof(struct ftphost))) == NULL) 797 goto nextline; 798 hrp->hostname = NULL; 799 insert = 1; 800 } else { 801 if (hrp->hostinfo && hrp->hostinfo != res) 802 freeaddrinfo(hrp->hostinfo); 803 insert = 0; /* host already in the chain */ 804 } 805 hrp->hostinfo = res; 806 807 /* 808 * determine hostname to use. 809 * force defined name if there is a valid alias 810 * otherwise fallback to primary hostname 811 */ 812 /* XXX: getaddrinfo() can't do alias check */ 813 switch(hrp->hostinfo->ai_family) { 814 case AF_INET: 815 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr; 816 addrsize = sizeof(struct in_addr); 817 break; 818 case AF_INET6: 819 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr; 820 addrsize = sizeof(struct in6_addr); 821 break; 822 default: 823 /* should not reach here */ 824 freeaddrinfo(hrp->hostinfo); 825 if (insert) 826 free(hrp); /*not in chain, can free*/ 827 else 828 hrp->hostinfo = NULL; /*mark as blank*/ 829 goto nextline; 830 /* NOTREACHED */ 831 } 832 if ((hp = getipnodebyaddr(addr, addrsize, 833 hrp->hostinfo->ai_family, 834 &hp_error)) != NULL) { 835 if (strcmp(vhost, hp->h_name) != 0) { 836 if (hp->h_aliases == NULL) 837 vhost = hp->h_name; 838 else { 839 i = 0; 840 while (hp->h_aliases[i] && 841 strcmp(vhost, hp->h_aliases[i]) != 0) 842 ++i; 843 if (hp->h_aliases[i] == NULL) 844 vhost = hp->h_name; 845 } 846 } 847 } 848 if (hrp->hostname && 849 strcmp(hrp->hostname, vhost) != 0) { 850 free(hrp->hostname); 851 hrp->hostname = NULL; 852 } 853 if (hrp->hostname == NULL && 854 (hrp->hostname = strdup(vhost)) == NULL) { 855 freeaddrinfo(hrp->hostinfo); 856 hrp->hostinfo = NULL; /* mark as blank */ 857 if (hp) 858 freehostent(hp); 859 goto nextline; 860 } 861 hrp->anonuser = anonuser; 862 hrp->statfile = statfile; 863 hrp->welcome = welcome; 864 hrp->loginmsg = loginmsg; 865 if (insert) { 866 hrp->next = NULL; 867 lhrp->next = hrp; 868 lhrp = hrp; 869 } 870 if (hp) 871 freehostent(hp); 872 } 873 nextline: 874 if (mp) 875 free(mp); 876 } 877 (void) fclose(fp); 878 } 879 } 880 881 static void 882 selecthost(union sockunion *su) 883 { 884 struct ftphost *hrp; 885 u_int16_t port; 886 #ifdef INET6 887 struct in6_addr *mapped_in6 = NULL; 888 #endif 889 struct addrinfo *hi; 890 891 #ifdef INET6 892 /* 893 * XXX IPv4 mapped IPv6 addr consideraton, 894 * specified in rfc2373. 895 */ 896 if (su->su_family == AF_INET6 && 897 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr)) 898 mapped_in6 = &su->su_sin6.sin6_addr; 899 #endif 900 901 hrp = thishost = firsthost; /* default */ 902 port = su->su_port; 903 su->su_port = 0; 904 while (hrp != NULL) { 905 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) { 906 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) { 907 thishost = hrp; 908 goto found; 909 } 910 #ifdef INET6 911 /* XXX IPv4 mapped IPv6 addr consideraton */ 912 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL && 913 (memcmp(&mapped_in6->s6_addr[12], 914 &((struct sockaddr_in *)hi->ai_addr)->sin_addr, 915 sizeof(struct in_addr)) == 0)) { 916 thishost = hrp; 917 goto found; 918 } 919 #endif 920 } 921 hrp = hrp->next; 922 } 923 found: 924 su->su_port = port; 925 /* setup static variables as appropriate */ 926 hostname = thishost->hostname; 927 ftpuser = thishost->anonuser; 928 } 929 #endif 930 931 /* 932 * Helper function for sgetpwnam(). 933 */ 934 static char * 935 sgetsave(char *s) 936 { 937 char *new = malloc(strlen(s) + 1); 938 939 if (new == NULL) { 940 reply(421, "Ran out of memory."); 941 dologout(1); 942 /* NOTREACHED */ 943 } 944 (void) strcpy(new, s); 945 return (new); 946 } 947 948 /* 949 * Save the result of a getpwnam. Used for USER command, since 950 * the data returned must not be clobbered by any other command 951 * (e.g., globbing). 952 * NB: The data returned by sgetpwnam() will remain valid until 953 * the next call to this function. Its difference from getpwnam() 954 * is that sgetpwnam() is known to be called from ftpd code only. 955 */ 956 static struct passwd * 957 sgetpwnam(char *name) 958 { 959 static struct passwd save; 960 struct passwd *p; 961 #ifdef __HAIKU__ 962 struct spwd *sp = NULL; 963 #endif 964 965 if ((p = getpwnam(name)) == NULL) 966 return (p); 967 #ifdef __HAIKU__ 968 if (strcmp(p->pw_passwd, "x") == 0) { 969 if ((sp = getspnam(name)) == NULL) 970 return (p); 971 } 972 #endif 973 if (save.pw_name) { 974 free(save.pw_name); 975 free(save.pw_passwd); 976 free(save.pw_gecos); 977 free(save.pw_dir); 978 free(save.pw_shell); 979 } 980 save = *p; 981 save.pw_name = sgetsave(p->pw_name); 982 #ifdef __HAIKU__ 983 if (sp) 984 save.pw_passwd = sgetsave(sp->sp_pwdp); 985 else 986 #endif 987 save.pw_passwd = sgetsave(p->pw_passwd); 988 save.pw_gecos = sgetsave(p->pw_gecos); 989 save.pw_dir = sgetsave(p->pw_dir); 990 save.pw_shell = sgetsave(p->pw_shell); 991 return (&save); 992 } 993 994 static int login_attempts; /* number of failed login attempts */ 995 static int askpasswd; /* had user command, ask for passwd */ 996 static char curname[MAXLOGNAME]; /* current USER name */ 997 998 /* 999 * USER command. 1000 * Sets global passwd pointer pw if named account exists and is acceptable; 1001 * sets askpasswd if a PASS command is expected. If logged in previously, 1002 * need to reset state. If name is "ftp" or "anonymous", the name is not in 1003 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return. 1004 * If account doesn't exist, ask for passwd anyway. Otherwise, check user 1005 * requesting login privileges. Disallow anyone who does not have a standard 1006 * shell as returned by getusershell(). Disallow anyone mentioned in the file 1007 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided. 1008 */ 1009 void 1010 user(char *name) 1011 { 1012 char *cp, *shell; 1013 1014 if (logged_in) { 1015 if (guest) { 1016 reply(530, "Can't change user from guest login."); 1017 return; 1018 } else if (dochroot) { 1019 reply(530, "Can't change user from chroot user."); 1020 return; 1021 } 1022 end_login(); 1023 } 1024 1025 guest = 0; 1026 #ifdef VIRTUAL_HOSTING 1027 pw = sgetpwnam(thishost->anonuser); 1028 #else 1029 pw = sgetpwnam("ftp"); 1030 #endif 1031 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) { 1032 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL) || 1033 checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL)) 1034 reply(530, "User %s access denied.", name); 1035 else if (pw != NULL) { 1036 guest = 1; 1037 askpasswd = 1; 1038 reply(331, 1039 "Guest login ok, send your email address as password."); 1040 } else 1041 reply(530, "User %s unknown.", name); 1042 if (!askpasswd && logging) 1043 syslog(LOG_NOTICE, 1044 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost); 1045 return; 1046 } 1047 if (anon_only != 0) { 1048 reply(530, "Sorry, only anonymous ftp allowed."); 1049 return; 1050 } 1051 1052 if ((pw = sgetpwnam(name))) { 1053 if ((shell = pw->pw_shell) == NULL || *shell == 0) 1054 shell = _PATH_BSHELL; 1055 setusershell(); 1056 while ((cp = getusershell()) != NULL) 1057 if (strcmp(cp, shell) == 0) 1058 break; 1059 endusershell(); 1060 1061 if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1, NULL)) { 1062 reply(530, "User %s access denied.", name); 1063 if (logging) 1064 syslog(LOG_NOTICE, 1065 "FTP LOGIN REFUSED FROM %s, %s", 1066 remotehost, name); 1067 pw = NULL; 1068 return; 1069 } 1070 } 1071 if (logging) 1072 strncpy(curname, name, sizeof(curname)-1); 1073 1074 pwok = 0; 1075 #ifdef USE_PAM 1076 /* XXX Kluge! The conversation mechanism needs to be fixed. */ 1077 #endif 1078 #ifdef HAVE_LIBOPIE 1079 if (opiechallenge(&opiedata, name, opieprompt) == 0) { 1080 pwok = (pw != NULL) && 1081 opieaccessfile(remotehost) && 1082 opiealways(pw->pw_dir); 1083 reply(331, "Response to %s %s for %s.", 1084 opieprompt, pwok ? "requested" : "required", name); 1085 } else 1086 #endif 1087 { 1088 pwok = 1; 1089 reply(331, "Password required for %s.", name); 1090 } 1091 askpasswd = 1; 1092 /* 1093 * Delay before reading passwd after first failed 1094 * attempt to slow down passwd-guessing programs. 1095 */ 1096 if (login_attempts) 1097 sleep(login_attempts); 1098 } 1099 1100 /* 1101 * Check if a user is in the file "fname", 1102 * return a pointer to a malloc'd string with the rest 1103 * of the matching line in "residue" if not NULL. 1104 */ 1105 static int 1106 checkuser(char *fname, char *name, int pwset, char **residue) 1107 { 1108 FILE *fd; 1109 int found = 0; 1110 size_t len; 1111 char *line, *mp, *p; 1112 1113 if ((fd = fopen(fname, "r")) != NULL) { 1114 while (!found && (line = fgetln(fd, &len)) != NULL) { 1115 /* skip comments */ 1116 if (line[0] == '#') 1117 continue; 1118 if (line[len - 1] == '\n') { 1119 line[len - 1] = '\0'; 1120 mp = NULL; 1121 } else { 1122 if ((mp = malloc(len + 1)) == NULL) 1123 fatalerror("Ran out of memory."); 1124 memcpy(mp, line, len); 1125 mp[len] = '\0'; 1126 line = mp; 1127 } 1128 /* avoid possible leading and trailing whitespace */ 1129 p = strtok(line, " \t"); 1130 /* skip empty lines */ 1131 if (p == NULL) 1132 goto nextline; 1133 /* 1134 * if first chr is '@', check group membership 1135 */ 1136 if (p[0] == '@') { 1137 int i = 0; 1138 struct group *grp; 1139 1140 if (p[1] == '\0') /* single @ matches anyone */ 1141 found = 1; 1142 else { 1143 if ((grp = getgrnam(p+1)) == NULL) 1144 goto nextline; 1145 /* 1146 * Check user's default group 1147 */ 1148 if (pwset && grp->gr_gid == pw->pw_gid) 1149 found = 1; 1150 /* 1151 * Check supplementary groups 1152 */ 1153 while (!found && grp->gr_mem[i]) 1154 found = strcmp(name, 1155 grp->gr_mem[i++]) 1156 == 0; 1157 } 1158 } 1159 /* 1160 * Otherwise, just check for username match 1161 */ 1162 else 1163 found = strcmp(p, name) == 0; 1164 /* 1165 * Save the rest of line to "residue" if matched 1166 */ 1167 if (found && residue) { 1168 if ((p = strtok(NULL, "")) != NULL) 1169 p += strspn(p, " \t"); 1170 if (p && *p) { 1171 if ((*residue = strdup(p)) == NULL) 1172 fatalerror("Ran out of memory."); 1173 } else 1174 *residue = NULL; 1175 } 1176 nextline: 1177 if (mp) 1178 free(mp); 1179 } 1180 (void) fclose(fd); 1181 } 1182 return (found); 1183 } 1184 1185 /* 1186 * Terminate login as previous user, if any, resetting state; 1187 * used when USER command is given or login fails. 1188 */ 1189 static void 1190 end_login(void) 1191 { 1192 #ifdef USE_PAM 1193 int e; 1194 #endif 1195 1196 (void) seteuid(0); 1197 if (logged_in && dowtmp) 1198 ftpd_logwtmp(ttyline, "", NULL); 1199 pw = NULL; 1200 #ifdef LOGIN_CAP 1201 setusercontext(NULL, getpwuid(0), 0, 1202 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK| 1203 LOGIN_SETMAC); 1204 #endif 1205 #ifdef USE_PAM 1206 if (pamh) { 1207 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS) 1208 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e)); 1209 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS) 1210 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e)); 1211 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) 1212 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e)); 1213 pamh = NULL; 1214 } 1215 #endif 1216 logged_in = 0; 1217 guest = 0; 1218 dochroot = 0; 1219 } 1220 1221 #ifdef USE_PAM 1222 1223 /* 1224 * the following code is stolen from imap-uw PAM authentication module and 1225 * login.c 1226 */ 1227 #define COPY_STRING(s) (s ? strdup(s) : NULL) 1228 1229 struct cred_t { 1230 const char *uname; /* user name */ 1231 const char *pass; /* password */ 1232 }; 1233 typedef struct cred_t cred_t; 1234 1235 static int 1236 auth_conv(int num_msg, const struct pam_message **msg, 1237 struct pam_response **resp, void *appdata) 1238 { 1239 int i; 1240 cred_t *cred = (cred_t *) appdata; 1241 struct pam_response *reply; 1242 1243 reply = calloc(num_msg, sizeof *reply); 1244 if (reply == NULL) 1245 return PAM_BUF_ERR; 1246 1247 for (i = 0; i < num_msg; i++) { 1248 switch (msg[i]->msg_style) { 1249 case PAM_PROMPT_ECHO_ON: /* assume want user name */ 1250 reply[i].resp_retcode = PAM_SUCCESS; 1251 reply[i].resp = COPY_STRING(cred->uname); 1252 /* PAM frees resp. */ 1253 break; 1254 case PAM_PROMPT_ECHO_OFF: /* assume want password */ 1255 reply[i].resp_retcode = PAM_SUCCESS; 1256 reply[i].resp = COPY_STRING(cred->pass); 1257 /* PAM frees resp. */ 1258 break; 1259 case PAM_TEXT_INFO: 1260 case PAM_ERROR_MSG: 1261 reply[i].resp_retcode = PAM_SUCCESS; 1262 reply[i].resp = NULL; 1263 break; 1264 default: /* unknown message style */ 1265 free(reply); 1266 return PAM_CONV_ERR; 1267 } 1268 } 1269 1270 *resp = reply; 1271 return PAM_SUCCESS; 1272 } 1273 1274 /* 1275 * Attempt to authenticate the user using PAM. Returns 0 if the user is 1276 * authenticated, or 1 if not authenticated. If some sort of PAM system 1277 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this 1278 * function returns -1. This can be used as an indication that we should 1279 * fall back to a different authentication mechanism. 1280 */ 1281 static int 1282 auth_pam(struct passwd **ppw, const char *pass) 1283 { 1284 const char *tmpl_user; 1285 const void *item; 1286 int rval; 1287 int e; 1288 cred_t auth_cred = { (*ppw)->pw_name, pass }; 1289 struct pam_conv conv = { &auth_conv, &auth_cred }; 1290 1291 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh); 1292 if (e != PAM_SUCCESS) { 1293 /* 1294 * In OpenPAM, it's OK to pass NULL to pam_strerror() 1295 * if context creation has failed in the first place. 1296 */ 1297 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e)); 1298 return -1; 1299 } 1300 1301 e = pam_set_item(pamh, PAM_RHOST, remotehost); 1302 if (e != PAM_SUCCESS) { 1303 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s", 1304 pam_strerror(pamh, e)); 1305 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) { 1306 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e)); 1307 } 1308 pamh = NULL; 1309 return -1; 1310 } 1311 1312 e = pam_authenticate(pamh, 0); 1313 switch (e) { 1314 case PAM_SUCCESS: 1315 /* 1316 * With PAM we support the concept of a "template" 1317 * user. The user enters a login name which is 1318 * authenticated by PAM, usually via a remote service 1319 * such as RADIUS or TACACS+. If authentication 1320 * succeeds, a different but related "template" name 1321 * is used for setting the credentials, shell, and 1322 * home directory. The name the user enters need only 1323 * exist on the remote authentication server, but the 1324 * template name must be present in the local password 1325 * database. 1326 * 1327 * This is supported by two various mechanisms in the 1328 * individual modules. However, from the application's 1329 * point of view, the template user is always passed 1330 * back as a changed value of the PAM_USER item. 1331 */ 1332 if ((e = pam_get_item(pamh, PAM_USER, &item)) == 1333 PAM_SUCCESS) { 1334 tmpl_user = (const char *) item; 1335 if (strcmp((*ppw)->pw_name, tmpl_user) != 0) 1336 *ppw = getpwnam(tmpl_user); 1337 } else 1338 syslog(LOG_ERR, "Couldn't get PAM_USER: %s", 1339 pam_strerror(pamh, e)); 1340 rval = 0; 1341 break; 1342 1343 case PAM_AUTH_ERR: 1344 case PAM_USER_UNKNOWN: 1345 case PAM_MAXTRIES: 1346 rval = 1; 1347 break; 1348 1349 default: 1350 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e)); 1351 rval = -1; 1352 break; 1353 } 1354 1355 if (rval == 0) { 1356 e = pam_acct_mgmt(pamh, 0); 1357 if (e != PAM_SUCCESS) { 1358 syslog(LOG_ERR, "pam_acct_mgmt: %s", 1359 pam_strerror(pamh, e)); 1360 rval = 1; 1361 } 1362 } 1363 1364 if (rval != 0) { 1365 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) { 1366 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e)); 1367 } 1368 pamh = NULL; 1369 } 1370 return rval; 1371 } 1372 1373 #endif /* USE_PAM */ 1374 1375 void 1376 pass(char *passwd) 1377 { 1378 int rval; 1379 FILE *fd; 1380 #ifdef LOGIN_CAP 1381 login_cap_t *lc = NULL; 1382 #endif 1383 #ifdef USE_PAM 1384 int e; 1385 #endif 1386 char *residue = NULL; 1387 char *xpasswd; 1388 1389 if (logged_in || askpasswd == 0) { 1390 reply(503, "Login with USER first."); 1391 return; 1392 } 1393 askpasswd = 0; 1394 if (!guest) { /* "ftp" is only account allowed no password */ 1395 if (pw == NULL) { 1396 rval = 1; /* failure below */ 1397 goto skip; 1398 } 1399 #ifdef USE_PAM 1400 rval = auth_pam(&pw, passwd); 1401 if (rval >= 0) { 1402 opieunlock(); 1403 goto skip; 1404 } 1405 #endif 1406 #ifdef HAVE_LIBOPIE 1407 if (opieverify(&opiedata, passwd) == 0) 1408 xpasswd = pw->pw_passwd; 1409 else 1410 #endif 1411 if (pwok) { 1412 xpasswd = crypt(passwd, pw->pw_passwd); 1413 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0') 1414 xpasswd = ":"; 1415 } else { 1416 rval = 1; 1417 goto skip; 1418 } 1419 rval = strcmp(pw->pw_passwd, xpasswd); 1420 #if (!defined(__BEOS__) && !defined(__HAIKU__)) 1421 if (pw->pw_expire && time(NULL) >= pw->pw_expire) 1422 rval = 1; /* failure */ 1423 #endif 1424 skip: 1425 /* 1426 * If rval == 1, the user failed the authentication check 1427 * above. If rval == 0, either PAM or local authentication 1428 * succeeded. 1429 */ 1430 if (rval) { 1431 reply(530, "Login incorrect."); 1432 if (logging) { 1433 syslog(LOG_NOTICE, 1434 "FTP LOGIN FAILED FROM %s", 1435 remotehost); 1436 syslog(LOG_AUTHPRIV | LOG_NOTICE, 1437 "FTP LOGIN FAILED FROM %s, %s", 1438 remotehost, curname); 1439 } 1440 pw = NULL; 1441 if (login_attempts++ >= 5) { 1442 syslog(LOG_NOTICE, 1443 "repeated login failures from %s", 1444 remotehost); 1445 exit(0); 1446 } 1447 return; 1448 } 1449 } 1450 login_attempts = 0; /* this time successful */ 1451 if (setegid(pw->pw_gid) < 0) { 1452 reply(550, "Can't set gid."); 1453 return; 1454 } 1455 /* May be overridden by login.conf */ 1456 (void) umask(defumask); 1457 #ifdef LOGIN_CAP 1458 if ((lc = login_getpwclass(pw)) != NULL) { 1459 char remote_ip[NI_MAXHOST]; 1460 1461 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len, 1462 remote_ip, sizeof(remote_ip) - 1, NULL, 0, 1463 NI_NUMERICHOST)) 1464 *remote_ip = 0; 1465 remote_ip[sizeof(remote_ip) - 1] = 0; 1466 if (!auth_hostok(lc, remotehost, remote_ip)) { 1467 syslog(LOG_INFO|LOG_AUTH, 1468 "FTP LOGIN FAILED (HOST) as %s: permission denied.", 1469 pw->pw_name); 1470 reply(530, "Permission denied."); 1471 pw = NULL; 1472 return; 1473 } 1474 if (!auth_timeok(lc, time(NULL))) { 1475 reply(530, "Login not available right now."); 1476 pw = NULL; 1477 return; 1478 } 1479 } 1480 setusercontext(lc, pw, 0, 1481 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY| 1482 LOGIN_SETRESOURCES|LOGIN_SETUMASK|LOGIN_SETMAC); 1483 #elif !(defined(__BEOS__) || defined(__HAIKU__)) 1484 setlogin(pw->pw_name); 1485 (void) initgroups(pw->pw_name, pw->pw_gid); 1486 #endif 1487 1488 #ifdef USE_PAM 1489 if (pamh) { 1490 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) { 1491 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e)); 1492 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) { 1493 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e)); 1494 } 1495 } 1496 #endif 1497 1498 /* open wtmp before chroot */ 1499 if (dowtmp) 1500 ftpd_logwtmp(ttyline, pw->pw_name, 1501 (struct sockaddr *)&his_addr); 1502 logged_in = 1; 1503 1504 if (guest && stats && statfd < 0) 1505 #ifdef VIRTUAL_HOSTING 1506 statfd = open(thishost->statfile, O_WRONLY|O_APPEND); 1507 #else 1508 statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND); 1509 #endif 1510 if (statfd < 0) 1511 stats = 0; 1512 1513 dochroot = 1514 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue) 1515 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */ 1516 || login_getcapbool(lc, "ftp-chroot", 0) 1517 #endif 1518 ; 1519 chrootdir = NULL; 1520 #if (!defined(__BEOS__) && !defined(__HAIKU__)) 1521 /* 1522 * For a chrooted local user, 1523 * a) see whether ftpchroot(5) specifies a chroot directory, 1524 * b) extract the directory pathname from the line, 1525 * c) expand it to the absolute pathname if necessary. 1526 */ 1527 if (dochroot && residue && 1528 (chrootdir = strtok(residue, " \t")) != NULL) { 1529 if (chrootdir[0] != '/') 1530 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir); 1531 else 1532 chrootdir = strdup(chrootdir); /* make it permanent */ 1533 if (chrootdir == NULL) 1534 fatalerror("Ran out of memory."); 1535 } 1536 #endif 1537 if (guest || dochroot) { 1538 #if (!defined(__BEOS__) && !defined(__HAIKU__)) 1539 /* 1540 * If no chroot directory set yet, use the login directory. 1541 * Copy it so it can be modified while pw->pw_dir stays intact. 1542 */ 1543 if (chrootdir == NULL && 1544 (chrootdir = strdup(pw->pw_dir)) == NULL) 1545 fatalerror("Ran out of memory."); 1546 /* 1547 * Check for the "/chroot/./home" syntax, 1548 * separate the chroot and home directory pathnames. 1549 */ 1550 if ((homedir = strstr(chrootdir, "/./")) != NULL) { 1551 *(homedir++) = '\0'; /* wipe '/' */ 1552 homedir++; /* skip '.' */ 1553 } else { 1554 /* 1555 * We MUST do a chdir() after the chroot. Otherwise 1556 * the old current directory will be accessible as "." 1557 * outside the new root! 1558 */ 1559 homedir = "/"; 1560 } 1561 /* 1562 * Finally, do chroot() 1563 */ 1564 if (chroot(chrootdir) < 0) { 1565 reply(550, "Can't change root."); 1566 goto bad; 1567 } 1568 #else 1569 homedir = "/"; 1570 #endif 1571 } else /* real user w/o chroot */ 1572 homedir = pw->pw_dir; 1573 /* 1574 * Set euid *before* doing chdir() so 1575 * a) the user won't be carried to a directory that he couldn't reach 1576 * on his own due to no permission to upper path components, 1577 * b) NFS mounted homedirs w/restrictive permissions will be accessible 1578 * (uid 0 has no root power over NFS if not mapped explicitly.) 1579 */ 1580 if (seteuid(pw->pw_uid) < 0) { 1581 reply(550, "Can't set uid."); 1582 goto bad; 1583 } 1584 if (chdir(homedir) < 0) { 1585 if (guest || dochroot) { 1586 reply(550, "Can't change to base directory."); 1587 goto bad; 1588 } else { 1589 if (chdir("/") < 0) { 1590 reply(550, "Root is inaccessible."); 1591 goto bad; 1592 } 1593 lreply(230, "No directory! Logging in with home=/."); 1594 } 1595 } 1596 1597 /* 1598 * Display a login message, if it exists. 1599 * N.B. reply(230,) must follow the message. 1600 */ 1601 #ifdef VIRTUAL_HOSTING 1602 fd = fopen(thishost->loginmsg, "r"); 1603 #else 1604 fd = fopen(_PATH_FTPLOGINMESG, "r"); 1605 #endif 1606 if (fd != NULL) { 1607 char *cp, line[LINE_MAX]; 1608 1609 while (fgets(line, sizeof(line), fd) != NULL) { 1610 if ((cp = strchr(line, '\n')) != NULL) 1611 *cp = '\0'; 1612 lreply(230, "%s", line); 1613 } 1614 (void) fflush(stdout); 1615 (void) fclose(fd); 1616 } 1617 if (guest) { 1618 if (ident != NULL) 1619 free(ident); 1620 ident = strdup(passwd); 1621 if (ident == NULL) 1622 fatalerror("Ran out of memory."); 1623 1624 reply(230, "Guest login ok, access restrictions apply."); 1625 #ifdef SETPROCTITLE 1626 #ifdef VIRTUAL_HOSTING 1627 if (thishost != firsthost) 1628 snprintf(proctitle, sizeof(proctitle), 1629 "%s: anonymous(%s)/%s", remotehost, hostname, 1630 passwd); 1631 else 1632 #endif 1633 snprintf(proctitle, sizeof(proctitle), 1634 "%s: anonymous/%s", remotehost, passwd); 1635 setproctitle("%s", proctitle); 1636 #endif /* SETPROCTITLE */ 1637 if (logging) 1638 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s", 1639 remotehost, passwd); 1640 } else { 1641 if (dochroot) 1642 reply(230, "User %s logged in, " 1643 "access restrictions apply.", pw->pw_name); 1644 else 1645 reply(230, "User %s logged in.", pw->pw_name); 1646 1647 #ifdef SETPROCTITLE 1648 snprintf(proctitle, sizeof(proctitle), 1649 "%s: user/%s", remotehost, pw->pw_name); 1650 setproctitle("%s", proctitle); 1651 #endif /* SETPROCTITLE */ 1652 if (logging) 1653 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s", 1654 remotehost, pw->pw_name); 1655 } 1656 if (logging && (guest || dochroot)) 1657 syslog(LOG_INFO, "session root changed to %s", chrootdir); 1658 #ifdef LOGIN_CAP 1659 login_close(lc); 1660 #endif 1661 if (residue) 1662 free(residue); 1663 return; 1664 bad: 1665 /* Forget all about it... */ 1666 #ifdef LOGIN_CAP 1667 login_close(lc); 1668 #endif 1669 if (residue) 1670 free(residue); 1671 end_login(); 1672 } 1673 1674 void 1675 retrieve(char *cmd, char *name) 1676 { 1677 FILE *fin, *dout; 1678 struct stat st; 1679 int (*closefunc)(FILE *); 1680 time_t start; 1681 1682 if (cmd == 0) { 1683 fin = fopen(name, "r"), closefunc = fclose; 1684 st.st_size = 0; 1685 } else { 1686 char line[BUFSIZ]; 1687 1688 (void) snprintf(line, sizeof(line), cmd, name), name = line; 1689 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose; 1690 st.st_size = -1; 1691 st.st_blksize = BUFSIZ; 1692 } 1693 if (fin == NULL) { 1694 if (errno != 0) { 1695 perror_reply(550, name); 1696 if (cmd == 0) { 1697 LOGCMD("get", name); 1698 } 1699 } 1700 return; 1701 } 1702 byte_count = -1; 1703 if (cmd == 0) { 1704 if (fstat(fileno(fin), &st) < 0) { 1705 perror_reply(550, name); 1706 goto done; 1707 } 1708 if (!S_ISREG(st.st_mode)) { 1709 /* 1710 * Never sending a raw directory is a workaround 1711 * for buggy clients that will attempt to RETR 1712 * a directory before listing it, e.g., Mozilla. 1713 * Preventing a guest from getting irregular files 1714 * is a simple security measure. 1715 */ 1716 if (S_ISDIR(st.st_mode) || guest) { 1717 reply(550, "%s: not a plain file.", name); 1718 goto done; 1719 } 1720 st.st_size = -1; 1721 /* st.st_blksize is set for all descriptor types */ 1722 } 1723 } 1724 if (restart_point) { 1725 if (type == TYPE_A) { 1726 off_t i, n; 1727 int c; 1728 1729 n = restart_point; 1730 i = 0; 1731 while (i++ < n) { 1732 if ((c=getc(fin)) == EOF) { 1733 perror_reply(550, name); 1734 goto done; 1735 } 1736 if (c == '\n') 1737 i++; 1738 } 1739 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) { 1740 perror_reply(550, name); 1741 goto done; 1742 } 1743 } 1744 dout = dataconn(name, st.st_size, "w"); 1745 if (dout == NULL) 1746 goto done; 1747 time(&start); 1748 send_data(fin, dout, st.st_blksize, st.st_size, 1749 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode)); 1750 if (cmd == 0 && guest && stats && byte_count > 0) 1751 logxfer(name, byte_count, start); 1752 (void) fclose(dout); 1753 data = -1; 1754 pdata = -1; 1755 done: 1756 if (cmd == 0) 1757 LOGBYTES("get", name, byte_count); 1758 (*closefunc)(fin); 1759 } 1760 1761 void 1762 store(char *name, char *mode, int unique) 1763 { 1764 int fd; 1765 FILE *fout, *din; 1766 int (*closefunc)(FILE *); 1767 1768 if (*mode == 'a') { /* APPE */ 1769 if (unique) { 1770 /* Programming error */ 1771 syslog(LOG_ERR, "Internal: unique flag to APPE"); 1772 unique = 0; 1773 } 1774 if (guest && noguestmod) { 1775 reply(550, "Appending to existing file denied."); 1776 goto err; 1777 } 1778 restart_point = 0; /* not affected by preceding REST */ 1779 } 1780 if (unique) /* STOU overrides REST */ 1781 restart_point = 0; 1782 if (guest && noguestmod) { 1783 if (restart_point) { /* guest STOR w/REST */ 1784 reply(550, "Modifying existing file denied."); 1785 goto err; 1786 } else /* treat guest STOR as STOU */ 1787 unique = 1; 1788 } 1789 1790 if (restart_point) 1791 mode = "r+"; /* so ASCII manual seek can work */ 1792 if (unique) { 1793 if ((fd = guniquefd(name, &name)) < 0) 1794 goto err; 1795 fout = fdopen(fd, mode); 1796 } else 1797 fout = fopen(name, mode); 1798 closefunc = fclose; 1799 if (fout == NULL) { 1800 perror_reply(553, name); 1801 goto err; 1802 } 1803 byte_count = -1; 1804 if (restart_point) { 1805 if (type == TYPE_A) { 1806 off_t i, n; 1807 int c; 1808 1809 n = restart_point; 1810 i = 0; 1811 while (i++ < n) { 1812 if ((c=getc(fout)) == EOF) { 1813 perror_reply(550, name); 1814 goto done; 1815 } 1816 if (c == '\n') 1817 i++; 1818 } 1819 /* 1820 * We must do this seek to "current" position 1821 * because we are changing from reading to 1822 * writing. 1823 */ 1824 if (fseeko(fout, 0, SEEK_CUR) < 0) { 1825 perror_reply(550, name); 1826 goto done; 1827 } 1828 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) { 1829 perror_reply(550, name); 1830 goto done; 1831 } 1832 } 1833 din = dataconn(name, -1, "r"); 1834 if (din == NULL) 1835 goto done; 1836 if (receive_data(din, fout) == 0) { 1837 if (unique) 1838 reply(226, "Transfer complete (unique file name:%s).", 1839 name); 1840 else 1841 reply(226, "Transfer complete."); 1842 } 1843 (void) fclose(din); 1844 data = -1; 1845 pdata = -1; 1846 done: 1847 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count); 1848 (*closefunc)(fout); 1849 return; 1850 err: 1851 LOGCMD(*mode == 'a' ? "append" : "put" , name); 1852 return; 1853 } 1854 1855 static FILE * 1856 getdatasock(char *mode) 1857 { 1858 int on = 1, s, t, tries; 1859 1860 if (data >= 0) 1861 return (fdopen(data, mode)); 1862 1863 s = socket(data_dest.su_family, SOCK_STREAM, 0); 1864 if (s < 0) 1865 goto bad; 1866 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) 1867 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m"); 1868 /* anchor socket to avoid multi-homing problems */ 1869 data_source = ctrl_addr; 1870 data_source.su_port = htons(dataport); 1871 (void) seteuid(0); 1872 for (tries = 1; ; tries++) { 1873 /* 1874 * We should loop here since it's possible that 1875 * another ftpd instance has passed this point and is 1876 * trying to open a data connection in active mode now. 1877 * Until the other connection is opened, we'll be getting 1878 * EADDRINUSE because no SOCK_STREAM sockets in the system 1879 * can share both local and remote addresses, localIP:20 1880 * and *:* in this case. 1881 */ 1882 if (bind(s, (struct sockaddr *)&data_source, 1883 data_source.su_len) >= 0) 1884 break; 1885 if (errno != EADDRINUSE || tries > 10) 1886 goto bad; 1887 sleep(tries); 1888 } 1889 (void) seteuid(pw->pw_uid); 1890 #ifdef IP_TOS 1891 if (data_source.su_family == AF_INET) 1892 { 1893 on = IPTOS_THROUGHPUT; 1894 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0) 1895 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m"); 1896 } 1897 #endif 1898 #ifdef TCP_NOPUSH 1899 /* 1900 * Turn off push flag to keep sender TCP from sending short packets 1901 * at the boundaries of each write(). 1902 */ 1903 on = 1; 1904 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0) 1905 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m"); 1906 #endif 1907 return (fdopen(s, mode)); 1908 bad: 1909 /* Return the real value of errno (close may change it) */ 1910 t = errno; 1911 (void) seteuid(pw->pw_uid); 1912 (void) close(s); 1913 errno = t; 1914 return (NULL); 1915 } 1916 1917 static FILE * 1918 dataconn(char *name, off_t size, char *mode) 1919 { 1920 char sizebuf[32]; 1921 FILE *file; 1922 int retry = 0, tos, conerrno; 1923 1924 file_size = size; 1925 byte_count = 0; 1926 if (size != -1) 1927 (void) snprintf(sizebuf, sizeof(sizebuf), 1928 " (%lld bytes)", (intmax_t)size); 1929 else 1930 *sizebuf = '\0'; 1931 if (pdata >= 0) { 1932 union sockunion from; 1933 socklen_t fromlen = ctrl_addr.su_len; 1934 int flags, s; 1935 struct timeval timeout; 1936 fd_set set; 1937 1938 FD_ZERO(&set); 1939 FD_SET(pdata, &set); 1940 1941 timeout.tv_usec = 0; 1942 timeout.tv_sec = 120; 1943 1944 /* 1945 * Granted a socket is in the blocking I/O mode, 1946 * accept() will block after a successful select() 1947 * if the selected connection dies in between. 1948 * Therefore set the non-blocking I/O flag here. 1949 */ 1950 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 || 1951 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1) 1952 goto pdata_err; 1953 if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 || 1954 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0) 1955 goto pdata_err; 1956 (void) close(pdata); 1957 pdata = s; 1958 /* 1959 * Unset the inherited non-blocking I/O flag 1960 * on the child socket so stdio can work on it. 1961 */ 1962 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 || 1963 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1) 1964 goto pdata_err; 1965 #ifdef IP_TOS 1966 if (from.su_family == AF_INET) 1967 { 1968 tos = IPTOS_THROUGHPUT; 1969 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0) 1970 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m"); 1971 } 1972 #endif 1973 reply(150, "Opening %s mode data connection for '%s'%s.", 1974 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf); 1975 return (fdopen(pdata, mode)); 1976 pdata_err: 1977 reply(425, "Can't open data connection."); 1978 (void) close(pdata); 1979 pdata = -1; 1980 return (NULL); 1981 } 1982 if (data >= 0) { 1983 reply(125, "Using existing data connection for '%s'%s.", 1984 name, sizebuf); 1985 usedefault = 1; 1986 return (fdopen(data, mode)); 1987 } 1988 if (usedefault) 1989 data_dest = his_addr; 1990 usedefault = 1; 1991 do { 1992 file = getdatasock(mode); 1993 if (file == NULL) { 1994 char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV]; 1995 1996 if (getnameinfo((struct sockaddr *)&data_source, 1997 data_source.su_len, 1998 hostbuf, sizeof(hostbuf) - 1, 1999 portbuf, sizeof(portbuf) - 1, 2000 NI_NUMERICHOST|NI_NUMERICSERV)) 2001 *hostbuf = *portbuf = 0; 2002 hostbuf[sizeof(hostbuf) - 1] = 0; 2003 portbuf[sizeof(portbuf) - 1] = 0; 2004 reply(425, "Can't create data socket (%s,%s): %s.", 2005 hostbuf, portbuf, strerror(errno)); 2006 return (NULL); 2007 } 2008 data = fileno(file); 2009 conerrno = 0; 2010 if (connect(data, (struct sockaddr *)&data_dest, 2011 data_dest.su_len) == 0) 2012 break; 2013 conerrno = errno; 2014 (void) fclose(file); 2015 data = -1; 2016 if (conerrno == EADDRINUSE) { 2017 sleep(swaitint); 2018 retry += swaitint; 2019 } else { 2020 break; 2021 } 2022 } while (retry <= swaitmax); 2023 if (conerrno != 0) { 2024 reply(425, "Can't build data connection: %s.", 2025 strerror(conerrno)); 2026 return (NULL); 2027 } 2028 reply(150, "Opening %s mode data connection for '%s'%s.", 2029 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf); 2030 return (file); 2031 } 2032 2033 /* 2034 * A helper macro to avoid code duplication 2035 * in send_data() and receive_data(). 2036 * 2037 * XXX We have to block SIGURG during putc() because BSD stdio 2038 * is unable to restart interrupted write operations and hence 2039 * the entire buffer contents will be lost as soon as a write() 2040 * call indicates EINTR to stdio. 2041 */ 2042 #define FTPD_PUTC(ch, file, label) \ 2043 do { \ 2044 int ret; \ 2045 \ 2046 do { \ 2047 START_UNSAFE; \ 2048 ret = putc((ch), (file)); \ 2049 END_UNSAFE; \ 2050 CHECKOOB(return (-1)) \ 2051 else if (ferror(file)) \ 2052 goto label; \ 2053 clearerr(file); \ 2054 } while (ret == EOF); \ 2055 } while (0) 2056 2057 /* 2058 * Tranfer the contents of "instr" to "outstr" peer using the appropriate 2059 * encapsulation of the data subject to Mode, Structure, and Type. 2060 * 2061 * NB: Form isn't handled. 2062 */ 2063 static int 2064 send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg) 2065 { 2066 int c, cp, filefd, netfd; 2067 char *buf; 2068 2069 STARTXFER; 2070 2071 switch (type) { 2072 2073 case TYPE_A: 2074 cp = EOF; 2075 for (;;) { 2076 c = getc(instr); 2077 CHECKOOB(return (-1)) 2078 else if (c == EOF && ferror(instr)) 2079 goto file_err; 2080 if (c == EOF) { 2081 if (ferror(instr)) { /* resume after OOB */ 2082 clearerr(instr); 2083 continue; 2084 } 2085 if (feof(instr)) /* EOF */ 2086 break; 2087 syslog(LOG_ERR, "Internal: impossible condition" 2088 " on file after getc()"); 2089 goto file_err; 2090 } 2091 if (c == '\n' && cp != '\r') { 2092 FTPD_PUTC('\r', outstr, data_err); 2093 byte_count++; 2094 } 2095 FTPD_PUTC(c, outstr, data_err); 2096 byte_count++; 2097 cp = c; 2098 } 2099 #ifdef notyet /* BSD stdio isn't ready for that */ 2100 while (fflush(outstr) == EOF) { 2101 CHECKOOB(return (-1)) 2102 else 2103 goto data_err; 2104 clearerr(outstr); 2105 } 2106 ENDXFER; 2107 #else 2108 ENDXFER; 2109 if (fflush(outstr) == EOF) 2110 goto data_err; 2111 #endif 2112 reply(226, "Transfer complete."); 2113 return (0); 2114 2115 case TYPE_I: 2116 case TYPE_L: 2117 /* 2118 * isreg is only set if we are not doing restart and we 2119 * are sending a regular file 2120 */ 2121 netfd = fileno(outstr); 2122 filefd = fileno(instr); 2123 2124 #if (!defined(__BEOS__) && !defined(__HAIKU__)) 2125 if (isreg) { 2126 char *msg = "Transfer complete."; 2127 off_t cnt, offset; 2128 int err; 2129 2130 cnt = offset = 0; 2131 2132 while (filesize > 0) { 2133 err = sendfile(filefd, netfd, offset, 0, 2134 NULL, &cnt, 0); 2135 /* 2136 * Calculate byte_count before OOB processing. 2137 * It can be used in myoob() later. 2138 */ 2139 byte_count += cnt; 2140 offset += cnt; 2141 filesize -= cnt; 2142 CHECKOOB(return (-1)) 2143 else if (err == -1) { 2144 if (errno != EINTR && 2145 cnt == 0 && offset == 0) 2146 goto oldway; 2147 goto data_err; 2148 } 2149 if (err == -1) /* resume after OOB */ 2150 continue; 2151 /* 2152 * We hit the EOF prematurely. 2153 * Perhaps the file was externally truncated. 2154 */ 2155 if (cnt == 0) { 2156 msg = "Transfer finished due to " 2157 "premature end of file."; 2158 break; 2159 } 2160 } 2161 ENDXFER; 2162 reply(226, msg); 2163 return (0); 2164 } 2165 2166 oldway: 2167 #endif /* !__BEOS__ */ 2168 if ((buf = malloc(blksize)) == NULL) { 2169 ENDXFER; 2170 reply(451, "Ran out of memory."); 2171 return (-1); 2172 } 2173 2174 for (;;) { 2175 int cnt, len; 2176 char *bp; 2177 2178 cnt = read(filefd, buf, blksize); 2179 CHECKOOB(free(buf); return (-1)) 2180 else if (cnt < 0) { 2181 free(buf); 2182 goto file_err; 2183 } 2184 if (cnt < 0) /* resume after OOB */ 2185 continue; 2186 if (cnt == 0) /* EOF */ 2187 break; 2188 for (len = cnt, bp = buf; len > 0;) { 2189 cnt = write(netfd, bp, len); 2190 CHECKOOB(free(buf); return (-1)) 2191 else if (cnt < 0) { 2192 free(buf); 2193 goto data_err; 2194 } 2195 if (cnt <= 0) 2196 continue; 2197 len -= cnt; 2198 bp += cnt; 2199 byte_count += cnt; 2200 } 2201 } 2202 ENDXFER; 2203 free(buf); 2204 reply(226, "Transfer complete."); 2205 return (0); 2206 default: 2207 ENDXFER; 2208 reply(550, "Unimplemented TYPE %d in send_data.", type); 2209 return (-1); 2210 } 2211 2212 data_err: 2213 ENDXFER; 2214 perror_reply(426, "Data connection"); 2215 return (-1); 2216 2217 file_err: 2218 ENDXFER; 2219 perror_reply(551, "Error on input file"); 2220 return (-1); 2221 } 2222 2223 /* 2224 * Transfer data from peer to "outstr" using the appropriate encapulation of 2225 * the data subject to Mode, Structure, and Type. 2226 * 2227 * N.B.: Form isn't handled. 2228 */ 2229 static int 2230 receive_data(FILE *instr, FILE *outstr) 2231 { 2232 int c, cp; 2233 int bare_lfs = 0; 2234 2235 STARTXFER; 2236 2237 switch (type) { 2238 2239 case TYPE_I: 2240 case TYPE_L: 2241 for (;;) { 2242 int cnt, len; 2243 char *bp; 2244 char buf[BUFSIZ]; 2245 2246 cnt = read(fileno(instr), buf, sizeof(buf)); 2247 CHECKOOB(return (-1)) 2248 else if (cnt < 0) 2249 goto data_err; 2250 if (cnt < 0) /* resume after OOB */ 2251 continue; 2252 if (cnt == 0) /* EOF */ 2253 break; 2254 for (len = cnt, bp = buf; len > 0;) { 2255 cnt = write(fileno(outstr), bp, len); 2256 CHECKOOB(return (-1)) 2257 else if (cnt < 0) 2258 goto file_err; 2259 if (cnt <= 0) 2260 continue; 2261 len -= cnt; 2262 bp += cnt; 2263 byte_count += cnt; 2264 } 2265 } 2266 ENDXFER; 2267 return (0); 2268 2269 case TYPE_E: 2270 ENDXFER; 2271 reply(553, "TYPE E not implemented."); 2272 return (-1); 2273 2274 case TYPE_A: 2275 cp = EOF; 2276 for (;;) { 2277 c = getc(instr); 2278 CHECKOOB(return (-1)) 2279 else if (c == EOF && ferror(instr)) 2280 goto data_err; 2281 if (c == EOF && ferror(instr)) { /* resume after OOB */ 2282 clearerr(instr); 2283 continue; 2284 } 2285 2286 if (cp == '\r') { 2287 if (c != '\n') 2288 FTPD_PUTC('\r', outstr, file_err); 2289 } else 2290 if (c == '\n') 2291 bare_lfs++; 2292 if (c == '\r') { 2293 byte_count++; 2294 cp = c; 2295 continue; 2296 } 2297 2298 /* Check for EOF here in order not to lose last \r. */ 2299 if (c == EOF) { 2300 if (feof(instr)) /* EOF */ 2301 break; 2302 syslog(LOG_ERR, "Internal: impossible condition" 2303 " on data stream after getc()"); 2304 goto data_err; 2305 } 2306 2307 byte_count++; 2308 FTPD_PUTC(c, outstr, file_err); 2309 cp = c; 2310 } 2311 #ifdef notyet /* BSD stdio isn't ready for that */ 2312 while (fflush(outstr) == EOF) { 2313 CHECKOOB(return (-1)) 2314 else 2315 goto file_err; 2316 clearerr(outstr); 2317 } 2318 ENDXFER; 2319 #else 2320 ENDXFER; 2321 if (fflush(outstr) == EOF) 2322 goto file_err; 2323 #endif 2324 if (bare_lfs) { 2325 lreply(226, 2326 "WARNING! %d bare linefeeds received in ASCII mode.", 2327 bare_lfs); 2328 (void)printf(" File may not have transferred correctly.\r\n"); 2329 } 2330 return (0); 2331 default: 2332 ENDXFER; 2333 reply(550, "Unimplemented TYPE %d in receive_data.", type); 2334 return (-1); 2335 } 2336 2337 data_err: 2338 ENDXFER; 2339 perror_reply(426, "Data connection"); 2340 return (-1); 2341 2342 file_err: 2343 ENDXFER; 2344 perror_reply(452, "Error writing to file"); 2345 return (-1); 2346 } 2347 2348 void 2349 statfilecmd(char *filename) 2350 { 2351 FILE *fin; 2352 int atstart; 2353 int c, code; 2354 char line[LINE_MAX]; 2355 struct stat st; 2356 2357 code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213; 2358 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename); 2359 fin = ftpd_popen(line, "r"); 2360 lreply(code, "Status of %s:", filename); 2361 atstart = 1; 2362 while ((c = getc(fin)) != EOF) { 2363 if (c == '\n') { 2364 if (ferror(stdout)){ 2365 perror_reply(421, "Control connection"); 2366 (void) ftpd_pclose(fin); 2367 dologout(1); 2368 /* NOTREACHED */ 2369 } 2370 if (ferror(fin)) { 2371 perror_reply(551, filename); 2372 (void) ftpd_pclose(fin); 2373 return; 2374 } 2375 (void) putc('\r', stdout); 2376 } 2377 /* 2378 * RFC 959 says neutral text should be prepended before 2379 * a leading 3-digit number followed by whitespace, but 2380 * many ftp clients can be confused by any leading digits, 2381 * as a matter of fact. 2382 */ 2383 if (atstart && isdigit(c)) 2384 (void) putc(' ', stdout); 2385 (void) putc(c, stdout); 2386 atstart = (c == '\n'); 2387 } 2388 (void) ftpd_pclose(fin); 2389 reply(code, "End of status."); 2390 } 2391 2392 void 2393 statcmd(void) 2394 { 2395 union sockunion *su; 2396 u_char *a, *p; 2397 char hname[NI_MAXHOST]; 2398 int ispassive; 2399 2400 if (hostinfo) { 2401 lreply(211, "%s FTP server status:", hostname); 2402 printf(" %s\r\n", version); 2403 } else 2404 lreply(211, "FTP server status:"); 2405 printf(" Connected to %s", remotehost); 2406 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len, 2407 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) { 2408 hname[sizeof(hname) - 1] = 0; 2409 if (strcmp(hname, remotehost) != 0) 2410 printf(" (%s)", hname); 2411 } 2412 printf("\r\n"); 2413 if (logged_in) { 2414 if (guest) 2415 printf(" Logged in anonymously\r\n"); 2416 else 2417 printf(" Logged in as %s\r\n", pw->pw_name); 2418 } else if (askpasswd) 2419 printf(" Waiting for password\r\n"); 2420 else 2421 printf(" Waiting for user name\r\n"); 2422 printf(" TYPE: %s", typenames[type]); 2423 if (type == TYPE_A || type == TYPE_E) 2424 printf(", FORM: %s", formnames[form]); 2425 if (type == TYPE_L) 2426 #if CHAR_BIT == 8 2427 printf(" %d", CHAR_BIT); 2428 #else 2429 printf(" %d", bytesize); /* need definition! */ 2430 #endif 2431 printf("; STRUcture: %s; transfer MODE: %s\r\n", 2432 strunames[stru], modenames[mode]); 2433 if (data != -1) 2434 printf(" Data connection open\r\n"); 2435 else if (pdata != -1) { 2436 ispassive = 1; 2437 su = &pasv_addr; 2438 goto printaddr; 2439 } else if (usedefault == 0) { 2440 ispassive = 0; 2441 su = &data_dest; 2442 printaddr: 2443 #define UC(b) (((int) b) & 0xff) 2444 if (epsvall) { 2445 printf(" EPSV only mode (EPSV ALL)\r\n"); 2446 goto epsvonly; 2447 } 2448 2449 /* PORT/PASV */ 2450 if (su->su_family == AF_INET) { 2451 a = (u_char *) &su->su_sin.sin_addr; 2452 p = (u_char *) &su->su_sin.sin_port; 2453 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n", 2454 ispassive ? "PASV" : "PORT", 2455 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]), 2456 UC(p[0]), UC(p[1])); 2457 } 2458 2459 /* LPRT/LPSV */ 2460 { 2461 int alen, af, i; 2462 2463 switch (su->su_family) { 2464 case AF_INET: 2465 a = (u_char *) &su->su_sin.sin_addr; 2466 p = (u_char *) &su->su_sin.sin_port; 2467 alen = sizeof(su->su_sin.sin_addr); 2468 af = 4; 2469 break; 2470 case AF_INET6: 2471 a = (u_char *) &su->su_sin6.sin6_addr; 2472 p = (u_char *) &su->su_sin6.sin6_port; 2473 alen = sizeof(su->su_sin6.sin6_addr); 2474 af = 6; 2475 break; 2476 default: 2477 af = 0; 2478 break; 2479 } 2480 if (af) { 2481 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT", 2482 af, alen); 2483 for (i = 0; i < alen; i++) 2484 printf("%d,", UC(a[i])); 2485 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1])); 2486 } 2487 } 2488 2489 epsvonly:; 2490 /* EPRT/EPSV */ 2491 { 2492 int af; 2493 2494 switch (su->su_family) { 2495 case AF_INET: 2496 af = 1; 2497 break; 2498 case AF_INET6: 2499 af = 2; 2500 break; 2501 default: 2502 af = 0; 2503 break; 2504 } 2505 if (af) { 2506 union sockunion tmp; 2507 2508 tmp = *su; 2509 if (tmp.su_family == AF_INET6) 2510 tmp.su_sin6.sin6_scope_id = 0; 2511 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len, 2512 hname, sizeof(hname) - 1, NULL, 0, 2513 NI_NUMERICHOST)) { 2514 hname[sizeof(hname) - 1] = 0; 2515 printf(" %s |%d|%s|%d|\r\n", 2516 ispassive ? "EPSV" : "EPRT", 2517 af, hname, htons(tmp.su_port)); 2518 } 2519 } 2520 } 2521 #undef UC 2522 } else 2523 printf(" No data connection\r\n"); 2524 reply(211, "End of status."); 2525 } 2526 2527 void 2528 fatalerror(char *s) 2529 { 2530 2531 reply(451, "Error in server: %s", s); 2532 reply(221, "Closing connection due to server error."); 2533 dologout(0); 2534 /* NOTREACHED */ 2535 } 2536 2537 void 2538 reply(int n, const char *fmt, ...) 2539 { 2540 va_list ap; 2541 2542 (void)printf("%d ", n); 2543 va_start(ap, fmt); 2544 (void)vprintf(fmt, ap); 2545 va_end(ap); 2546 (void)printf("\r\n"); 2547 (void)fflush(stdout); 2548 if (ftpdebug) { 2549 syslog(LOG_DEBUG, "<--- %d ", n); 2550 va_start(ap, fmt); 2551 vsyslog(LOG_DEBUG, fmt, ap); 2552 va_end(ap); 2553 } 2554 } 2555 2556 void 2557 lreply(int n, const char *fmt, ...) 2558 { 2559 va_list ap; 2560 2561 (void)printf("%d- ", n); 2562 va_start(ap, fmt); 2563 (void)vprintf(fmt, ap); 2564 va_end(ap); 2565 (void)printf("\r\n"); 2566 (void)fflush(stdout); 2567 if (ftpdebug) { 2568 syslog(LOG_DEBUG, "<--- %d- ", n); 2569 va_start(ap, fmt); 2570 vsyslog(LOG_DEBUG, fmt, ap); 2571 va_end(ap); 2572 } 2573 } 2574 2575 static void 2576 ack(char *s) 2577 { 2578 2579 reply(250, "%s command successful.", s); 2580 } 2581 2582 void 2583 nack(char *s) 2584 { 2585 2586 reply(502, "%s command not implemented.", s); 2587 } 2588 2589 /* ARGSUSED */ 2590 void 2591 yyerror(char *s) 2592 { 2593 char *cp; 2594 2595 if ((cp = strchr(cbuf,'\n'))) 2596 *cp = '\0'; 2597 reply(500, "%s: command not understood.", cbuf); 2598 } 2599 2600 void 2601 delete(char *name) 2602 { 2603 struct stat st; 2604 2605 LOGCMD("delete", name); 2606 if (lstat(name, &st) < 0) { 2607 perror_reply(550, name); 2608 return; 2609 } 2610 if (S_ISDIR(st.st_mode)) { 2611 if (rmdir(name) < 0) { 2612 perror_reply(550, name); 2613 return; 2614 } 2615 goto done; 2616 } 2617 if (guest && noguestmod) { 2618 reply(550, "Operation not permitted."); 2619 return; 2620 } 2621 if (unlink(name) < 0) { 2622 perror_reply(550, name); 2623 return; 2624 } 2625 done: 2626 ack("DELE"); 2627 } 2628 2629 void 2630 cwd(char *path) 2631 { 2632 2633 if (chdir(path) < 0) 2634 perror_reply(550, path); 2635 else 2636 ack("CWD"); 2637 } 2638 2639 void 2640 makedir(char *name) 2641 { 2642 char *s; 2643 2644 LOGCMD("mkdir", name); 2645 if (guest && noguestmkd) 2646 reply(550, "Operation not permitted."); 2647 else if (mkdir(name, 0777) < 0) 2648 perror_reply(550, name); 2649 else { 2650 if ((s = doublequote(name)) == NULL) 2651 fatalerror("Ran out of memory."); 2652 reply(257, "\"%s\" directory created.", s); 2653 free(s); 2654 } 2655 } 2656 2657 void 2658 removedir(char *name) 2659 { 2660 2661 LOGCMD("rmdir", name); 2662 if (rmdir(name) < 0) 2663 perror_reply(550, name); 2664 else 2665 ack("RMD"); 2666 } 2667 2668 void 2669 pwd(void) 2670 { 2671 char *s, path[MAXPATHLEN + 1]; 2672 2673 if (getcwd(path, sizeof(path)) == NULL) 2674 perror_reply(550, "Get current directory"); 2675 else { 2676 if ((s = doublequote(path)) == NULL) 2677 fatalerror("Ran out of memory."); 2678 reply(257, "\"%s\" is current directory.", s); 2679 free(s); 2680 } 2681 } 2682 2683 char * 2684 renamefrom(char *name) 2685 { 2686 struct stat st; 2687 2688 if (guest && noguestmod) { 2689 reply(550, "Operation not permitted."); 2690 return (NULL); 2691 } 2692 if (lstat(name, &st) < 0) { 2693 perror_reply(550, name); 2694 return (NULL); 2695 } 2696 reply(350, "File exists, ready for destination name."); 2697 return (name); 2698 } 2699 2700 void 2701 renamecmd(char *from, char *to) 2702 { 2703 struct stat st; 2704 2705 LOGCMD2("rename", from, to); 2706 2707 if (guest && (stat(to, &st) == 0)) { 2708 reply(550, "%s: permission denied.", to); 2709 return; 2710 } 2711 2712 if (rename(from, to) < 0) 2713 perror_reply(550, "rename"); 2714 else 2715 ack("RNTO"); 2716 } 2717 2718 static void 2719 dolog(struct sockaddr *who) 2720 { 2721 char who_name[NI_MAXHOST]; 2722 2723 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len); 2724 remotehost[sizeof(remotehost) - 1] = 0; 2725 if (getnameinfo(who, who->sa_len, 2726 who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST)) 2727 *who_name = 0; 2728 who_name[sizeof(who_name) - 1] = 0; 2729 2730 #ifdef SETPROCTITLE 2731 #ifdef VIRTUAL_HOSTING 2732 if (thishost != firsthost) 2733 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)", 2734 remotehost, hostname); 2735 else 2736 #endif 2737 snprintf(proctitle, sizeof(proctitle), "%s: connected", 2738 remotehost); 2739 setproctitle("%s", proctitle); 2740 #endif /* SETPROCTITLE */ 2741 2742 if (logging) { 2743 #ifdef VIRTUAL_HOSTING 2744 if (thishost != firsthost) 2745 syslog(LOG_INFO, "connection from %s (%s) to %s", 2746 remotehost, who_name, hostname); 2747 else 2748 #endif 2749 syslog(LOG_INFO, "connection from %s (%s)", 2750 remotehost, who_name); 2751 } 2752 } 2753 2754 /* 2755 * Record logout in wtmp file 2756 * and exit with supplied status. 2757 */ 2758 void 2759 dologout(int status) 2760 { 2761 2762 if (logged_in && dowtmp) { 2763 (void) seteuid(0); 2764 ftpd_logwtmp(ttyline, "", NULL); 2765 } 2766 /* beware of flushing buffers after a SIGPIPE */ 2767 _exit(status); 2768 } 2769 2770 static void 2771 sigurg(int signo) 2772 { 2773 2774 recvurg = 1; 2775 } 2776 2777 static void 2778 maskurg(int flag) 2779 { 2780 int oerrno; 2781 sigset_t sset; 2782 2783 if (!transflag) { 2784 syslog(LOG_ERR, "Internal: maskurg() while no transfer"); 2785 return; 2786 } 2787 oerrno = errno; 2788 sigemptyset(&sset); 2789 sigaddset(&sset, SIGURG); 2790 sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL); 2791 errno = oerrno; 2792 } 2793 2794 static void 2795 flagxfer(int flag) 2796 { 2797 2798 if (flag) { 2799 if (transflag) 2800 syslog(LOG_ERR, "Internal: flagxfer(1): " 2801 "transfer already under way"); 2802 transflag = 1; 2803 maskurg(0); 2804 recvurg = 0; 2805 } else { 2806 if (!transflag) 2807 syslog(LOG_ERR, "Internal: flagxfer(0): " 2808 "no active transfer"); 2809 maskurg(1); 2810 transflag = 0; 2811 } 2812 } 2813 2814 /* 2815 * Returns 0 if OK to resume or -1 if abort requested. 2816 */ 2817 static int 2818 myoob(void) 2819 { 2820 char *cp; 2821 2822 if (!transflag) { 2823 syslog(LOG_ERR, "Internal: myoob() while no transfer"); 2824 return (0); 2825 } 2826 cp = tmpline; 2827 if (ftpd_getline(cp, 7, stdin) == NULL) { 2828 reply(221, "You could at least say goodbye."); 2829 dologout(0); 2830 } 2831 upper(cp); 2832 if (strcmp(cp, "ABOR\r\n") == 0) { 2833 tmpline[0] = '\0'; 2834 reply(426, "Transfer aborted. Data connection closed."); 2835 reply(226, "Abort successful."); 2836 return (-1); 2837 } 2838 if (strcmp(cp, "STAT\r\n") == 0) { 2839 tmpline[0] = '\0'; 2840 if (file_size != -1) 2841 reply(213, "Status: %lld of %lld bytes transferred.", 2842 (intmax_t)byte_count, (intmax_t)file_size); 2843 else 2844 reply(213, "Status: %lld bytes transferred.", 2845 (intmax_t)byte_count); 2846 } 2847 return (0); 2848 } 2849 2850 /* 2851 * Note: a response of 425 is not mentioned as a possible response to 2852 * the PASV command in RFC959. However, it has been blessed as 2853 * a legitimate response by Jon Postel in a telephone conversation 2854 * with Rick Adams on 25 Jan 89. 2855 */ 2856 void 2857 passive(void) 2858 { 2859 socklen_t len; 2860 int on; 2861 char *p, *a; 2862 2863 if (pdata >= 0) /* close old port if one set */ 2864 close(pdata); 2865 2866 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0); 2867 if (pdata < 0) { 2868 perror_reply(425, "Can't open passive connection"); 2869 return; 2870 } 2871 on = 1; 2872 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) 2873 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m"); 2874 2875 (void) seteuid(0); 2876 2877 #ifdef IP_PORTRANGE 2878 if (ctrl_addr.su_family == AF_INET) { 2879 on = restricted_data_ports ? IP_PORTRANGE_HIGH 2880 : IP_PORTRANGE_DEFAULT; 2881 2882 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE, 2883 &on, sizeof(on)) < 0) 2884 goto pasv_error; 2885 } 2886 #endif 2887 #ifdef IPV6_PORTRANGE 2888 if (ctrl_addr.su_family == AF_INET6) { 2889 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH 2890 : IPV6_PORTRANGE_DEFAULT; 2891 2892 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE, 2893 &on, sizeof(on)) < 0) 2894 goto pasv_error; 2895 } 2896 #endif 2897 2898 pasv_addr = ctrl_addr; 2899 pasv_addr.su_port = 0; 2900 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0) 2901 goto pasv_error; 2902 2903 (void) seteuid(pw->pw_uid); 2904 2905 len = sizeof(pasv_addr); 2906 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0) 2907 goto pasv_error; 2908 if (listen(pdata, 1) < 0) 2909 goto pasv_error; 2910 if (pasv_addr.su_family == AF_INET) 2911 a = (char *) &pasv_addr.su_sin.sin_addr; 2912 #ifdef HAVE_AF_INET6 2913 else if (pasv_addr.su_family == AF_INET6 && 2914 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) 2915 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12]; 2916 #endif 2917 else 2918 goto pasv_error; 2919 2920 p = (char *) &pasv_addr.su_port; 2921 2922 #define UC(b) (((int) b) & 0xff) 2923 2924 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]), 2925 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1])); 2926 return; 2927 2928 pasv_error: 2929 (void) seteuid(pw->pw_uid); 2930 (void) close(pdata); 2931 pdata = -1; 2932 perror_reply(425, "Can't open passive connection"); 2933 return; 2934 } 2935 2936 /* 2937 * Long Passive defined in RFC 1639. 2938 * 228 Entering Long Passive Mode 2939 * (af, hal, h1, h2, h3,..., pal, p1, p2...) 2940 */ 2941 2942 void 2943 long_passive(char *cmd, int pf) 2944 { 2945 socklen_t len; 2946 int on; 2947 char *p, *a; 2948 2949 if (pdata >= 0) /* close old port if one set */ 2950 close(pdata); 2951 2952 if (pf != PF_UNSPEC) { 2953 if (ctrl_addr.su_family != pf) { 2954 switch (ctrl_addr.su_family) { 2955 case AF_INET: 2956 pf = 1; 2957 break; 2958 case AF_INET6: 2959 pf = 2; 2960 break; 2961 default: 2962 pf = 0; 2963 break; 2964 } 2965 /* 2966 * XXX 2967 * only EPRT/EPSV ready clients will understand this 2968 */ 2969 if (strcmp(cmd, "EPSV") == 0 && pf) { 2970 reply(522, "Network protocol mismatch, " 2971 "use (%d)", pf); 2972 } else 2973 reply(501, "Network protocol mismatch."); /*XXX*/ 2974 2975 return; 2976 } 2977 } 2978 2979 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0); 2980 if (pdata < 0) { 2981 perror_reply(425, "Can't open passive connection"); 2982 return; 2983 } 2984 on = 1; 2985 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) 2986 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m"); 2987 2988 (void) seteuid(0); 2989 2990 pasv_addr = ctrl_addr; 2991 pasv_addr.su_port = 0; 2992 len = pasv_addr.su_len; 2993 2994 #ifdef IP_PORTRANGE 2995 if (ctrl_addr.su_family == AF_INET) { 2996 on = restricted_data_ports ? IP_PORTRANGE_HIGH 2997 : IP_PORTRANGE_DEFAULT; 2998 2999 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE, 3000 &on, sizeof(on)) < 0) 3001 goto pasv_error; 3002 } 3003 #endif 3004 #ifdef IPV6_PORTRANGE 3005 if (ctrl_addr.su_family == AF_INET6) { 3006 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH 3007 : IPV6_PORTRANGE_DEFAULT; 3008 3009 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE, 3010 &on, sizeof(on)) < 0) 3011 goto pasv_error; 3012 } 3013 #endif 3014 3015 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0) 3016 goto pasv_error; 3017 3018 (void) seteuid(pw->pw_uid); 3019 3020 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0) 3021 goto pasv_error; 3022 if (listen(pdata, 1) < 0) 3023 goto pasv_error; 3024 3025 #define UC(b) (((int) b) & 0xff) 3026 3027 if (strcmp(cmd, "LPSV") == 0) { 3028 p = (char *)&pasv_addr.su_port; 3029 switch (pasv_addr.su_family) { 3030 case AF_INET: 3031 a = (char *) &pasv_addr.su_sin.sin_addr; 3032 #ifdef HAVE_AF_INET6 3033 v4_reply: 3034 #endif 3035 reply(228, 3036 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)", 3037 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]), 3038 2, UC(p[0]), UC(p[1])); 3039 return; 3040 #ifdef HAVE_AF_INET6 3041 case AF_INET6: 3042 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) { 3043 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12]; 3044 goto v4_reply; 3045 } 3046 a = (char *) &pasv_addr.su_sin6.sin6_addr; 3047 reply(228, 3048 "Entering Long Passive Mode " 3049 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)", 3050 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]), 3051 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]), 3052 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]), 3053 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]), 3054 2, UC(p[0]), UC(p[1])); 3055 return; 3056 #endif 3057 } 3058 } else if (strcmp(cmd, "EPSV") == 0) { 3059 switch (pasv_addr.su_family) { 3060 case AF_INET: 3061 case AF_INET6: 3062 reply(229, "Entering Extended Passive Mode (|||%d|)", 3063 ntohs(pasv_addr.su_port)); 3064 return; 3065 } 3066 } else { 3067 /* more proper error code? */ 3068 } 3069 3070 pasv_error: 3071 (void) seteuid(pw->pw_uid); 3072 (void) close(pdata); 3073 pdata = -1; 3074 perror_reply(425, "Can't open passive connection"); 3075 return; 3076 } 3077 3078 /* 3079 * Generate unique name for file with basename "local" 3080 * and open the file in order to avoid possible races. 3081 * Try "local" first, then "local.1", "local.2" etc, up to "local.99". 3082 * Return descriptor to the file, set "name" to its name. 3083 * 3084 * Generates failure reply on error. 3085 */ 3086 static int 3087 guniquefd(char *local, char **name) 3088 { 3089 static char new[MAXPATHLEN]; 3090 struct stat st; 3091 char *cp; 3092 int count; 3093 int fd; 3094 3095 cp = strrchr(local, '/'); 3096 if (cp) 3097 *cp = '\0'; 3098 if (stat(cp ? local : ".", &st) < 0) { 3099 perror_reply(553, cp ? local : "."); 3100 return (-1); 3101 } 3102 if (cp) { 3103 /* 3104 * Let not overwrite dirname with counter suffix. 3105 * -4 is for /nn\0 3106 * In this extreme case dot won't be put in front of suffix. 3107 */ 3108 if (strlen(local) > sizeof(new) - 4) { 3109 reply(553, "Pathname too long."); 3110 return (-1); 3111 } 3112 *cp = '/'; 3113 } 3114 /* -4 is for the .nn<null> we put on the end below */ 3115 (void) snprintf(new, sizeof(new) - 4, "%s", local); 3116 cp = new + strlen(new); 3117 /* 3118 * Don't generate dotfile unless requested explicitly. 3119 * This covers the case when basename gets truncated off 3120 * by buffer size. 3121 */ 3122 if (cp > new && cp[-1] != '/') 3123 *cp++ = '.'; 3124 for (count = 0; count < 100; count++) { 3125 /* At count 0 try unmodified name */ 3126 if (count) 3127 (void)sprintf(cp, "%d", count); 3128 if ((fd = open(count ? new : local, 3129 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) { 3130 *name = count ? new : local; 3131 return (fd); 3132 } 3133 if (errno != EEXIST) { 3134 perror_reply(553, count ? new : local); 3135 return (-1); 3136 } 3137 } 3138 reply(452, "Unique file name cannot be created."); 3139 return (-1); 3140 } 3141 3142 /* 3143 * Format and send reply containing system error number. 3144 */ 3145 void 3146 perror_reply(int code, char *string) 3147 { 3148 3149 reply(code, "%s: %s.", string, strerror(errno)); 3150 } 3151 3152 static char *onefile[] = { 3153 "", 3154 0 3155 }; 3156 3157 void 3158 send_file_list(char *whichf) 3159 { 3160 struct stat st; 3161 DIR *dirp = NULL; 3162 struct dirent *dir; 3163 FILE *dout = NULL; 3164 char **dirlist, *dirname; 3165 int simple = 0; 3166 int freeglob = 0; 3167 glob_t gl; 3168 3169 if (strpbrk(whichf, "~{[*?") != NULL) { 3170 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE; 3171 3172 memset(&gl, 0, sizeof(gl)); 3173 gl.gl_matchc = MAXGLOBARGS; 3174 flags |= GLOB_LIMIT; 3175 freeglob = 1; 3176 if (glob(whichf, flags, 0, &gl)) { 3177 reply(550, "No matching files found."); 3178 goto out; 3179 } else if (gl.gl_pathc == 0) { 3180 errno = ENOENT; 3181 perror_reply(550, whichf); 3182 goto out; 3183 } 3184 dirlist = gl.gl_pathv; 3185 } else { 3186 onefile[0] = whichf; 3187 dirlist = onefile; 3188 simple = 1; 3189 } 3190 3191 while ((dirname = *dirlist++)) { 3192 if (stat(dirname, &st) < 0) { 3193 /* 3194 * If user typed "ls -l", etc, and the client 3195 * used NLST, do what the user meant. 3196 */ 3197 if (dirname[0] == '-' && *dirlist == NULL && 3198 dout == NULL) 3199 retrieve(_PATH_LS " %s", dirname); 3200 else 3201 perror_reply(550, whichf); 3202 goto out; 3203 } 3204 3205 if (S_ISREG(st.st_mode)) { 3206 if (dout == NULL) { 3207 dout = dataconn("file list", -1, "w"); 3208 if (dout == NULL) 3209 goto out; 3210 STARTXFER; 3211 } 3212 START_UNSAFE; 3213 fprintf(dout, "%s%s\n", dirname, 3214 type == TYPE_A ? "\r" : ""); 3215 END_UNSAFE; 3216 if (ferror(dout)) 3217 goto data_err; 3218 byte_count += strlen(dirname) + 3219 (type == TYPE_A ? 2 : 1); 3220 CHECKOOB(goto abrt); 3221 continue; 3222 } else if (!S_ISDIR(st.st_mode)) 3223 continue; 3224 3225 if ((dirp = opendir(dirname)) == NULL) 3226 continue; 3227 3228 while ((dir = readdir(dirp)) != NULL) { 3229 char nbuf[MAXPATHLEN]; 3230 3231 CHECKOOB(goto abrt); 3232 3233 #if (defined(__BEOS__) || defined(__HAIKU__)) 3234 if (dir->d_name[0] == '.' && dir->d_name[1] == '\0') 3235 continue; 3236 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' && 3237 dir->d_name[2] == '\0') 3238 continue; 3239 #else 3240 if (dir->d_name[0] == '.' && dir->d_namlen == 1) 3241 continue; 3242 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' && 3243 dir->d_namlen == 2) 3244 continue; 3245 #endif 3246 3247 snprintf(nbuf, sizeof(nbuf), 3248 "%s/%s", dirname, dir->d_name); 3249 3250 /* 3251 * We have to do a stat to insure it's 3252 * not a directory or special file. 3253 */ 3254 if (simple || (stat(nbuf, &st) == 0 && 3255 S_ISREG(st.st_mode))) { 3256 if (dout == NULL) { 3257 dout = dataconn("file list", -1, "w"); 3258 if (dout == NULL) 3259 goto out; 3260 STARTXFER; 3261 } 3262 START_UNSAFE; 3263 if (nbuf[0] == '.' && nbuf[1] == '/') 3264 fprintf(dout, "%s%s\n", &nbuf[2], 3265 type == TYPE_A ? "\r" : ""); 3266 else 3267 fprintf(dout, "%s%s\n", nbuf, 3268 type == TYPE_A ? "\r" : ""); 3269 END_UNSAFE; 3270 if (ferror(dout)) 3271 goto data_err; 3272 byte_count += strlen(nbuf) + 3273 (type == TYPE_A ? 2 : 1); 3274 CHECKOOB(goto abrt); 3275 } 3276 } 3277 (void) closedir(dirp); 3278 dirp = NULL; 3279 } 3280 3281 if (dout == NULL) 3282 reply(550, "No files found."); 3283 else if (ferror(dout)) 3284 data_err: perror_reply(550, "Data connection"); 3285 else 3286 reply(226, "Transfer complete."); 3287 out: 3288 if (dout) { 3289 ENDXFER; 3290 abrt: 3291 (void) fclose(dout); 3292 data = -1; 3293 pdata = -1; 3294 } 3295 if (dirp) 3296 (void) closedir(dirp); 3297 if (freeglob) { 3298 freeglob = 0; 3299 globfree(&gl); 3300 } 3301 } 3302 3303 void 3304 reapchild(int signo) 3305 { 3306 while (waitpid(-1, NULL, WNOHANG) > 0); 3307 } 3308 3309 static void 3310 appendf(char **strp, char *fmt, ...) 3311 { 3312 va_list ap; 3313 char *ostr, *p; 3314 3315 va_start(ap, fmt); 3316 vasprintf(&p, fmt, ap); 3317 va_end(ap); 3318 if (p == NULL) 3319 fatalerror("Ran out of memory."); 3320 if (*strp == NULL) 3321 *strp = p; 3322 else { 3323 ostr = *strp; 3324 asprintf(strp, "%s%s", ostr, p); 3325 if (*strp == NULL) 3326 fatalerror("Ran out of memory."); 3327 free(ostr); 3328 } 3329 } 3330 3331 static void 3332 logcmd(char *cmd, char *file1, char *file2, off_t cnt) 3333 { 3334 char *msg = NULL; 3335 char wd[MAXPATHLEN + 1]; 3336 3337 if (logging <= 1) 3338 return; 3339 3340 if (getcwd(wd, sizeof(wd) - 1) == NULL) 3341 strcpy(wd, strerror(errno)); 3342 3343 appendf(&msg, "%s", cmd); 3344 if (file1) 3345 appendf(&msg, " %s", file1); 3346 if (file2) 3347 appendf(&msg, " %s", file2); 3348 if (cnt >= 0) 3349 appendf(&msg, " = %lld bytes", (intmax_t)cnt); 3350 appendf(&msg, " (wd: %s", wd); 3351 if (guest || dochroot) 3352 appendf(&msg, "; chrooted"); 3353 appendf(&msg, ")"); 3354 syslog(LOG_INFO, "%s", msg); 3355 free(msg); 3356 } 3357 3358 static void 3359 logxfer(char *name, off_t size, time_t start) 3360 { 3361 char buf[MAXPATHLEN + 1024]; 3362 char path[MAXPATHLEN + 1]; 3363 time_t now; 3364 3365 if (statfd >= 0) { 3366 time(&now); 3367 if (realpath(name, path) == NULL) { 3368 syslog(LOG_NOTICE, "realpath failed on %s: %m", path); 3369 return; 3370 } 3371 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%lld!%ld\n", 3372 ctime(&now)+4, ident, remotehost, 3373 path, (intmax_t)size, 3374 (long)(now - start + (now == start))); 3375 write(statfd, buf, strlen(buf)); 3376 } 3377 } 3378 3379 static char * 3380 doublequote(char *s) 3381 { 3382 int n; 3383 char *p, *s2; 3384 3385 for (p = s, n = 0; *p; p++) 3386 if (*p == '"') 3387 n++; 3388 3389 if ((s2 = malloc(p - s + n + 1)) == NULL) 3390 return (NULL); 3391 3392 for (p = s2; *s; s++, p++) { 3393 if ((*p = *s) == '"') 3394 *(++p) = '"'; 3395 } 3396 *p = '\0'; 3397 3398 return (s2); 3399 } 3400 3401 /* setup server socket for specified address family */ 3402 /* if af is PF_UNSPEC more than one socket may be returned */ 3403 /* the returned list is dynamically allocated, so caller needs to free it */ 3404 static int * 3405 socksetup(int af, char *bindname, const char *bindport) 3406 { 3407 struct addrinfo hints, *res, *r; 3408 int error, maxs, *s, *socks; 3409 const int on = 1; 3410 3411 memset(&hints, 0, sizeof(hints)); 3412 hints.ai_flags = AI_PASSIVE; 3413 hints.ai_family = af; 3414 hints.ai_socktype = SOCK_STREAM; 3415 error = getaddrinfo(bindname, bindport, &hints, &res); 3416 if (error) { 3417 syslog(LOG_ERR, "%s", gai_strerror(error)); 3418 if (error == EAI_SYSTEM) 3419 syslog(LOG_ERR, "%s", strerror(errno)); 3420 return NULL; 3421 } 3422 3423 /* Count max number of sockets we may open */ 3424 for (maxs = 0, r = res; r; r = r->ai_next, maxs++) 3425 ; 3426 socks = malloc((maxs + 1) * sizeof(int)); 3427 if (!socks) { 3428 freeaddrinfo(res); 3429 syslog(LOG_ERR, "couldn't allocate memory for sockets"); 3430 return NULL; 3431 } 3432 3433 *socks = 0; /* num of sockets counter at start of array */ 3434 s = socks + 1; 3435 for (r = res; r; r = r->ai_next) { 3436 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol); 3437 if (*s < 0) { 3438 syslog(LOG_DEBUG, "control socket: %m"); 3439 continue; 3440 } 3441 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, 3442 &on, sizeof(on)) < 0) 3443 syslog(LOG_WARNING, 3444 "control setsockopt (SO_REUSEADDR): %m"); 3445 #ifdef HAVE_AF_INET6 3446 if (r->ai_family == AF_INET6) { 3447 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY, 3448 &on, sizeof(on)) < 0) 3449 syslog(LOG_WARNING, 3450 "control setsockopt (IPV6_V6ONLY): %m"); 3451 } 3452 #endif 3453 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) { 3454 syslog(LOG_DEBUG, "control bind: %m"); 3455 close(*s); 3456 continue; 3457 } 3458 (*socks)++; 3459 s++; 3460 } 3461 3462 if (res) 3463 freeaddrinfo(res); 3464 3465 if (*socks == 0) { 3466 syslog(LOG_ERR, "control socket: Couldn't bind to any socket"); 3467 free(socks); 3468 return NULL; 3469 } 3470 return(socks); 3471 } 3472