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