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