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