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