ftpd.c revision 110037
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 110037 2003-01-29 10:58:58Z 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, %s", 1407 remotehost, curname); 1408 pw = NULL; 1409 if (login_attempts++ >= 5) { 1410 syslog(LOG_NOTICE, 1411 "repeated login failures from %s", 1412 remotehost); 1413 exit(0); 1414 } 1415 return; 1416 } 1417 } 1418 login_attempts = 0; /* this time successful */ 1419 if (setegid((gid_t)pw->pw_gid) < 0) { 1420 reply(550, "Can't set gid."); 1421 return; 1422 } 1423 /* May be overridden by login.conf */ 1424 (void) umask(defumask); 1425#ifdef LOGIN_CAP 1426 if ((lc = login_getpwclass(pw)) != NULL) { 1427 char remote_ip[MAXHOSTNAMELEN]; 1428 1429 getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len, 1430 remote_ip, sizeof(remote_ip) - 1, NULL, 0, 1431 NI_NUMERICHOST); 1432 remote_ip[sizeof(remote_ip) - 1] = 0; 1433 if (!auth_hostok(lc, remotehost, remote_ip)) { 1434 syslog(LOG_INFO|LOG_AUTH, 1435 "FTP LOGIN FAILED (HOST) as %s: permission denied.", 1436 pw->pw_name); 1437 reply(530, "Permission denied.\n"); 1438 pw = NULL; 1439 return; 1440 } 1441 if (!auth_timeok(lc, time(NULL))) { 1442 reply(530, "Login not available right now.\n"); 1443 pw = NULL; 1444 return; 1445 } 1446 } 1447 setusercontext(lc, pw, (uid_t)0, 1448 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY| 1449 LOGIN_SETRESOURCES|LOGIN_SETUMASK|LOGIN_SETMAC); 1450#else 1451 setlogin(pw->pw_name); 1452 (void) initgroups(pw->pw_name, pw->pw_gid); 1453#endif 1454 1455#ifdef USE_PAM 1456 if (pamh) { 1457 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) { 1458 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e)); 1459 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) { 1460 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e)); 1461 } 1462 } 1463#endif 1464 1465 /* open wtmp before chroot */ 1466 if (dowtmp) 1467 ftpd_logwtmp(ttyline, pw->pw_name, 1468 (struct sockaddr *)&his_addr); 1469 logged_in = 1; 1470 1471 if (guest && stats && statfd < 0) 1472#ifdef VIRTUAL_HOSTING 1473 if ((statfd = open(thishost->statfile, O_WRONLY|O_APPEND)) < 0) 1474#else 1475 if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0) 1476#endif 1477 stats = 0; 1478 1479 dochroot = 1480 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue) 1481#ifdef LOGIN_CAP /* Allow login.conf configuration as well */ 1482 || login_getcapbool(lc, "ftp-chroot", 0) 1483#endif 1484 ; 1485 chrootdir = NULL; 1486 /* 1487 * For a chrooted local user, 1488 * a) see whether ftpchroot(5) specifies a chroot directory, 1489 * b) extract the directory pathname from the line, 1490 * c) expand it to the absolute pathname if necessary. 1491 */ 1492 if (dochroot && residue && 1493 (chrootdir = strtok(residue, " \t")) != NULL && 1494 chrootdir[0] != '/') { 1495 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir); 1496 if (chrootdir == NULL) 1497 fatalerror("Ran out of memory."); 1498 1499 } 1500 if (guest || dochroot) { 1501 /* 1502 * If no chroot directory set yet, use the login directory. 1503 * Copy it so it can be modified while pw->pw_dir stays intact. 1504 */ 1505 if (chrootdir == NULL && 1506 (chrootdir = strdup(pw->pw_dir)) == NULL) 1507 fatalerror("Ran out of memory."); 1508 /* 1509 * Check for the "/chroot/./home" syntax, 1510 * separate the chroot and home directory pathnames. 1511 */ 1512 if ((homedir = strstr(chrootdir, "/./")) != NULL) { 1513 *(homedir++) = '\0'; /* wipe '/' */ 1514 homedir++; /* skip '.' */ 1515 /* so chrootdir can be freed later */ 1516 if ((homedir = strdup(homedir)) == NULL) 1517 fatalerror("Ran out of memory."); 1518 } else { 1519 /* 1520 * We MUST do a chdir() after the chroot. Otherwise 1521 * the old current directory will be accessible as "." 1522 * outside the new root! 1523 */ 1524 homedir = "/"; 1525 } 1526 /* 1527 * Finally, do chroot() 1528 */ 1529 if (chroot(chrootdir) < 0) { 1530 reply(550, "Can't change root."); 1531 goto bad; 1532 } 1533 } else /* real user w/o chroot */ 1534 homedir = pw->pw_dir; 1535 /* 1536 * Set euid *before* doing chdir() so 1537 * a) the user won't be carried to a directory that he couldn't reach 1538 * on his own due to no permission to upper path components, 1539 * b) NFS mounted homedirs w/restrictive permissions will be accessible 1540 * (uid 0 has no root power over NFS if not mapped explicitly.) 1541 */ 1542 if (seteuid((uid_t)pw->pw_uid) < 0) { 1543 reply(550, "Can't set uid."); 1544 goto bad; 1545 } 1546 if (chdir(homedir) < 0) { 1547 if (guest || dochroot) { 1548 reply(550, "Can't change to base directory."); 1549 goto bad; 1550 } else { 1551 if (chdir("/") < 0) { 1552 reply(550, "Root is inaccessible."); 1553 goto bad; 1554 } 1555 lreply(230, "No directory! Logging in with home=/"); 1556 } 1557 } 1558 1559 /* 1560 * Display a login message, if it exists. 1561 * N.B. reply(230,) must follow the message. 1562 */ 1563#ifdef VIRTUAL_HOSTING 1564 if ((fd = fopen(thishost->loginmsg, "r")) != NULL) { 1565#else 1566 if ((fd = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) { 1567#endif 1568 char *cp, line[LINE_MAX]; 1569 1570 while (fgets(line, sizeof(line), fd) != NULL) { 1571 if ((cp = strchr(line, '\n')) != NULL) 1572 *cp = '\0'; 1573 lreply(230, "%s", line); 1574 } 1575 (void) fflush(stdout); 1576 (void) fclose(fd); 1577 } 1578 if (guest) { 1579 if (ident != NULL) 1580 free(ident); 1581 ident = strdup(passwd); 1582 if (ident == NULL) 1583 fatalerror("Ran out of memory."); 1584 1585 reply(230, "Guest login ok, access restrictions apply."); 1586#ifdef SETPROCTITLE 1587#ifdef VIRTUAL_HOSTING 1588 if (thishost != firsthost) 1589 snprintf(proctitle, sizeof(proctitle), 1590 "%s: anonymous(%s)/%s", remotehost, hostname, 1591 passwd); 1592 else 1593#endif 1594 snprintf(proctitle, sizeof(proctitle), 1595 "%s: anonymous/%s", remotehost, passwd); 1596 setproctitle("%s", proctitle); 1597#endif /* SETPROCTITLE */ 1598 if (logging) 1599 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s", 1600 remotehost, passwd); 1601 } else { 1602 if (dochroot) 1603 reply(230, "User %s logged in, " 1604 "access restrictions apply.", pw->pw_name); 1605 else 1606 reply(230, "User %s logged in.", pw->pw_name); 1607 1608#ifdef SETPROCTITLE 1609 snprintf(proctitle, sizeof(proctitle), 1610 "%s: user/%s", remotehost, pw->pw_name); 1611 setproctitle("%s", proctitle); 1612#endif /* SETPROCTITLE */ 1613 if (logging) 1614 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s", 1615 remotehost, pw->pw_name); 1616 } 1617#ifdef LOGIN_CAP 1618 login_close(lc); 1619#endif 1620 if (chrootdir) 1621 free(chrootdir); 1622 if (residue) 1623 free(residue); 1624 return; 1625bad: 1626 /* Forget all about it... */ 1627#ifdef LOGIN_CAP 1628 login_close(lc); 1629#endif 1630 if (chrootdir) 1631 free(chrootdir); 1632 if (residue) 1633 free(residue); 1634 end_login(); 1635} 1636 1637void 1638retrieve(char *cmd, char *name) 1639{ 1640 FILE *fin, *dout; 1641 struct stat st; 1642 int (*closefunc)(FILE *); 1643 time_t start; 1644 1645 if (cmd == 0) { 1646 fin = fopen(name, "r"), closefunc = fclose; 1647 st.st_size = 0; 1648 } else { 1649 char line[BUFSIZ]; 1650 1651 (void) snprintf(line, sizeof(line), cmd, name), name = line; 1652 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose; 1653 st.st_size = -1; 1654 st.st_blksize = BUFSIZ; 1655 } 1656 if (fin == NULL) { 1657 if (errno != 0) { 1658 perror_reply(550, name); 1659 if (cmd == 0) { 1660 LOGCMD("get", name); 1661 } 1662 } 1663 return; 1664 } 1665 byte_count = -1; 1666 if (cmd == 0 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) { 1667 reply(550, "%s: not a plain file.", name); 1668 goto done; 1669 } 1670 if (restart_point) { 1671 if (type == TYPE_A) { 1672 off_t i, n; 1673 int c; 1674 1675 n = restart_point; 1676 i = 0; 1677 while (i++ < n) { 1678 if ((c=getc(fin)) == EOF) { 1679 perror_reply(550, name); 1680 goto done; 1681 } 1682 if (c == '\n') 1683 i++; 1684 } 1685 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) { 1686 perror_reply(550, name); 1687 goto done; 1688 } 1689 } 1690 dout = dataconn(name, st.st_size, "w"); 1691 if (dout == NULL) 1692 goto done; 1693 time(&start); 1694 send_data(fin, dout, st.st_blksize, st.st_size, 1695 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode)); 1696 if (cmd == 0 && guest && stats) 1697 logxfer(name, st.st_size, start); 1698 (void) fclose(dout); 1699 data = -1; 1700 pdata = -1; 1701done: 1702 if (cmd == 0) 1703 LOGBYTES("get", name, byte_count); 1704 (*closefunc)(fin); 1705} 1706 1707void 1708store(char *name, char *mode, int unique) 1709{ 1710 int fd; 1711 FILE *fout, *din; 1712 int (*closefunc)(FILE *); 1713 1714 if (*mode == 'a') { /* APPE */ 1715 if (unique) { 1716 /* Programming error */ 1717 syslog(LOG_ERR, "Internal: unique flag to APPE"); 1718 unique = 0; 1719 } 1720 if (guest && noguestmod) { 1721 reply(550, "Appending to existing file denied"); 1722 goto err; 1723 } 1724 restart_point = 0; /* not affected by preceding REST */ 1725 } 1726 if (unique) /* STOU overrides REST */ 1727 restart_point = 0; 1728 if (guest && noguestmod) { 1729 if (restart_point) { /* guest STOR w/REST */ 1730 reply(550, "Modifying existing file denied"); 1731 goto err; 1732 } else /* treat guest STOR as STOU */ 1733 unique = 1; 1734 } 1735 1736 if (restart_point) 1737 mode = "r+"; /* so ASCII manual seek can work */ 1738 if (unique) { 1739 if ((fd = guniquefd(name, &name)) < 0) 1740 goto err; 1741 fout = fdopen(fd, mode); 1742 } else 1743 fout = fopen(name, mode); 1744 closefunc = fclose; 1745 if (fout == NULL) { 1746 perror_reply(553, name); 1747 goto err; 1748 } 1749 byte_count = -1; 1750 if (restart_point) { 1751 if (type == TYPE_A) { 1752 off_t i, n; 1753 int c; 1754 1755 n = restart_point; 1756 i = 0; 1757 while (i++ < n) { 1758 if ((c=getc(fout)) == EOF) { 1759 perror_reply(550, name); 1760 goto done; 1761 } 1762 if (c == '\n') 1763 i++; 1764 } 1765 /* 1766 * We must do this seek to "current" position 1767 * because we are changing from reading to 1768 * writing. 1769 */ 1770 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) { 1771 perror_reply(550, name); 1772 goto done; 1773 } 1774 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) { 1775 perror_reply(550, name); 1776 goto done; 1777 } 1778 } 1779 din = dataconn(name, (off_t)-1, "r"); 1780 if (din == NULL) 1781 goto done; 1782 if (receive_data(din, fout) == 0) { 1783 if (unique) 1784 reply(226, "Transfer complete (unique file name:%s).", 1785 name); 1786 else 1787 reply(226, "Transfer complete."); 1788 } 1789 (void) fclose(din); 1790 data = -1; 1791 pdata = -1; 1792done: 1793 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count); 1794 (*closefunc)(fout); 1795 return; 1796err: 1797 LOGCMD(*mode == 'a' ? "append" : "put" , name); 1798 return; 1799} 1800 1801static FILE * 1802getdatasock(char *mode) 1803{ 1804 int on = 1, s, t, tries; 1805 1806 if (data >= 0) 1807 return (fdopen(data, mode)); 1808 (void) seteuid((uid_t)0); 1809 1810 s = socket(data_dest.su_family, SOCK_STREAM, 0); 1811 if (s < 0) 1812 goto bad; 1813 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) 1814 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m"); 1815 /* anchor socket to avoid multi-homing problems */ 1816 data_source = ctrl_addr; 1817 data_source.su_port = htons(dataport); 1818 for (tries = 1; ; tries++) { 1819 if (bind(s, (struct sockaddr *)&data_source, 1820 data_source.su_len) >= 0) 1821 break; 1822 if (errno != EADDRINUSE || tries > 10) 1823 goto bad; 1824 sleep(tries); 1825 } 1826 (void) seteuid((uid_t)pw->pw_uid); 1827#ifdef IP_TOS 1828 if (data_source.su_family == AF_INET) 1829 { 1830 on = IPTOS_THROUGHPUT; 1831 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0) 1832 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m"); 1833 } 1834#endif 1835#ifdef TCP_NOPUSH 1836 /* 1837 * Turn off push flag to keep sender TCP from sending short packets 1838 * at the boundaries of each write(). Should probably do a SO_SNDBUF 1839 * to set the send buffer size as well, but that may not be desirable 1840 * in heavy-load situations. 1841 */ 1842 on = 1; 1843 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0) 1844 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m"); 1845#endif 1846#ifdef SO_SNDBUF 1847 on = 65536; 1848 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &on, sizeof on) < 0) 1849 syslog(LOG_WARNING, "data setsockopt (SO_SNDBUF): %m"); 1850#endif 1851 1852 return (fdopen(s, mode)); 1853bad: 1854 /* Return the real value of errno (close may change it) */ 1855 t = errno; 1856 (void) seteuid((uid_t)pw->pw_uid); 1857 (void) close(s); 1858 errno = t; 1859 return (NULL); 1860} 1861 1862static FILE * 1863dataconn(char *name, off_t size, char *mode) 1864{ 1865 char sizebuf[32]; 1866 FILE *file; 1867 int retry = 0, tos, conerrno; 1868 1869 file_size = size; 1870 byte_count = 0; 1871 if (size != (off_t) -1) 1872 (void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)", size); 1873 else 1874 *sizebuf = '\0'; 1875 if (pdata >= 0) { 1876 union sockunion from; 1877 int flags; 1878 int s, fromlen = ctrl_addr.su_len; 1879 struct timeval timeout; 1880 fd_set set; 1881 1882 FD_ZERO(&set); 1883 FD_SET(pdata, &set); 1884 1885 timeout.tv_usec = 0; 1886 timeout.tv_sec = 120; 1887 1888 /* 1889 * Granted a socket is in the blocking I/O mode, 1890 * accept() will block after a successful select() 1891 * if the selected connection dies in between. 1892 * Therefore set the non-blocking I/O flag here. 1893 */ 1894 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 || 1895 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1) 1896 goto pdata_err; 1897 if (select(pdata+1, &set, (fd_set *) 0, (fd_set *) 0, &timeout) <= 0 || 1898 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0) 1899 goto pdata_err; 1900 (void) close(pdata); 1901 pdata = s; 1902 /* 1903 * Unset the inherited non-blocking I/O flag 1904 * on the child socket so stdio can work on it. 1905 */ 1906 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 || 1907 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1) 1908 goto pdata_err; 1909#ifdef IP_TOS 1910 if (from.su_family == AF_INET) 1911 { 1912 tos = IPTOS_THROUGHPUT; 1913 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0) 1914 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m"); 1915 } 1916#endif 1917 reply(150, "Opening %s mode data connection for '%s'%s.", 1918 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf); 1919 return (fdopen(pdata, mode)); 1920pdata_err: 1921 reply(425, "Can't open data connection."); 1922 (void) close(pdata); 1923 pdata = -1; 1924 return (NULL); 1925 } 1926 if (data >= 0) { 1927 reply(125, "Using existing data connection for '%s'%s.", 1928 name, sizebuf); 1929 usedefault = 1; 1930 return (fdopen(data, mode)); 1931 } 1932 if (usedefault) 1933 data_dest = his_addr; 1934 usedefault = 1; 1935 do { 1936 file = getdatasock(mode); 1937 if (file == NULL) { 1938 char hostbuf[BUFSIZ], portbuf[BUFSIZ]; 1939 getnameinfo((struct sockaddr *)&data_source, 1940 data_source.su_len, hostbuf, sizeof(hostbuf) - 1, 1941 portbuf, sizeof(portbuf), 1942 NI_NUMERICHOST|NI_NUMERICSERV); 1943 reply(425, "Can't create data socket (%s,%s): %s.", 1944 hostbuf, portbuf, strerror(errno)); 1945 return (NULL); 1946 } 1947 data = fileno(file); 1948 conerrno = 0; 1949 if (connect(data, (struct sockaddr *)&data_dest, 1950 data_dest.su_len) == 0) 1951 break; 1952 conerrno = errno; 1953 (void) fclose(file); 1954 data = -1; 1955 if (conerrno == EADDRINUSE) { 1956 sleep((unsigned) swaitint); 1957 retry += swaitint; 1958 } else { 1959 break; 1960 } 1961 } while (retry <= swaitmax); 1962 if (conerrno != 0) { 1963 perror_reply(425, "Can't build data connection"); 1964 return (NULL); 1965 } 1966 reply(150, "Opening %s mode data connection for '%s'%s.", 1967 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf); 1968 return (file); 1969} 1970 1971/* 1972 * Tranfer the contents of "instr" to "outstr" peer using the appropriate 1973 * encapsulation of the data subject to Mode, Structure, and Type. 1974 * 1975 * NB: Form isn't handled. 1976 */ 1977static int 1978send_data(FILE *instr, FILE *outstr, off_t blksize, off_t filesize, int isreg) 1979{ 1980 int c, filefd, netfd; 1981 char *buf; 1982 off_t cnt; 1983 1984 transflag++; 1985 switch (type) { 1986 1987 case TYPE_A: 1988 while ((c = getc(instr)) != EOF) { 1989 if (recvurg) 1990 goto got_oob; 1991 byte_count++; 1992 if (c == '\n') { 1993 if (ferror(outstr)) 1994 goto data_err; 1995 (void) putc('\r', outstr); 1996 } 1997 (void) putc(c, outstr); 1998 } 1999 if (recvurg) 2000 goto got_oob; 2001 fflush(outstr); 2002 transflag = 0; 2003 if (ferror(instr)) 2004 goto file_err; 2005 if (ferror(outstr)) 2006 goto data_err; 2007 reply(226, "Transfer complete."); 2008 return (0); 2009 2010 case TYPE_I: 2011 case TYPE_L: 2012 /* 2013 * isreg is only set if we are not doing restart and we 2014 * are sending a regular file 2015 */ 2016 netfd = fileno(outstr); 2017 filefd = fileno(instr); 2018 2019 if (isreg) { 2020 2021 off_t offset; 2022 int err; 2023 2024 err = cnt = offset = 0; 2025 2026 while (err != -1 && filesize > 0) { 2027 err = sendfile(filefd, netfd, offset, 0, 2028 (struct sf_hdtr *) NULL, &cnt, 0); 2029 /* 2030 * Calculate byte_count before OOB processing. 2031 * It can be used in myoob() later. 2032 */ 2033 byte_count += cnt; 2034 if (recvurg) 2035 goto got_oob; 2036 offset += cnt; 2037 filesize -= cnt; 2038 2039 if (err == -1) { 2040 if (!cnt) 2041 goto oldway; 2042 2043 goto data_err; 2044 } 2045 } 2046 2047 transflag = 0; 2048 reply(226, "Transfer complete."); 2049 return (0); 2050 } 2051 2052oldway: 2053 if ((buf = malloc((u_int)blksize)) == NULL) { 2054 transflag = 0; 2055 perror_reply(451, "Local resource failure: malloc"); 2056 return (-1); 2057 } 2058 2059 while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 && 2060 write(netfd, buf, cnt) == cnt) 2061 byte_count += cnt; 2062 transflag = 0; 2063 (void)free(buf); 2064 if (cnt != 0) { 2065 if (cnt < 0) 2066 goto file_err; 2067 goto data_err; 2068 } 2069 reply(226, "Transfer complete."); 2070 return (0); 2071 default: 2072 transflag = 0; 2073 reply(550, "Unimplemented TYPE %d in send_data", type); 2074 return (-1); 2075 } 2076 2077data_err: 2078 transflag = 0; 2079 perror_reply(426, "Data connection"); 2080 return (-1); 2081 2082file_err: 2083 transflag = 0; 2084 perror_reply(551, "Error on input file"); 2085 return (-1); 2086 2087got_oob: 2088 myoob(); 2089 recvurg = 0; 2090 transflag = 0; 2091 return (-1); 2092} 2093 2094/* 2095 * Transfer data from peer to "outstr" using the appropriate encapulation of 2096 * the data subject to Mode, Structure, and Type. 2097 * 2098 * N.B.: Form isn't handled. 2099 */ 2100static int 2101receive_data(FILE *instr, FILE *outstr) 2102{ 2103 int c; 2104 int cnt, bare_lfs; 2105 char buf[BUFSIZ]; 2106 2107 transflag++; 2108 bare_lfs = 0; 2109 2110 switch (type) { 2111 2112 case TYPE_I: 2113 case TYPE_L: 2114 while ((cnt = read(fileno(instr), buf, sizeof(buf))) > 0) { 2115 if (recvurg) 2116 goto got_oob; 2117 if (write(fileno(outstr), buf, cnt) != cnt) 2118 goto file_err; 2119 byte_count += cnt; 2120 } 2121 if (recvurg) 2122 goto got_oob; 2123 if (cnt < 0) 2124 goto data_err; 2125 transflag = 0; 2126 return (0); 2127 2128 case TYPE_E: 2129 reply(553, "TYPE E not implemented."); 2130 transflag = 0; 2131 return (-1); 2132 2133 case TYPE_A: 2134 while ((c = getc(instr)) != EOF) { 2135 if (recvurg) 2136 goto got_oob; 2137 byte_count++; 2138 if (c == '\n') 2139 bare_lfs++; 2140 while (c == '\r') { 2141 if (ferror(outstr)) 2142 goto data_err; 2143 if ((c = getc(instr)) != '\n') { 2144 (void) putc ('\r', outstr); 2145 if (c == '\0' || c == EOF) 2146 goto contin2; 2147 } 2148 } 2149 (void) putc(c, outstr); 2150 contin2: ; 2151 } 2152 if (recvurg) 2153 goto got_oob; 2154 fflush(outstr); 2155 if (ferror(instr)) 2156 goto data_err; 2157 if (ferror(outstr)) 2158 goto file_err; 2159 transflag = 0; 2160 if (bare_lfs) { 2161 lreply(226, 2162 "WARNING! %d bare linefeeds received in ASCII mode", 2163 bare_lfs); 2164 (void)printf(" File may not have transferred correctly.\r\n"); 2165 } 2166 return (0); 2167 default: 2168 reply(550, "Unimplemented TYPE %d in receive_data", type); 2169 transflag = 0; 2170 return (-1); 2171 } 2172 2173data_err: 2174 transflag = 0; 2175 perror_reply(426, "Data Connection"); 2176 return (-1); 2177 2178file_err: 2179 transflag = 0; 2180 perror_reply(452, "Error writing file"); 2181 return (-1); 2182 2183got_oob: 2184 myoob(); 2185 recvurg = 0; 2186 transflag = 0; 2187 return (-1); 2188} 2189 2190void 2191statfilecmd(char *filename) 2192{ 2193 FILE *fin; 2194 int atstart; 2195 int c; 2196 char line[LINE_MAX]; 2197 2198 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename); 2199 fin = ftpd_popen(line, "r"); 2200 lreply(211, "status of %s:", filename); 2201 atstart = 1; 2202 while ((c = getc(fin)) != EOF) { 2203 if (c == '\n') { 2204 if (ferror(stdout)){ 2205 perror_reply(421, "control connection"); 2206 (void) ftpd_pclose(fin); 2207 dologout(1); 2208 /* NOTREACHED */ 2209 } 2210 if (ferror(fin)) { 2211 perror_reply(551, filename); 2212 (void) ftpd_pclose(fin); 2213 return; 2214 } 2215 (void) putc('\r', stdout); 2216 } 2217 /* 2218 * RFC 959 says neutral text should be prepended before 2219 * a leading 3-digit number followed by whitespace, but 2220 * many ftp clients can be confused by any leading digits, 2221 * as a matter of fact. 2222 */ 2223 if (atstart && isdigit(c)) 2224 (void) putc(' ', stdout); 2225 (void) putc(c, stdout); 2226 atstart = (c == '\n'); 2227 } 2228 (void) ftpd_pclose(fin); 2229 reply(211, "End of Status"); 2230} 2231 2232void 2233statcmd(void) 2234{ 2235 union sockunion *su; 2236 u_char *a, *p; 2237 char hname[NI_MAXHOST]; 2238 int ispassive; 2239 2240 if (hostinfo) { 2241 lreply(211, "%s FTP server status:", hostname); 2242 printf(" %s\r\n", version); 2243 } else 2244 lreply(211, "FTP server status:"); 2245 printf(" Connected to %s", remotehost); 2246 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len, 2247 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) { 2248 if (strcmp(hname, remotehost) != 0) 2249 printf(" (%s)", hname); 2250 } 2251 printf("\r\n"); 2252 if (logged_in) { 2253 if (guest) 2254 printf(" Logged in anonymously\r\n"); 2255 else 2256 printf(" Logged in as %s\r\n", pw->pw_name); 2257 } else if (askpasswd) 2258 printf(" Waiting for password\r\n"); 2259 else 2260 printf(" Waiting for user name\r\n"); 2261 printf(" TYPE: %s", typenames[type]); 2262 if (type == TYPE_A || type == TYPE_E) 2263 printf(", FORM: %s", formnames[form]); 2264 if (type == TYPE_L) 2265#if CHAR_BIT == 8 2266 printf(" %d", CHAR_BIT); 2267#else 2268 printf(" %d", bytesize); /* need definition! */ 2269#endif 2270 printf("; STRUcture: %s; transfer MODE: %s\r\n", 2271 strunames[stru], modenames[mode]); 2272 if (data != -1) 2273 printf(" Data connection open\r\n"); 2274 else if (pdata != -1) { 2275 ispassive = 1; 2276 su = &pasv_addr; 2277 goto printaddr; 2278 } else if (usedefault == 0) { 2279 ispassive = 0; 2280 su = &data_dest; 2281printaddr: 2282#define UC(b) (((int) b) & 0xff) 2283 if (epsvall) { 2284 printf(" EPSV only mode (EPSV ALL)\r\n"); 2285 goto epsvonly; 2286 } 2287 2288 /* PORT/PASV */ 2289 if (su->su_family == AF_INET) { 2290 a = (u_char *) &su->su_sin.sin_addr; 2291 p = (u_char *) &su->su_sin.sin_port; 2292 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n", 2293 ispassive ? "PASV" : "PORT", 2294 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]), 2295 UC(p[0]), UC(p[1])); 2296 } 2297 2298 /* LPRT/LPSV */ 2299 { 2300 int alen, af, i; 2301 2302 switch (su->su_family) { 2303 case AF_INET: 2304 a = (u_char *) &su->su_sin.sin_addr; 2305 p = (u_char *) &su->su_sin.sin_port; 2306 alen = sizeof(su->su_sin.sin_addr); 2307 af = 4; 2308 break; 2309 case AF_INET6: 2310 a = (u_char *) &su->su_sin6.sin6_addr; 2311 p = (u_char *) &su->su_sin6.sin6_port; 2312 alen = sizeof(su->su_sin6.sin6_addr); 2313 af = 6; 2314 break; 2315 default: 2316 af = 0; 2317 break; 2318 } 2319 if (af) { 2320 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT", 2321 af, alen); 2322 for (i = 0; i < alen; i++) 2323 printf("%d,", UC(a[i])); 2324 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1])); 2325 } 2326 } 2327 2328epsvonly:; 2329 /* EPRT/EPSV */ 2330 { 2331 int af; 2332 2333 switch (su->su_family) { 2334 case AF_INET: 2335 af = 1; 2336 break; 2337 case AF_INET6: 2338 af = 2; 2339 break; 2340 default: 2341 af = 0; 2342 break; 2343 } 2344 if (af) { 2345 union sockunion tmp; 2346 2347 tmp = *su; 2348 if (tmp.su_family == AF_INET6) 2349 tmp.su_sin6.sin6_scope_id = 0; 2350 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len, 2351 hname, sizeof(hname) - 1, NULL, 0, 2352 NI_NUMERICHOST)) { 2353 printf(" %s |%d|%s|%d|\r\n", 2354 ispassive ? "EPSV" : "EPRT", 2355 af, hname, htons(tmp.su_port)); 2356 } 2357 } 2358 } 2359#undef UC 2360 } else 2361 printf(" No data connection\r\n"); 2362 reply(211, "End of status"); 2363} 2364 2365void 2366fatalerror(char *s) 2367{ 2368 2369 reply(451, "Error in server: %s\n", s); 2370 reply(221, "Closing connection due to server error."); 2371 dologout(0); 2372 /* NOTREACHED */ 2373} 2374 2375void 2376reply(int n, const char *fmt, ...) 2377{ 2378 va_list ap; 2379 2380 va_start(ap, fmt); 2381 (void)printf("%d ", n); 2382 (void)vprintf(fmt, ap); 2383 (void)printf("\r\n"); 2384 (void)fflush(stdout); 2385 if (ftpdebug) { 2386 syslog(LOG_DEBUG, "<--- %d ", n); 2387 vsyslog(LOG_DEBUG, fmt, ap); 2388 } 2389} 2390 2391void 2392lreply(int n, const char *fmt, ...) 2393{ 2394 va_list ap; 2395 2396 va_start(ap, fmt); 2397 (void)printf("%d- ", n); 2398 (void)vprintf(fmt, ap); 2399 (void)printf("\r\n"); 2400 (void)fflush(stdout); 2401 if (ftpdebug) { 2402 syslog(LOG_DEBUG, "<--- %d- ", n); 2403 vsyslog(LOG_DEBUG, fmt, ap); 2404 } 2405} 2406 2407static void 2408ack(char *s) 2409{ 2410 2411 reply(250, "%s command successful.", s); 2412} 2413 2414void 2415nack(char *s) 2416{ 2417 2418 reply(502, "%s command not implemented.", s); 2419} 2420 2421/* ARGSUSED */ 2422void 2423yyerror(char *s) 2424{ 2425 char *cp; 2426 2427 if ((cp = strchr(cbuf,'\n'))) 2428 *cp = '\0'; 2429 reply(500, "'%s': command not understood.", cbuf); 2430} 2431 2432void 2433delete(char *name) 2434{ 2435 struct stat st; 2436 2437 LOGCMD("delete", name); 2438 if (lstat(name, &st) < 0) { 2439 perror_reply(550, name); 2440 return; 2441 } 2442 if ((st.st_mode&S_IFMT) == S_IFDIR) { 2443 if (rmdir(name) < 0) { 2444 perror_reply(550, name); 2445 return; 2446 } 2447 goto done; 2448 } 2449 if (unlink(name) < 0) { 2450 perror_reply(550, name); 2451 return; 2452 } 2453done: 2454 ack("DELE"); 2455} 2456 2457void 2458cwd(char *path) 2459{ 2460 2461 if (chdir(path) < 0) 2462 perror_reply(550, path); 2463 else 2464 ack("CWD"); 2465} 2466 2467void 2468makedir(char *name) 2469{ 2470 char *s; 2471 2472 LOGCMD("mkdir", name); 2473 if (guest && noguestmkd) 2474 reply(550, "%s: permission denied", name); 2475 else if (mkdir(name, 0777) < 0) 2476 perror_reply(550, name); 2477 else { 2478 if ((s = doublequote(name)) == NULL) 2479 fatalerror("Ran out of memory."); 2480 reply(257, "\"%s\" directory created.", s); 2481 free(s); 2482 } 2483} 2484 2485void 2486removedir(char *name) 2487{ 2488 2489 LOGCMD("rmdir", name); 2490 if (rmdir(name) < 0) 2491 perror_reply(550, name); 2492 else 2493 ack("RMD"); 2494} 2495 2496void 2497pwd(void) 2498{ 2499 char *s, path[MAXPATHLEN + 1]; 2500 2501 if (getwd(path) == (char *)NULL) 2502 reply(550, "%s.", path); 2503 else { 2504 if ((s = doublequote(path)) == NULL) 2505 fatalerror("Ran out of memory."); 2506 reply(257, "\"%s\" is current directory.", s); 2507 free(s); 2508 } 2509} 2510 2511char * 2512renamefrom(char *name) 2513{ 2514 struct stat st; 2515 2516 if (lstat(name, &st) < 0) { 2517 perror_reply(550, name); 2518 return ((char *)0); 2519 } 2520 reply(350, "File exists, ready for destination name"); 2521 return (name); 2522} 2523 2524void 2525renamecmd(char *from, char *to) 2526{ 2527 struct stat st; 2528 2529 LOGCMD2("rename", from, to); 2530 2531 if (guest && (stat(to, &st) == 0)) { 2532 reply(550, "%s: permission denied", to); 2533 return; 2534 } 2535 2536 if (rename(from, to) < 0) 2537 perror_reply(550, "rename"); 2538 else 2539 ack("RNTO"); 2540} 2541 2542static void 2543dolog(struct sockaddr *who) 2544{ 2545 int error; 2546 2547 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len); 2548 2549#ifdef SETPROCTITLE 2550#ifdef VIRTUAL_HOSTING 2551 if (thishost != firsthost) 2552 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)", 2553 remotehost, hostname); 2554 else 2555#endif 2556 snprintf(proctitle, sizeof(proctitle), "%s: connected", 2557 remotehost); 2558 setproctitle("%s", proctitle); 2559#endif /* SETPROCTITLE */ 2560 2561 if (logging) { 2562#ifdef VIRTUAL_HOSTING 2563 if (thishost != firsthost) 2564 syslog(LOG_INFO, "connection from %s (to %s)", 2565 remotehost, hostname); 2566 else 2567#endif 2568 { 2569 char who_name[MAXHOSTNAMELEN]; 2570 2571 error = getnameinfo(who, who->sa_len, 2572 who_name, sizeof(who_name) - 1, 2573 NULL, 0, NI_NUMERICHOST); 2574 syslog(LOG_INFO, "connection from %s (%s)", remotehost, 2575 error == 0 ? who_name : ""); 2576 } 2577 } 2578} 2579 2580/* 2581 * Record logout in wtmp file 2582 * and exit with supplied status. 2583 */ 2584void 2585dologout(int status) 2586{ 2587 /* 2588 * Prevent reception of SIGURG from resulting in a resumption 2589 * back to the main program loop. 2590 */ 2591 transflag = 0; 2592 2593 if (logged_in && dowtmp) { 2594 (void) seteuid((uid_t)0); 2595 ftpd_logwtmp(ttyline, "", NULL); 2596 } 2597 /* beware of flushing buffers after a SIGPIPE */ 2598 _exit(status); 2599} 2600 2601static void 2602sigurg(int signo) 2603{ 2604 2605 recvurg = 1; 2606} 2607 2608static void 2609myoob(void) 2610{ 2611 char *cp; 2612 2613 /* only process if transfer occurring */ 2614 if (!transflag) 2615 return; 2616 cp = tmpline; 2617 if (getline(cp, 7, stdin) == NULL) { 2618 reply(221, "You could at least say goodbye."); 2619 dologout(0); 2620 } 2621 upper(cp); 2622 if (strcmp(cp, "ABOR\r\n") == 0) { 2623 tmpline[0] = '\0'; 2624 reply(426, "Transfer aborted. Data connection closed."); 2625 reply(226, "Abort successful"); 2626 } 2627 if (strcmp(cp, "STAT\r\n") == 0) { 2628 tmpline[0] = '\0'; 2629 if (file_size != (off_t) -1) 2630 reply(213, "Status: %qd of %qd bytes transferred", 2631 byte_count, file_size); 2632 else 2633 reply(213, "Status: %qd bytes transferred", byte_count); 2634 } 2635} 2636 2637/* 2638 * Note: a response of 425 is not mentioned as a possible response to 2639 * the PASV command in RFC959. However, it has been blessed as 2640 * a legitimate response by Jon Postel in a telephone conversation 2641 * with Rick Adams on 25 Jan 89. 2642 */ 2643void 2644passive(void) 2645{ 2646 int len, on; 2647 char *p, *a; 2648 2649 if (pdata >= 0) /* close old port if one set */ 2650 close(pdata); 2651 2652 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0); 2653 if (pdata < 0) { 2654 perror_reply(425, "Can't open passive connection"); 2655 return; 2656 } 2657 on = 1; 2658 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) 2659 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m"); 2660 2661 (void) seteuid((uid_t)0); 2662 2663#ifdef IP_PORTRANGE 2664 if (ctrl_addr.su_family == AF_INET) { 2665 on = restricted_data_ports ? IP_PORTRANGE_HIGH 2666 : IP_PORTRANGE_DEFAULT; 2667 2668 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE, 2669 &on, sizeof(on)) < 0) 2670 goto pasv_error; 2671 } 2672#endif 2673#ifdef IPV6_PORTRANGE 2674 if (ctrl_addr.su_family == AF_INET6) { 2675 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH 2676 : IPV6_PORTRANGE_DEFAULT; 2677 2678 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE, 2679 &on, sizeof(on)) < 0) 2680 goto pasv_error; 2681 } 2682#endif 2683 2684 pasv_addr = ctrl_addr; 2685 pasv_addr.su_port = 0; 2686 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0) 2687 goto pasv_error; 2688 2689 (void) seteuid((uid_t)pw->pw_uid); 2690 2691 len = sizeof(pasv_addr); 2692 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0) 2693 goto pasv_error; 2694 if (listen(pdata, 1) < 0) 2695 goto pasv_error; 2696 if (pasv_addr.su_family == AF_INET) 2697 a = (char *) &pasv_addr.su_sin.sin_addr; 2698 else if (pasv_addr.su_family == AF_INET6 && 2699 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) 2700 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12]; 2701 else 2702 goto pasv_error; 2703 2704 p = (char *) &pasv_addr.su_port; 2705 2706#define UC(b) (((int) b) & 0xff) 2707 2708 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]), 2709 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1])); 2710 return; 2711 2712pasv_error: 2713 (void) seteuid((uid_t)pw->pw_uid); 2714 (void) close(pdata); 2715 pdata = -1; 2716 perror_reply(425, "Can't open passive connection"); 2717 return; 2718} 2719 2720/* 2721 * Long Passive defined in RFC 1639. 2722 * 228 Entering Long Passive Mode 2723 * (af, hal, h1, h2, h3,..., pal, p1, p2...) 2724 */ 2725 2726void 2727long_passive(char *cmd, int pf) 2728{ 2729 int len, on; 2730 char *p, *a; 2731 2732 if (pdata >= 0) /* close old port if one set */ 2733 close(pdata); 2734 2735 if (pf != PF_UNSPEC) { 2736 if (ctrl_addr.su_family != pf) { 2737 switch (ctrl_addr.su_family) { 2738 case AF_INET: 2739 pf = 1; 2740 break; 2741 case AF_INET6: 2742 pf = 2; 2743 break; 2744 default: 2745 pf = 0; 2746 break; 2747 } 2748 /* 2749 * XXX 2750 * only EPRT/EPSV ready clients will understand this 2751 */ 2752 if (strcmp(cmd, "EPSV") == 0 && pf) { 2753 reply(522, "Network protocol mismatch, " 2754 "use (%d)", pf); 2755 } else 2756 reply(501, "Network protocol mismatch"); /*XXX*/ 2757 2758 return; 2759 } 2760 } 2761 2762 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0); 2763 if (pdata < 0) { 2764 perror_reply(425, "Can't open passive connection"); 2765 return; 2766 } 2767 on = 1; 2768 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) 2769 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m"); 2770 2771 (void) seteuid((uid_t)0); 2772 2773 pasv_addr = ctrl_addr; 2774 pasv_addr.su_port = 0; 2775 len = pasv_addr.su_len; 2776 2777#ifdef IP_PORTRANGE 2778 if (ctrl_addr.su_family == AF_INET) { 2779 on = restricted_data_ports ? IP_PORTRANGE_HIGH 2780 : IP_PORTRANGE_DEFAULT; 2781 2782 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE, 2783 &on, sizeof(on)) < 0) 2784 goto pasv_error; 2785 } 2786#endif 2787#ifdef IPV6_PORTRANGE 2788 if (ctrl_addr.su_family == AF_INET6) { 2789 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH 2790 : IPV6_PORTRANGE_DEFAULT; 2791 2792 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE, 2793 &on, sizeof(on)) < 0) 2794 goto pasv_error; 2795 } 2796#endif 2797 2798 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0) 2799 goto pasv_error; 2800 2801 (void) seteuid((uid_t)pw->pw_uid); 2802 2803 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0) 2804 goto pasv_error; 2805 if (listen(pdata, 1) < 0) 2806 goto pasv_error; 2807 2808#define UC(b) (((int) b) & 0xff) 2809 2810 if (strcmp(cmd, "LPSV") == 0) { 2811 p = (char *)&pasv_addr.su_port; 2812 switch (pasv_addr.su_family) { 2813 case AF_INET: 2814 a = (char *) &pasv_addr.su_sin.sin_addr; 2815 v4_reply: 2816 reply(228, 2817"Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)", 2818 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]), 2819 2, UC(p[0]), UC(p[1])); 2820 return; 2821 case AF_INET6: 2822 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) { 2823 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12]; 2824 goto v4_reply; 2825 } 2826 a = (char *) &pasv_addr.su_sin6.sin6_addr; 2827 reply(228, 2828"Entering Long Passive Mode " 2829"(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)", 2830 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]), 2831 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]), 2832 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]), 2833 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]), 2834 2, UC(p[0]), UC(p[1])); 2835 return; 2836 } 2837 } else if (strcmp(cmd, "EPSV") == 0) { 2838 switch (pasv_addr.su_family) { 2839 case AF_INET: 2840 case AF_INET6: 2841 reply(229, "Entering Extended Passive Mode (|||%d|)", 2842 ntohs(pasv_addr.su_port)); 2843 return; 2844 } 2845 } else { 2846 /* more proper error code? */ 2847 } 2848 2849pasv_error: 2850 (void) seteuid((uid_t)pw->pw_uid); 2851 (void) close(pdata); 2852 pdata = -1; 2853 perror_reply(425, "Can't open passive connection"); 2854 return; 2855} 2856 2857/* 2858 * Generate unique name for file with basename "local" 2859 * and open the file in order to avoid possible races. 2860 * Try "local" first, then "local.1", "local.2" etc, up to "local.99". 2861 * Return descriptor to the file, set "name" to its name. 2862 * 2863 * Generates failure reply on error. 2864 */ 2865static int 2866guniquefd(char *local, char **name) 2867{ 2868 static char new[MAXPATHLEN]; 2869 struct stat st; 2870 char *cp; 2871 int count; 2872 int fd; 2873 2874 cp = strrchr(local, '/'); 2875 if (cp) 2876 *cp = '\0'; 2877 if (stat(cp ? local : ".", &st) < 0) { 2878 perror_reply(553, cp ? local : "."); 2879 return (-1); 2880 } 2881 if (cp) { 2882 /* 2883 * Let not overwrite dirname with counter suffix. 2884 * -4 is for /nn\0 2885 * In this extreme case dot won't be put in front of suffix. 2886 */ 2887 if (strlen(local) > sizeof(new) - 4) { 2888 reply(553, "Pathname too long"); 2889 return (-1); 2890 } 2891 *cp = '/'; 2892 } 2893 /* -4 is for the .nn<null> we put on the end below */ 2894 (void) snprintf(new, sizeof(new) - 4, "%s", local); 2895 cp = new + strlen(new); 2896 /* 2897 * Don't generate dotfile unless requested explicitly. 2898 * This covers the case when basename gets truncated off 2899 * by buffer size. 2900 */ 2901 if (cp > new && cp[-1] != '/') 2902 *cp++ = '.'; 2903 for (count = 0; count < 100; count++) { 2904 /* At count 0 try unmodified name */ 2905 if (count) 2906 (void)sprintf(cp, "%d", count); 2907 if ((fd = open(count ? new : local, 2908 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) { 2909 *name = count ? new : local; 2910 return (fd); 2911 } 2912 } 2913 reply(452, "Unique file name cannot be created."); 2914 return (-1); 2915} 2916 2917/* 2918 * Format and send reply containing system error number. 2919 */ 2920void 2921perror_reply(int code, char *string) 2922{ 2923 2924 reply(code, "%s: %s.", string, strerror(errno)); 2925} 2926 2927static char *onefile[] = { 2928 "", 2929 0 2930}; 2931 2932void 2933send_file_list(char *whichf) 2934{ 2935 struct stat st; 2936 DIR *dirp = NULL; 2937 struct dirent *dir; 2938 FILE *dout = NULL; 2939 char **dirlist, *dirname; 2940 int simple = 0; 2941 int freeglob = 0; 2942 glob_t gl; 2943 2944 if (strpbrk(whichf, "~{[*?") != NULL) { 2945 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE; 2946 2947 memset(&gl, 0, sizeof(gl)); 2948 gl.gl_matchc = MAXGLOBARGS; 2949 flags |= GLOB_LIMIT; 2950 freeglob = 1; 2951 if (glob(whichf, flags, 0, &gl)) { 2952 reply(550, "not found"); 2953 goto out; 2954 } else if (gl.gl_pathc == 0) { 2955 errno = ENOENT; 2956 perror_reply(550, whichf); 2957 goto out; 2958 } 2959 dirlist = gl.gl_pathv; 2960 } else { 2961 onefile[0] = whichf; 2962 dirlist = onefile; 2963 simple = 1; 2964 } 2965 2966 while ((dirname = *dirlist++)) { 2967 if (stat(dirname, &st) < 0) { 2968 /* 2969 * If user typed "ls -l", etc, and the client 2970 * used NLST, do what the user meant. 2971 */ 2972 if (dirname[0] == '-' && *dirlist == NULL && 2973 transflag == 0) { 2974 retrieve(_PATH_LS " %s", dirname); 2975 goto out; 2976 } 2977 perror_reply(550, whichf); 2978 if (dout != NULL) { 2979 (void) fclose(dout); 2980 transflag = 0; 2981 data = -1; 2982 pdata = -1; 2983 } 2984 goto out; 2985 } 2986 2987 if (S_ISREG(st.st_mode)) { 2988 if (dout == NULL) { 2989 dout = dataconn("file list", (off_t)-1, "w"); 2990 if (dout == NULL) 2991 goto out; 2992 transflag++; 2993 } 2994 fprintf(dout, "%s%s\n", dirname, 2995 type == TYPE_A ? "\r" : ""); 2996 byte_count += strlen(dirname) + 1; 2997 continue; 2998 } else if (!S_ISDIR(st.st_mode)) 2999 continue; 3000 3001 if ((dirp = opendir(dirname)) == NULL) 3002 continue; 3003 3004 while ((dir = readdir(dirp)) != NULL) { 3005 char nbuf[MAXPATHLEN]; 3006 3007 if (recvurg) { 3008 myoob(); 3009 recvurg = 0; 3010 transflag = 0; 3011 goto out; 3012 } 3013 3014 if (dir->d_name[0] == '.' && dir->d_namlen == 1) 3015 continue; 3016 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' && 3017 dir->d_namlen == 2) 3018 continue; 3019 3020 snprintf(nbuf, sizeof(nbuf), 3021 "%s/%s", dirname, dir->d_name); 3022 3023 /* 3024 * We have to do a stat to insure it's 3025 * not a directory or special file. 3026 */ 3027 if (simple || (stat(nbuf, &st) == 0 && 3028 S_ISREG(st.st_mode))) { 3029 if (dout == NULL) { 3030 dout = dataconn("file list", (off_t)-1, 3031 "w"); 3032 if (dout == NULL) 3033 goto out; 3034 transflag++; 3035 } 3036 if (nbuf[0] == '.' && nbuf[1] == '/') 3037 fprintf(dout, "%s%s\n", &nbuf[2], 3038 type == TYPE_A ? "\r" : ""); 3039 else 3040 fprintf(dout, "%s%s\n", nbuf, 3041 type == TYPE_A ? "\r" : ""); 3042 byte_count += strlen(nbuf) + 1; 3043 } 3044 } 3045 (void) closedir(dirp); 3046 } 3047 3048 if (dout == NULL) 3049 reply(550, "No files found."); 3050 else if (ferror(dout) != 0) 3051 perror_reply(550, "Data connection"); 3052 else 3053 reply(226, "Transfer complete."); 3054 3055 transflag = 0; 3056 if (dout != NULL) 3057 (void) fclose(dout); 3058 data = -1; 3059 pdata = -1; 3060out: 3061 if (freeglob) { 3062 freeglob = 0; 3063 globfree(&gl); 3064 } 3065} 3066 3067void 3068reapchild(int signo) 3069{ 3070 while (wait3(NULL, WNOHANG, NULL) > 0); 3071} 3072 3073#ifdef OLD_SETPROCTITLE 3074/* 3075 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.) 3076 * Warning, since this is usually started from inetd.conf, it often doesn't 3077 * have much of an environment or arglist to overwrite. 3078 */ 3079void 3080setproctitle(const char *fmt, ...) 3081{ 3082 int i; 3083 va_list ap; 3084 char *p, *bp, ch; 3085 char buf[LINE_MAX]; 3086 3087 va_start(ap, fmt); 3088 (void)vsnprintf(buf, sizeof(buf), fmt, ap); 3089 3090 /* make ps print our process name */ 3091 p = Argv[0]; 3092 *p++ = '-'; 3093 3094 i = strlen(buf); 3095 if (i > LastArgv - p - 2) { 3096 i = LastArgv - p - 2; 3097 buf[i] = '\0'; 3098 } 3099 bp = buf; 3100 while (ch = *bp++) 3101 if (ch != '\n' && ch != '\r') 3102 *p++ = ch; 3103 while (p < LastArgv) 3104 *p++ = ' '; 3105} 3106#endif /* OLD_SETPROCTITLE */ 3107 3108static void 3109logxfer(char *name, off_t size, time_t start) 3110{ 3111 char buf[1024]; 3112 char path[MAXPATHLEN + 1]; 3113 time_t now; 3114 3115 if (statfd >= 0 && getwd(path) != NULL) { 3116 time(&now); 3117 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s/%s!%qd!%ld\n", 3118 ctime(&now)+4, ident, remotehost, 3119 path, name, (long long)size, 3120 (long)(now - start + (now == start))); 3121 write(statfd, buf, strlen(buf)); 3122 } 3123} 3124 3125static char * 3126doublequote(char *s) 3127{ 3128 int n; 3129 char *p, *s2; 3130 3131 for (p = s, n = 0; *p; p++) 3132 if (*p == '"') 3133 n++; 3134 3135 if ((s2 = malloc(p - s + n + 1)) == NULL) 3136 return (NULL); 3137 3138 for (p = s2; *s; s++, p++) { 3139 if ((*p = *s) == '"') 3140 *(++p) = '"'; 3141 } 3142 *p = '\0'; 3143 3144 return (s2); 3145} 3146