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