ftpd.c revision 1.162
1/* $OpenBSD: ftpd.c,v 1.162 2004/12/06 23:04:14 deraadt Exp $ */ 2/* $NetBSD: ftpd.c,v 1.15 1995/06/03 22:46:47 mycroft Exp $ */ 3 4/* 5 * Copyright (C) 1997 and 1998 WIDE Project. 6 * All rights reserved. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 11 * 1. Redistributions of source code must retain the above copyright 12 * notice, this list of conditions and the following disclaimer. 13 * 2. Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in the 15 * documentation and/or other materials provided with the distribution. 16 * 3. Neither the name of the project nor the names of its contributors 17 * may be used to endorse or promote products derived from this software 18 * without specific prior written permission. 19 * 20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND 21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE 24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 30 * SUCH DAMAGE. 31 */ 32 33/* 34 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994 35 * The Regents of the University of California. All rights reserved. 36 * 37 * Redistribution and use in source and binary forms, with or without 38 * modification, are permitted provided that the following conditions 39 * are met: 40 * 1. Redistributions of source code must retain the above copyright 41 * notice, this list of conditions and the following disclaimer. 42 * 2. Redistributions in binary form must reproduce the above copyright 43 * notice, this list of conditions and the following disclaimer in the 44 * documentation and/or other materials provided with the distribution. 45 * 3. Neither the name of the University nor the names of its contributors 46 * may be used to endorse or promote products derived from this software 47 * without specific prior written permission. 48 * 49 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 50 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 51 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 52 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 53 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 54 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 55 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 56 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 57 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 58 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 59 * SUCH DAMAGE. 60 */ 61 62#ifndef lint 63static const char copyright[] = 64"@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\ 65 The Regents of the University of California. All rights reserved.\n"; 66#endif /* not lint */ 67 68#ifndef lint 69#if 0 70static const char sccsid[] = "@(#)ftpd.c 8.4 (Berkeley) 4/16/94"; 71#else 72static const char rcsid[] = 73 "$OpenBSD: ftpd.c,v 1.162 2004/12/06 23:04:14 deraadt Exp $"; 74#endif 75#endif /* not lint */ 76 77/* 78 * FTP server. 79 */ 80#include <sys/param.h> 81#include <sys/stat.h> 82#include <sys/ioctl.h> 83#include <sys/socket.h> 84#include <sys/wait.h> 85#include <sys/mman.h> 86 87#include <netinet/in.h> 88#include <netinet/in_systm.h> 89#include <netinet/ip.h> 90#include <netinet/tcp.h> 91 92#define FTP_NAMES 93#include <arpa/ftp.h> 94#include <arpa/inet.h> 95#include <arpa/telnet.h> 96 97#include <bsd_auth.h> 98#include <ctype.h> 99#include <dirent.h> 100#include <errno.h> 101#include <fcntl.h> 102#include <glob.h> 103#include <limits.h> 104#include <login_cap.h> 105#include <netdb.h> 106#include <pwd.h> 107#include <signal.h> 108#include <stdarg.h> 109#include <stdio.h> 110#include <stdlib.h> 111#include <string.h> 112#include <syslog.h> 113#include <time.h> 114#include <vis.h> 115#include <unistd.h> 116#include <util.h> 117#include <utmp.h> 118#include <poll.h> 119 120#if defined(TCPWRAPPERS) 121#include <tcpd.h> 122#endif /* TCPWRAPPERS */ 123 124#include "pathnames.h" 125#include "extern.h" 126#include "monitor.h" 127 128static char version[] = "Version 6.6/OpenBSD"; 129 130extern off_t restart_point; 131extern char cbuf[]; 132 133union sockunion server_addr; 134union sockunion ctrl_addr; 135union sockunion data_source; 136union sockunion data_dest; 137union sockunion his_addr; 138union sockunion pasv_addr; 139 140sigset_t allsigs; 141 142int daemon_mode = 0; 143int data; 144int logged_in; 145struct passwd *pw; 146int debug = 0; 147int timeout = 900; /* timeout after 15 minutes of inactivity */ 148int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */ 149int logging; 150int anon_ok = 1; 151int anon_only = 0; 152int multihome = 0; 153int guest; 154int stats; 155int statfd = -1; 156int portcheck = 1; 157int dochroot; 158int type; 159int form; 160int stru; /* avoid C keyword */ 161int mode; 162int doutmp = 0; /* update utmp file */ 163int usedefault = 1; /* for data transfers */ 164int pdata = -1; /* for passive mode */ 165int family = AF_UNSPEC; 166volatile sig_atomic_t transflag; 167off_t file_size; 168off_t byte_count; 169#if !defined(CMASK) || CMASK == 0 170#undef CMASK 171#define CMASK 022 172#endif 173int defumask = CMASK; /* default umask value */ 174int umaskchange = 1; /* allow user to change umask value. */ 175char tmpline[7]; 176char hostname[MAXHOSTNAMELEN]; 177char remotehost[MAXHOSTNAMELEN]; 178char dhostname[MAXHOSTNAMELEN]; 179char *guestpw; 180char ttyline[20]; 181char *tty = ttyline; /* for klogin */ 182static struct utmp utmp; /* for utmp */ 183static login_cap_t *lc; 184static auth_session_t *as; 185static volatile sig_atomic_t recvurg; 186 187#if defined(TCPWRAPPERS) 188int allow_severity = LOG_INFO; 189int deny_severity = LOG_NOTICE; 190#endif /* TCPWRAPPERS */ 191 192char *ident = NULL; 193 194 195int epsvall = 0; 196 197/* 198 * Timeout intervals for retrying connections 199 * to hosts that don't accept PORT cmds. This 200 * is a kludge, but given the problems with TCP... 201 */ 202#define SWAITMAX 90 /* wait at most 90 seconds */ 203#define SWAITINT 5 /* interval between retries */ 204 205int swaitmax = SWAITMAX; 206int swaitint = SWAITINT; 207 208#ifdef HASSETPROCTITLE 209char proctitle[BUFSIZ]; /* initial part of title */ 210#endif /* HASSETPROCTITLE */ 211 212#define LOGCMD(cmd, file) \ 213 if (logging > 1) \ 214 syslog(LOG_INFO,"%s %s%s", cmd, \ 215 *(file) == '/' ? "" : curdir(), file); 216#define LOGCMD2(cmd, file1, file2) \ 217 if (logging > 1) \ 218 syslog(LOG_INFO,"%s %s%s %s%s", cmd, \ 219 *(file1) == '/' ? "" : curdir(), file1, \ 220 *(file2) == '/' ? "" : curdir(), file2); 221#define LOGBYTES(cmd, file, cnt) \ 222 if (logging > 1) { \ 223 if (cnt == (off_t)-1) \ 224 syslog(LOG_INFO,"%s %s%s", cmd, \ 225 *(file) == '/' ? "" : curdir(), file); \ 226 else \ 227 syslog(LOG_INFO, "%s %s%s = %qd bytes", \ 228 cmd, (*(file) == '/') ? "" : curdir(), file, cnt); \ 229 } 230 231static void ack(char *); 232static void sigurg(int); 233static void myoob(void); 234static int checkuser(char *, char *); 235static FILE *dataconn(char *, off_t, char *); 236static void dolog(struct sockaddr *); 237static char *copy_dir(char *, struct passwd *); 238static char *curdir(void); 239static void end_login(void); 240static FILE *getdatasock(char *); 241static int guniquefd(char *, char **); 242static void lostconn(int); 243static void sigquit(int); 244static int receive_data(FILE *, FILE *); 245static void replydirname(const char *, const char *); 246static int send_data(FILE *, FILE *, off_t, off_t, int); 247static struct passwd * 248 sgetpwnam(char *, struct passwd *); 249static void reapchild(int); 250#if defined(TCPWRAPPERS) 251static int check_host(struct sockaddr *); 252#endif /* TCPWRAPPERS */ 253static void usage(void); 254 255void logxfer(char *, off_t, time_t); 256void set_slave_signals(void); 257 258static char * 259curdir(void) 260{ 261 static char path[MAXPATHLEN+1]; /* path + '/' */ 262 263 if (getcwd(path, sizeof(path)-1) == NULL) 264 return (""); 265 if (path[1] != '\0') /* special case for root dir. */ 266 strlcat(path, "/", sizeof path); 267 /* For guest account, skip / since it's chrooted */ 268 return (guest ? path+1 : path); 269} 270 271char *argstr = "AdDhnlMSt:T:u:UvP46"; 272 273static void 274usage(void) 275{ 276 syslog(LOG_ERR, 277 "usage: ftpd [-46ADdlMnPSU] [-T maxtimeout] [-t timeout] [-u mask]"); 278 exit(2); 279} 280 281int 282main(int argc, char *argv[]) 283{ 284 socklen_t addrlen; 285 int ch, on = 1, tos; 286 char *cp, line[LINE_MAX]; 287 FILE *fp; 288 struct hostent *hp; 289 struct sigaction sa; 290 291 tzset(); /* in case no timezone database in ~ftp */ 292 sigfillset(&allsigs); /* used to block signals while root */ 293 sigemptyset(&sa.sa_mask); 294 sa.sa_flags = SA_RESTART; 295 296 while ((ch = getopt(argc, argv, argstr)) != -1) { 297 switch (ch) { 298 case 'A': 299 anon_only = 1; 300 break; 301 302 case 'd': 303 case 'v': /* deprecated */ 304 debug = 1; 305 break; 306 307 case 'D': 308 daemon_mode = 1; 309 break; 310 311 case 'P': 312 portcheck = 0; 313 break; 314 315 case 'h': /* deprecated */ 316 break; 317 318 case 'l': 319 logging++; /* > 1 == extra logging */ 320 break; 321 322 case 'M': 323 multihome = 1; 324 break; 325 326 case 'n': 327 anon_ok = 0; 328 break; 329 330 case 'S': 331 stats = 1; 332 break; 333 334 case 't': 335 timeout = atoi(optarg); 336 if (maxtimeout < timeout) 337 maxtimeout = timeout; 338 break; 339 340 case 'T': 341 maxtimeout = atoi(optarg); 342 if (timeout > maxtimeout) 343 timeout = maxtimeout; 344 break; 345 346 case 'u': 347 { 348 long val = 0; 349 char *p; 350 umaskchange = 0; 351 352 val = strtol(optarg, &p, 8); 353 if (*p != '\0' || val < 0 || (val & ~ACCESSPERMS)) { 354 syslog(LOG_ERR, 355 "%s is a bad value for -u, aborting..", 356 optarg); 357 exit(2); 358 } else 359 defumask = val; 360 break; 361 } 362 363 case 'U': 364 doutmp = 1; 365 break; 366 367 case '4': 368 family = AF_INET; 369 break; 370 371 case '6': 372 family = AF_INET6; 373 break; 374 375 default: 376 usage(); 377 break; 378 } 379 } 380 381 (void) freopen(_PATH_DEVNULL, "w", stderr); 382 383 /* 384 * LOG_NDELAY sets up the logging connection immediately, 385 * necessary for anonymous ftp's that chroot and can't do it later. 386 */ 387 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP); 388 389 if (getpwnam(FTPD_PRIVSEP_USER) == NULL) { 390 syslog(LOG_ERR, "privilege separation user %s not found", 391 FTPD_PRIVSEP_USER); 392 exit(1); 393 } 394 endpwent(); 395 396 if (daemon_mode) { 397 int *fds, n, error, i, fd; 398 struct pollfd *pfds; 399 struct addrinfo hints, *res, *res0; 400 401 /* 402 * Detach from parent. 403 */ 404 if (daemon(1, 1) < 0) { 405 syslog(LOG_ERR, "failed to become a daemon"); 406 exit(1); 407 } 408 sa.sa_handler = reapchild; 409 (void) sigaction(SIGCHLD, &sa, NULL); 410 411 memset(&hints, 0, sizeof(hints)); 412 hints.ai_family = family; 413 hints.ai_socktype = SOCK_STREAM; 414 hints.ai_protocol = IPPROTO_TCP; 415 hints.ai_flags = AI_PASSIVE; 416 error = getaddrinfo(NULL, "ftp", &hints, &res0); 417 if (error) { 418 syslog(LOG_ERR, "%s", gai_strerror(error)); 419 exit(1); 420 } 421 422 n = 0; 423 for (res = res0; res; res = res->ai_next) 424 n++; 425 426 fds = malloc(n * sizeof(int)); 427 pfds = malloc(n * sizeof(struct pollfd)); 428 if (!fds || !pfds) { 429 syslog(LOG_ERR, "%s", strerror(errno)); 430 exit(1); 431 } 432 433 /* 434 * Open sockets, bind it to the FTP port, and start 435 * listening. 436 */ 437 n = 0; 438 for (res = res0; res; res = res->ai_next) { 439 fds[n] = socket(res->ai_family, res->ai_socktype, 440 res->ai_protocol); 441 if (fds[n] < 0) 442 continue; 443 444 if (setsockopt(fds[n], SOL_SOCKET, SO_REUSEADDR, 445 (char *)&on, sizeof(on)) < 0) { 446 close(fds[n]); 447 fds[n] = -1; 448 continue; 449 } 450 451 if (bind(fds[n], res->ai_addr, res->ai_addrlen) < 0) { 452 close(fds[n]); 453 fds[n] = -1; 454 continue; 455 } 456 if (listen(fds[n], 32) < 0) { 457 close(fds[n]); 458 fds[n] = -1; 459 continue; 460 } 461 462 pfds[n].fd = fds[n]; 463 pfds[n].events = POLLIN; 464 n++; 465 } 466 freeaddrinfo(res0); 467 468 if (n == 0) { 469 syslog(LOG_ERR, "could not open control socket"); 470 exit(1); 471 } 472 473 /* Stash pid in pidfile */ 474 if (pidfile(NULL)) 475 syslog(LOG_ERR, "can't open pidfile: %m"); 476 /* 477 * Loop forever accepting connection requests and forking off 478 * children to handle them. 479 */ 480 while (1) { 481 if (poll(pfds, n, INFTIM) < 0) { 482 if (errno == EINTR) 483 continue; 484 syslog(LOG_ERR, "poll: %m"); 485 exit(1); 486 } 487 for (i = 0; i < n; i++) 488 if (pfds[i].revents & POLLIN) { 489 addrlen = sizeof(his_addr); 490 fd = accept(pfds[i].fd, 491 (struct sockaddr *)&his_addr, 492 &addrlen); 493 if (fd != -1) { 494 if (fork() == 0) 495 goto child; 496 close(fd); 497 } 498 } 499 } 500 501 child: 502 /* child */ 503 (void)dup2(fd, STDIN_FILENO); 504 (void)dup2(fd, STDOUT_FILENO); 505 for (i = 0; i < n; i++) 506 close(fds[i]); 507#if defined(TCPWRAPPERS) 508 /* ..in the child. */ 509 if (!check_host((struct sockaddr *)&his_addr)) 510 exit(1); 511#endif /* TCPWRAPPERS */ 512 } else { 513 addrlen = sizeof(his_addr); 514 if (getpeername(0, (struct sockaddr *)&his_addr, 515 &addrlen) < 0) { 516 /* syslog(LOG_ERR, "getpeername (%s): %m", argv[0]); */ 517 exit(1); 518 } 519 } 520 521 /* set this here so klogin can use it... */ 522 (void)snprintf(ttyline, sizeof(ttyline), "ftp%ld", (long)getpid()); 523 524 set_slave_signals(); 525 526 addrlen = sizeof(ctrl_addr); 527 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) { 528 syslog(LOG_ERR, "getsockname: %m"); 529 exit(1); 530 } 531 if (his_addr.su_family == AF_INET6 532 && IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr)) { 533#if 1 534 /* 535 * IPv4 control connection arrived to AF_INET6 socket. 536 * I hate to do this, but this is the easiest solution. 537 */ 538 union sockunion tmp_addr; 539 const int off = sizeof(struct in6_addr) - sizeof(struct in_addr); 540 541 tmp_addr = his_addr; 542 memset(&his_addr, 0, sizeof(his_addr)); 543 his_addr.su_sin.sin_family = AF_INET; 544 his_addr.su_sin.sin_len = sizeof(his_addr.su_sin); 545 memcpy(&his_addr.su_sin.sin_addr, 546 &tmp_addr.su_sin6.sin6_addr.s6_addr[off], 547 sizeof(his_addr.su_sin.sin_addr)); 548 his_addr.su_sin.sin_port = tmp_addr.su_sin6.sin6_port; 549 550 tmp_addr = ctrl_addr; 551 memset(&ctrl_addr, 0, sizeof(ctrl_addr)); 552 ctrl_addr.su_sin.sin_family = AF_INET; 553 ctrl_addr.su_sin.sin_len = sizeof(ctrl_addr.su_sin); 554 memcpy(&ctrl_addr.su_sin.sin_addr, 555 &tmp_addr.su_sin6.sin6_addr.s6_addr[off], 556 sizeof(ctrl_addr.su_sin.sin_addr)); 557 ctrl_addr.su_sin.sin_port = tmp_addr.su_sin6.sin6_port; 558#else 559 while (fgets(line, sizeof(line), fd) != NULL) { 560 if ((cp = strchr(line, '\n')) != NULL) 561 *cp = '\0'; 562 lreply(530, "%s", line); 563 } 564 (void) fflush(stdout); 565 (void) fclose(fd); 566 reply(530, 567 "Connection from IPv4 mapped address is not supported."); 568 exit(0); 569#endif 570 } 571#ifdef IP_TOS 572 if (his_addr.su_family == AF_INET) { 573 tos = IPTOS_LOWDELAY; 574 if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos, 575 sizeof(int)) < 0) 576 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m"); 577 } 578#endif 579 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1); 580 581 /* Try to handle urgent data inline */ 582#ifdef SO_OOBINLINE 583 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0) 584 syslog(LOG_ERR, "setsockopt: %m"); 585#endif 586 587 dolog((struct sockaddr *)&his_addr); 588 /* 589 * Set up default state 590 */ 591 data = -1; 592 type = TYPE_A; 593 form = FORM_N; 594 stru = STRU_F; 595 mode = MODE_S; 596 tmpline[0] = '\0'; 597 598 /* If logins are disabled, print out the message. */ 599 if ((fp = fopen(_PATH_NOLOGIN, "r")) != NULL) { 600 while (fgets(line, sizeof(line), fp) != NULL) { 601 if ((cp = strchr(line, '\n')) != NULL) 602 *cp = '\0'; 603 lreply(530, "%s", line); 604 } 605 (void) fflush(stdout); 606 (void) fclose(fp); 607 reply(530, "System not available."); 608 exit(0); 609 } 610 if ((fp = fopen(_PATH_FTPWELCOME, "r")) != NULL) { 611 while (fgets(line, sizeof(line), fp) != NULL) { 612 if ((cp = strchr(line, '\n')) != NULL) 613 *cp = '\0'; 614 lreply(220, "%s", line); 615 } 616 (void) fflush(stdout); 617 (void) fclose(fp); 618 /* reply(220,) must follow */ 619 } 620 (void) gethostname(hostname, sizeof(hostname)); 621 622 /* Make sure hostname is fully qualified. */ 623 hp = gethostbyname(hostname); 624 if (hp != NULL) 625 strlcpy(hostname, hp->h_name, sizeof(hostname)); 626 627 if (multihome) { 628 getnameinfo((struct sockaddr *)&ctrl_addr, ctrl_addr.su_len, 629 dhostname, sizeof(dhostname), NULL, 0, 0); 630 } 631 632 reply(220, "%s FTP server (%s) ready.", 633 (multihome ? dhostname : hostname), version); 634 635 monitor_init(); 636 637 for (;;) 638 (void) yyparse(); 639 /* NOTREACHED */ 640} 641 642/* 643 * Signal handlers. 644 */ 645 646static void 647lostconn(int signo) 648{ 649 struct syslog_data sdata = SYSLOG_DATA_INIT; 650 651 if (debug) 652 syslog_r(LOG_DEBUG, &sdata, "lost connection"); 653 dologout(1); 654} 655 656static void 657sigquit(int signo) 658{ 659 struct syslog_data sdata = SYSLOG_DATA_INIT; 660 661 syslog_r(LOG_ERR, &sdata, "got signal %s", sys_signame[signo]); 662 dologout(1); 663} 664 665/* 666 * Save the result of a getpwnam. Used for USER command, since 667 * the data returned must not be clobbered by any other command 668 * (e.g., globbing). 669 */ 670static struct passwd * 671sgetpwnam(char *name, struct passwd *pw) 672{ 673 static struct passwd *save; 674 struct passwd *old; 675 676 if (pw == NULL && (pw = getpwnam(name)) == NULL) 677 return (NULL); 678 old = save; 679 save = pw_dup(pw); 680 if (save == NULL) { 681 perror_reply(421, "Local resource failure: malloc"); 682 dologout(1); 683 /* NOTREACHED */ 684 } 685 if (old) { 686 memset(old->pw_passwd, 0, strlen(old->pw_passwd)); 687 free(old); 688 } 689 return (save); 690} 691 692static int login_attempts; /* number of failed login attempts */ 693static int askpasswd; /* had user command, ask for passwd */ 694static char curname[MAXLOGNAME]; /* current USER name */ 695 696/* 697 * USER command. 698 * Sets global passwd pointer pw if named account exists and is acceptable; 699 * sets askpasswd if a PASS command is expected. If logged in previously, 700 * need to reset state. If name is "ftp" or "anonymous", the name is not in 701 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return. 702 * If account doesn't exist, ask for passwd anyway. Otherwise, check user 703 * requesting login privileges. Disallow anyone who does not have a standard 704 * shell as returned by getusershell(). Disallow anyone mentioned in the file 705 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided. 706 */ 707void 708user(char *name) 709{ 710 char *cp, *shell, *style, *host; 711 char *class = NULL; 712 713 if (logged_in) { 714 kill_slave(); 715 end_login(); 716 } 717 718 /* Close session from previous user if there was one. */ 719 if (as) { 720 auth_close(as); 721 as = NULL; 722 } 723 if (lc) { 724 login_close(lc); 725 lc = NULL; 726 } 727 728 if ((style = strchr(name, ':')) != NULL) 729 *style++ = 0; 730 731 guest = 0; 732 host = multihome ? dhostname : hostname; 733 if (anon_ok && 734 (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0)) { 735 if (checkuser(_PATH_FTPUSERS, "ftp") || 736 checkuser(_PATH_FTPUSERS, "anonymous")) 737 reply(530, "User %s access denied.", name); 738 else if ((pw = sgetpwnam("ftp", NULL)) != NULL) { 739 guest = 1; 740 askpasswd = 1; 741 lc = login_getclass(pw->pw_class); 742 if ((as = auth_open()) == NULL || 743 auth_setpwd(as, pw) != 0 || 744 auth_setoption(as, "FTPD_HOST", host) < 0) { 745 if (as) { 746 auth_close(as); 747 as = NULL; 748 } 749 login_close(lc); 750 lc = NULL; 751 reply(421, "Local resource failure"); 752 return; 753 } 754 reply(331, 755 "Guest login ok, send your email address as password."); 756 } else 757 reply(530, "User %s unknown.", name); 758 if (!askpasswd && logging) 759 syslog(LOG_NOTICE, 760 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost); 761 return; 762 } 763 764 shell = _PATH_BSHELL; 765 if ((pw = sgetpwnam(name, NULL))) { 766 class = pw->pw_class; 767 if (pw->pw_shell != NULL && *pw->pw_shell != '\0') 768 shell = pw->pw_shell; 769 while ((cp = getusershell()) != NULL) 770 if (strcmp(cp, shell) == 0) 771 break; 772 shell = cp; 773 endusershell(); 774 } 775 776 /* Get login class; if invalid style treat like unknown user. */ 777 lc = login_getclass(class); 778 if (lc && (style = login_getstyle(lc, style, "auth-ftp")) == NULL) { 779 login_close(lc); 780 lc = NULL; 781 pw = NULL; 782 } 783 784 /* Do pre-authentication setup. */ 785 if (lc && ((as = auth_open()) == NULL || 786 (pw != NULL && auth_setpwd(as, pw) != 0) || 787 auth_setitem(as, AUTHV_STYLE, style) < 0 || 788 auth_setitem(as, AUTHV_NAME, name) < 0 || 789 auth_setitem(as, AUTHV_CLASS, class) < 0 || 790 auth_setoption(as, "login", "yes") < 0 || 791 auth_setoption(as, "notickets", "yes") < 0 || 792 auth_setoption(as, "FTPD_HOST", host) < 0)) { 793 if (as) { 794 auth_close(as); 795 as = NULL; 796 } 797 login_close(lc); 798 lc = NULL; 799 reply(421, "Local resource failure"); 800 return; 801 } 802 if (logging) 803 strlcpy(curname, name, sizeof(curname)); 804 805 dochroot = (lc && login_getcapbool(lc, "ftp-chroot", 0)) || 806 checkuser(_PATH_FTPCHROOT, name); 807 if (anon_only && !dochroot) { 808 if (anon_ok) 809 reply(530, "Sorry, only anonymous ftp allowed."); 810 else 811 reply(530, "User %s access denied.", name); 812 return; 813 } 814 if (pw) { 815 if ((!shell && !dochroot) || checkuser(_PATH_FTPUSERS, name)) { 816 reply(530, "User %s access denied.", name); 817 if (logging) 818 syslog(LOG_NOTICE, 819 "FTP LOGIN REFUSED FROM %s, %s", 820 remotehost, name); 821 pw = NULL; 822 return; 823 } 824 } 825 826 if (as != NULL && (cp = auth_challenge(as)) != NULL) 827 reply(331, "%s", cp); 828 else 829 reply(331, "Password required for %s.", name); 830 831 askpasswd = 1; 832 /* 833 * Delay before reading passwd after first failed 834 * attempt to slow down passwd-guessing programs. 835 */ 836 if (login_attempts) 837 sleep((unsigned) login_attempts); 838} 839 840/* 841 * Check if a user is in the file "fname" 842 */ 843static int 844checkuser(char *fname, char *name) 845{ 846 FILE *fp; 847 int found = 0; 848 char *p, line[BUFSIZ]; 849 850 if ((fp = fopen(fname, "r")) != NULL) { 851 while (fgets(line, sizeof(line), fp) != NULL) 852 if ((p = strchr(line, '\n')) != NULL) { 853 *p = '\0'; 854 if (line[0] == '#') 855 continue; 856 if (strcmp(line, name) == 0) { 857 found = 1; 858 break; 859 } 860 } 861 (void) fclose(fp); 862 } 863 return (found); 864} 865 866/* 867 * Terminate login as previous user, if any, resetting state; 868 * used when USER command is given or login fails. 869 */ 870static void 871end_login(void) 872{ 873 sigprocmask (SIG_BLOCK, &allsigs, NULL); 874 if (logged_in) { 875 ftpdlogwtmp(ttyline, "", ""); 876 if (doutmp) 877 ftpd_logout(utmp.ut_line); 878 } 879 reply(530, "Please reconnect to work as another user"); 880 _exit(0); 881} 882 883enum auth_ret 884pass(char *passwd) 885{ 886 int authok, flags; 887 FILE *fp; 888 static char homedir[MAXPATHLEN]; 889 char *motd, *dir, rootdir[MAXPATHLEN]; 890 size_t sz_pw_dir; 891 892 if (logged_in || askpasswd == 0) { 893 reply(503, "Login with USER first."); 894 return (AUTH_FAILED); 895 } 896 askpasswd = 0; 897 if (!guest) { /* "ftp" is only account allowed no password */ 898 authok = 0; 899 if (pw == NULL || pw->pw_passwd[0] == '\0') { 900 useconds_t us; 901 902 /* Sleep between 1 and 3 seconds to emulate a crypt. */ 903 us = arc4random() % 3000000; 904 usleep(us); 905 if (as != NULL) { 906 auth_close(as); 907 as = NULL; 908 } 909 } else { 910 authok = auth_userresponse(as, passwd, 0); 911 as = NULL; 912 } 913 if (authok == 0) { 914 reply(530, "Login incorrect."); 915 if (logging) 916 syslog(LOG_NOTICE, 917 "FTP LOGIN FAILED FROM %s, %s", 918 remotehost, curname); 919 pw = NULL; 920 if (login_attempts++ >= 5) { 921 syslog(LOG_NOTICE, 922 "repeated login failures from %s", 923 remotehost); 924 kill_slave(); 925 _exit(0); 926 } 927 return (AUTH_FAILED); 928 } 929 } else if (lc != NULL) { 930 /* Save anonymous' password. */ 931 if (guestpw != NULL) 932 free(guestpw); 933 guestpw = strdup(passwd); 934 if (guestpw == NULL) { 935 kill_slave(); 936 fatal("Out of memory."); 937 } 938 939 authok = auth_approval(as, lc, pw->pw_name, "ftp"); 940 auth_close(as); 941 as = NULL; 942 if (authok == 0) { 943 syslog(LOG_INFO|LOG_AUTH, 944 "FTP LOGIN FAILED (HOST) as %s: approval failure.", 945 pw->pw_name); 946 reply(530, "Approval failure."); 947 kill_slave(); 948 _exit(0); 949 } 950 } else { 951 syslog(LOG_INFO|LOG_AUTH, 952 "FTP LOGIN CLASS %s MISSING for %s: approval failure.", 953 pw->pw_class, pw->pw_name); 954 reply(530, "Permission denied."); 955 kill_slave(); 956 _exit(0); 957 } 958 959 if (monitor_post_auth() == 1) { 960 /* Post-auth monitor process */ 961 logged_in = 1; 962 return (AUTH_MONITOR); 963 } 964 965 login_attempts = 0; /* this time successful */ 966 /* set umask via setusercontext() unless -u flag was given. */ 967 flags = LOGIN_SETGROUP|LOGIN_SETPRIORITY|LOGIN_SETRESOURCES; 968 if (umaskchange) 969 flags |= LOGIN_SETUMASK; 970 else 971 (void) umask(defumask); 972 if (setusercontext(lc, pw, (uid_t)0, flags) != 0) { 973 perror_reply(451, "Local resource failure: setusercontext"); 974 syslog(LOG_NOTICE, "setusercontext: %m"); 975 dologout(1); 976 /* NOTREACHED */ 977 } 978 979 /* open wtmp before chroot */ 980 ftpdlogwtmp(ttyline, pw->pw_name, remotehost); 981 982 /* open utmp before chroot */ 983 if (doutmp) { 984 memset((void *)&utmp, 0, sizeof(utmp)); 985 (void)time(&utmp.ut_time); 986 (void)strncpy(utmp.ut_name, pw->pw_name, sizeof(utmp.ut_name)); 987 (void)strncpy(utmp.ut_host, remotehost, sizeof(utmp.ut_host)); 988 (void)strncpy(utmp.ut_line, ttyline, sizeof(utmp.ut_line)); 989 ftpd_login(&utmp); 990 } 991 992 /* open stats file before chroot */ 993 if (guest && (stats == 1) && (statfd < 0)) 994 if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0) 995 stats = 0; 996 997 logged_in = 1; 998 999 if ((dir = login_getcapstr(lc, "ftp-dir", NULL, NULL))) { 1000 char *newdir; 1001 1002 newdir = copy_dir(dir, pw); 1003 if (newdir == NULL) { 1004 perror_reply(421, "Local resource failure: malloc"); 1005 dologout(1); 1006 /* NOTREACHED */ 1007 } 1008 pw->pw_dir = newdir; 1009 pw = sgetpwnam(NULL, pw); 1010 free(dir); 1011 free(newdir); 1012 } 1013 1014 /* make sure pw->pw_dir is big enough to hold "/" */ 1015 sz_pw_dir = strlen(pw->pw_dir) + 1; 1016 if (sz_pw_dir < 2) { 1017 pw->pw_dir = "/"; 1018 pw = sgetpwnam(NULL, pw); 1019 sz_pw_dir = 2; 1020 } 1021 1022 if (guest || dochroot) { 1023 if (multihome && guest) { 1024 struct stat ts; 1025 1026 /* Compute root directory. */ 1027 snprintf(rootdir, sizeof(rootdir), "%s/%s", 1028 pw->pw_dir, dhostname); 1029 if (stat(rootdir, &ts) < 0) { 1030 snprintf(rootdir, sizeof(rootdir), "%s/%s", 1031 pw->pw_dir, hostname); 1032 } 1033 } else 1034 strlcpy(rootdir, pw->pw_dir, sizeof(rootdir)); 1035 } 1036 if (guest) { 1037 /* 1038 * We MUST do a chdir() after the chroot. Otherwise 1039 * the old current directory will be accessible as "." 1040 * outside the new root! 1041 */ 1042 if (chroot(rootdir) < 0 || chdir("/") < 0) { 1043 reply(550, "Can't set guest privileges."); 1044 goto bad; 1045 } 1046 strlcpy(pw->pw_dir, "/", sz_pw_dir); 1047 if (setenv("HOME", "/", 1) == -1) { 1048 reply(550, "Can't setup environment."); 1049 goto bad; 1050 } 1051 } else if (dochroot) { 1052 if (chroot(rootdir) < 0 || chdir("/") < 0) { 1053 reply(550, "Can't change root."); 1054 goto bad; 1055 } 1056 strlcpy(pw->pw_dir, "/", sz_pw_dir); 1057 if (setenv("HOME", "/", 1) == -1) { 1058 reply(550, "Can't setup environment."); 1059 goto bad; 1060 } 1061 } else if (chdir(pw->pw_dir) < 0) { 1062 if (chdir("/") < 0) { 1063 reply(530, "User %s: can't change directory to %s.", 1064 pw->pw_name, pw->pw_dir); 1065 goto bad; 1066 } else 1067 lreply(230, "No directory! Logging in with home=/"); 1068 } 1069 if (setegid(pw->pw_gid) < 0 || setgid(pw->pw_gid) < 0) { 1070 reply(550, "Can't set gid."); 1071 goto bad; 1072 } 1073 if (seteuid(pw->pw_uid) < 0 || setuid(pw->pw_uid) < 0) { 1074 reply(550, "Can't set uid."); 1075 goto bad; 1076 } 1077 sigprocmask(SIG_UNBLOCK, &allsigs, NULL); 1078 1079 /* 1080 * Set home directory so that use of ~ (tilde) works correctly. 1081 */ 1082 if (getcwd(homedir, MAXPATHLEN) != NULL) { 1083 if (setenv("HOME", homedir, 1) == -1) { 1084 reply(550, "Can't setup environment."); 1085 goto bad; 1086 } 1087 } 1088 1089 /* 1090 * Display a login message, if it exists. 1091 * N.B. reply(230,) must follow the message. 1092 */ 1093 motd = login_getcapstr(lc, "welcome", NULL, NULL); 1094 if ((fp = fopen(motd ? motd : _PATH_FTPLOGINMESG, "r")) != NULL) { 1095 char *cp, line[LINE_MAX]; 1096 1097 while (fgets(line, sizeof(line), fp) != NULL) { 1098 if ((cp = strchr(line, '\n')) != NULL) 1099 *cp = '\0'; 1100 lreply(230, "%s", line); 1101 } 1102 (void) fflush(stdout); 1103 (void) fclose(fp); 1104 } 1105 if (motd != NULL) 1106 free(motd); 1107 if (guest) { 1108 if (ident != NULL) 1109 free(ident); 1110 ident = strdup(passwd); 1111 if (ident == NULL) 1112 fatal("Ran out of memory."); 1113 reply(230, "Guest login ok, access restrictions apply."); 1114#ifdef HASSETPROCTITLE 1115 snprintf(proctitle, sizeof(proctitle), 1116 "%s: anonymous/%.*s", remotehost, 1117 (int)(sizeof(proctitle) - sizeof(remotehost) - 1118 sizeof(": anonymous/")), passwd); 1119 setproctitle("%s", proctitle); 1120#endif /* HASSETPROCTITLE */ 1121 if (logging) 1122 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s", 1123 remotehost, passwd); 1124 } else { 1125 reply(230, "User %s logged in.", pw->pw_name); 1126#ifdef HASSETPROCTITLE 1127 snprintf(proctitle, sizeof(proctitle), 1128 "%s: %s", remotehost, pw->pw_name); 1129 setproctitle("%s", proctitle); 1130#endif /* HASSETPROCTITLE */ 1131 if (logging) 1132 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s", 1133 remotehost, pw->pw_name); 1134 } 1135 login_close(lc); 1136 lc = NULL; 1137 return (AUTH_SLAVE); 1138bad: 1139 /* Forget all about it... */ 1140 login_close(lc); 1141 lc = NULL; 1142 end_login(); 1143 return (AUTH_FAILED); 1144} 1145 1146void 1147retrieve(char *cmd, char *name) 1148{ 1149 FILE *fin, *dout; 1150 struct stat st; 1151 int (*closefunc)(FILE *); 1152 time_t start; 1153 1154 if (cmd == 0) { 1155 fin = fopen(name, "r"), closefunc = fclose; 1156 st.st_size = 0; 1157 } else { 1158 char line[BUFSIZ]; 1159 1160 (void) snprintf(line, sizeof(line), cmd, name); 1161 name = line; 1162 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose; 1163 st.st_size = -1; 1164 st.st_blksize = BUFSIZ; 1165 } 1166 if (fin == NULL) { 1167 if (errno != 0) { 1168 perror_reply(550, name); 1169 if (cmd == 0) { 1170 LOGCMD("get", name); 1171 } 1172 } 1173 return; 1174 } 1175 byte_count = -1; 1176 if (cmd == 0 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) { 1177 reply(550, "%s: not a plain file.", name); 1178 goto done; 1179 } 1180 if (restart_point) { 1181 if (type == TYPE_A) { 1182 off_t i, n; 1183 int c; 1184 1185 n = restart_point; 1186 i = 0; 1187 while (i++ < n) { 1188 if ((c=getc(fin)) == EOF) { 1189 perror_reply(550, name); 1190 goto done; 1191 } 1192 if (c == '\n') 1193 i++; 1194 } 1195 } else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) { 1196 perror_reply(550, name); 1197 goto done; 1198 } 1199 } 1200 dout = dataconn(name, st.st_size, "w"); 1201 if (dout == NULL) 1202 goto done; 1203 time(&start); 1204 send_data(fin, dout, st.st_blksize, st.st_size, 1205 (restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode))); 1206 if ((cmd == 0) && stats) 1207 logxfer(name, byte_count, start); 1208 (void) fclose(dout); 1209 data = -1; 1210done: 1211 if (pdata >= 0) 1212 (void) close(pdata); 1213 pdata = -1; 1214 if (cmd == 0) 1215 LOGBYTES("get", name, byte_count); 1216 (*closefunc)(fin); 1217} 1218 1219void 1220store(char *name, char *mode, int unique) 1221{ 1222 FILE *fout, *din; 1223 int (*closefunc)(FILE *); 1224 struct stat st; 1225 int fd; 1226 1227 if (restart_point && *mode != 'a') 1228 mode = "r+"; 1229 1230 if (unique && stat(name, &st) == 0) { 1231 char *nam; 1232 1233 fd = guniquefd(name, &nam); 1234 if (fd == -1) { 1235 LOGCMD(*mode == 'w' ? "put" : "append", name); 1236 return; 1237 } 1238 name = nam; 1239 fout = fdopen(fd, mode); 1240 } else 1241 fout = fopen(name, mode); 1242 1243 closefunc = fclose; 1244 if (fout == NULL) { 1245 perror_reply(553, name); 1246 LOGCMD(*mode == 'w' ? "put" : "append", name); 1247 return; 1248 } 1249 byte_count = -1; 1250 if (restart_point) { 1251 if (type == TYPE_A) { 1252 off_t i, n; 1253 int c; 1254 1255 n = restart_point; 1256 i = 0; 1257 while (i++ < n) { 1258 if ((c=getc(fout)) == EOF) { 1259 perror_reply(550, name); 1260 goto done; 1261 } 1262 if (c == '\n') 1263 i++; 1264 } 1265 /* 1266 * We must do this seek to "current" position 1267 * because we are changing from reading to 1268 * writing. 1269 */ 1270 if (fseek(fout, 0L, SEEK_CUR) < 0) { 1271 perror_reply(550, name); 1272 goto done; 1273 } 1274 } else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) { 1275 perror_reply(550, name); 1276 goto done; 1277 } 1278 } 1279 din = dataconn(name, (off_t)-1, "r"); 1280 if (din == NULL) 1281 goto done; 1282 if (receive_data(din, fout) == 0) { 1283 if (unique) 1284 reply(226, "Transfer complete (unique file name:%s).", 1285 name); 1286 else 1287 reply(226, "Transfer complete."); 1288 } 1289 (void) fclose(din); 1290 data = -1; 1291 pdata = -1; 1292done: 1293 LOGBYTES(*mode == 'w' ? "put" : "append", name, byte_count); 1294 (*closefunc)(fout); 1295} 1296 1297static FILE * 1298getdatasock(char *mode) 1299{ 1300 int on = 1, s, t, tries; 1301 1302 if (data >= 0) 1303 return (fdopen(data, mode)); 1304 sigprocmask (SIG_BLOCK, &allsigs, NULL); 1305 s = socket(ctrl_addr.su_family, SOCK_STREAM, 0); 1306 if (s < 0) 1307 goto bad; 1308 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, 1309 (char *) &on, sizeof(on)) < 0) 1310 goto bad; 1311 /* anchor socket to avoid multi-homing problems */ 1312 data_source = ctrl_addr; 1313 data_source.su_port = htons(20); /* ftp-data port */ 1314 for (tries = 1; ; tries++) { 1315 if (monitor_bind(s, (struct sockaddr *)&data_source, 1316 data_source.su_len) >= 0) 1317 break; 1318 if (errno != EADDRINUSE || tries > 10) 1319 goto bad; 1320 sleep(tries); 1321 } 1322 sigprocmask (SIG_UNBLOCK, &allsigs, NULL); 1323 1324#ifdef IP_TOS 1325 if (ctrl_addr.su_family == AF_INET) { 1326 on = IPTOS_THROUGHPUT; 1327 if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on, 1328 sizeof(int)) < 0) 1329 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m"); 1330 } 1331#endif 1332#ifdef TCP_NOPUSH 1333 /* 1334 * Turn off push flag to keep sender TCP from sending short packets 1335 * at the boundaries of each write(). Should probably do a SO_SNDBUF 1336 * to set the send buffer size as well, but that may not be desirable 1337 * in heavy-load situations. 1338 */ 1339 on = 1; 1340 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, (char *)&on, sizeof(on)) < 0) 1341 syslog(LOG_WARNING, "setsockopt (TCP_NOPUSH): %m"); 1342#endif 1343#ifdef SO_SNDBUF 1344 on = 65536; 1345 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&on, sizeof(on)) < 0) 1346 syslog(LOG_WARNING, "setsockopt (SO_SNDBUF): %m"); 1347#endif 1348 1349 return (fdopen(s, mode)); 1350bad: 1351 /* Return the real value of errno (close may change it) */ 1352 t = errno; 1353 sigprocmask (SIG_UNBLOCK, &allsigs, NULL); 1354 if (s >= 0) 1355 (void) close(s); 1356 errno = t; 1357 return (NULL); 1358} 1359 1360static FILE * 1361dataconn(char *name, off_t size, char *mode) 1362{ 1363 char sizebuf[32]; 1364 FILE *file; 1365 int retry = 0; 1366 in_port_t *p; 1367 u_char *fa, *ha; 1368 int alen; 1369 1370 file_size = size; 1371 byte_count = 0; 1372 if (size != (off_t) -1) { 1373 (void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)", 1374 size); 1375 } else 1376 sizebuf[0] = '\0'; 1377 if (pdata >= 0) { 1378 union sockunion from; 1379 int s; 1380 socklen_t fromlen = sizeof(from); 1381 1382 (void) alarm ((unsigned) timeout); 1383 s = accept(pdata, (struct sockaddr *)&from, &fromlen); 1384 (void) alarm (0); 1385 if (s < 0) { 1386 reply(425, "Can't open data connection."); 1387 (void) close(pdata); 1388 pdata = -1; 1389 return (NULL); 1390 } 1391 switch (from.su_family) { 1392 case AF_INET: 1393 p = (in_port_t *)&from.su_sin.sin_port; 1394 fa = (u_char *)&from.su_sin.sin_addr; 1395 ha = (u_char *)&his_addr.su_sin.sin_addr; 1396 alen = sizeof(struct in_addr); 1397 break; 1398 case AF_INET6: 1399 p = (in_port_t *)&from.su_sin6.sin6_port; 1400 fa = (u_char *)&from.su_sin6.sin6_addr; 1401 ha = (u_char *)&his_addr.su_sin6.sin6_addr; 1402 alen = sizeof(struct in6_addr); 1403 break; 1404 default: 1405 perror_reply(425, "Can't build data connection"); 1406 (void) close(pdata); 1407 (void) close(s); 1408 pdata = -1; 1409 return (NULL); 1410 } 1411 if (from.su_family != his_addr.su_family || 1412 ntohs(*p) < IPPORT_RESERVED) { 1413 perror_reply(425, "Can't build data connection"); 1414 (void) close(pdata); 1415 (void) close(s); 1416 pdata = -1; 1417 return (NULL); 1418 } 1419 if (portcheck && memcmp(fa, ha, alen) != 0) { 1420 perror_reply(435, "Can't build data connection"); 1421 (void) close(pdata); 1422 (void) close(s); 1423 pdata = -1; 1424 return (NULL); 1425 } 1426 (void) close(pdata); 1427 pdata = s; 1428 reply(150, "Opening %s mode data connection for '%s'%s.", 1429 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf); 1430 return (fdopen(pdata, mode)); 1431 } 1432 if (data >= 0) { 1433 reply(125, "Using existing data connection for '%s'%s.", 1434 name, sizebuf); 1435 usedefault = 1; 1436 return (fdopen(data, mode)); 1437 } 1438 if (usedefault) 1439 data_dest = his_addr; 1440 usedefault = 1; 1441 do { 1442 file = getdatasock(mode); 1443 if (file == NULL) { 1444 char hbuf[MAXHOSTNAMELEN], pbuf[10]; 1445 1446 getnameinfo((struct sockaddr *)&data_source, 1447 data_source.su_len, hbuf, sizeof(hbuf), pbuf, 1448 sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV); 1449 reply(425, "Can't create data socket (%s,%s): %s.", 1450 hbuf, pbuf, strerror(errno)); 1451 return (NULL); 1452 } 1453 1454 /* 1455 * attempt to connect to reserved port on client machine; 1456 * this looks like an attack 1457 */ 1458 switch (data_dest.su_family) { 1459 case AF_INET: 1460 p = (in_port_t *)&data_dest.su_sin.sin_port; 1461 fa = (u_char *)&data_dest.su_sin.sin_addr; 1462 ha = (u_char *)&his_addr.su_sin.sin_addr; 1463 alen = sizeof(struct in_addr); 1464 break; 1465 case AF_INET6: 1466 p = (in_port_t *)&data_dest.su_sin6.sin6_port; 1467 fa = (u_char *)&data_dest.su_sin6.sin6_addr; 1468 ha = (u_char *)&his_addr.su_sin6.sin6_addr; 1469 alen = sizeof(struct in6_addr); 1470 break; 1471 default: 1472 perror_reply(425, "Can't build data connection"); 1473 (void) fclose(file); 1474 pdata = -1; 1475 return (NULL); 1476 } 1477 if (data_dest.su_family != his_addr.su_family || 1478 ntohs(*p) < IPPORT_RESERVED || ntohs(*p) == 2049) { /* XXX */ 1479 perror_reply(425, "Can't build data connection"); 1480 (void) fclose(file); 1481 return NULL; 1482 } 1483 if (portcheck && memcmp(fa, ha, alen) != 0) { 1484 perror_reply(435, "Can't build data connection"); 1485 (void) fclose(file); 1486 return NULL; 1487 } 1488 1489 if (connect(fileno(file), (struct sockaddr *)&data_dest, 1490 data_dest.su_len) == 0) { 1491 reply(150, "Opening %s mode data connection for '%s'%s.", 1492 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf); 1493 data = fileno(file); 1494 return (file); 1495 } 1496 if (errno != EADDRINUSE) 1497 break; 1498 (void) fclose(file); 1499 sleep((unsigned) swaitint); 1500 retry += swaitint; 1501 } while (retry <= swaitmax); 1502 perror_reply(425, "Can't build data connection"); 1503 (void) fclose(file); 1504 return (NULL); 1505} 1506 1507/* 1508 * Tranfer the contents of "instr" to "outstr" peer using the appropriate 1509 * encapsulation of the data subject to Mode, Structure, and Type. 1510 * 1511 * NB: Form isn't handled. 1512 */ 1513static int 1514send_data(FILE *instr, FILE *outstr, off_t blksize, off_t filesize, int isreg) 1515{ 1516 int c, cnt, filefd, netfd; 1517 char *buf, *bp; 1518 size_t len; 1519 1520 transflag++; 1521 switch (type) { 1522 1523 case TYPE_A: 1524 while ((c = getc(instr)) != EOF) { 1525 if (recvurg) 1526 goto got_oob; 1527 byte_count++; 1528 if (c == '\n') { 1529 if (ferror(outstr)) 1530 goto data_err; 1531 (void) putc('\r', outstr); 1532 } 1533 (void) putc(c, outstr); 1534 } 1535 fflush(outstr); 1536 transflag = 0; 1537 if (ferror(instr)) 1538 goto file_err; 1539 if (ferror(outstr)) 1540 goto data_err; 1541 reply(226, "Transfer complete."); 1542 return(0); 1543 1544 case TYPE_I: 1545 case TYPE_L: 1546 /* 1547 * isreg is only set if we are not doing restart and we 1548 * are sending a regular file 1549 */ 1550 netfd = fileno(outstr); 1551 filefd = fileno(instr); 1552 1553 if (isreg && filesize < (off_t)16 * 1024 * 1024) { 1554 buf = mmap(0, filesize, PROT_READ, MAP_SHARED, filefd, 1555 (off_t)0); 1556 if (buf == MAP_FAILED) { 1557 syslog(LOG_WARNING, "mmap(%lu): %m", 1558 (unsigned long)filesize); 1559 goto oldway; 1560 } 1561 bp = buf; 1562 len = filesize; 1563 do { 1564 cnt = write(netfd, bp, len); 1565 if (recvurg) { 1566 munmap(buf, (size_t)filesize); 1567 goto got_oob; 1568 } 1569 len -= cnt; 1570 bp += cnt; 1571 if (cnt > 0) 1572 byte_count += cnt; 1573 } while(cnt > 0 && len > 0); 1574 1575 transflag = 0; 1576 munmap(buf, (size_t)filesize); 1577 if (cnt < 0) 1578 goto data_err; 1579 reply(226, "Transfer complete."); 1580 return(0); 1581 } 1582 1583oldway: 1584 if ((buf = malloc((u_int)blksize)) == NULL) { 1585 transflag = 0; 1586 perror_reply(451, "Local resource failure: malloc"); 1587 return(-1); 1588 } 1589 1590 while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 && 1591 write(netfd, buf, cnt) == cnt) 1592 byte_count += cnt; 1593 transflag = 0; 1594 (void)free(buf); 1595 if (cnt != 0) { 1596 if (cnt < 0) 1597 goto file_err; 1598 goto data_err; 1599 } 1600 reply(226, "Transfer complete."); 1601 return(0); 1602 default: 1603 transflag = 0; 1604 reply(550, "Unimplemented TYPE %d in send_data", type); 1605 return(-1); 1606 } 1607 1608data_err: 1609 transflag = 0; 1610 perror_reply(426, "Data connection"); 1611 return(-1); 1612 1613file_err: 1614 transflag = 0; 1615 perror_reply(551, "Error on input file"); 1616 return(-1); 1617 1618got_oob: 1619 myoob(); 1620 recvurg = 0; 1621 transflag = 0; 1622 return(-1); 1623} 1624 1625/* 1626 * Transfer data from peer to "outstr" using the appropriate encapulation of 1627 * the data subject to Mode, Structure, and Type. 1628 * 1629 * N.B.: Form isn't handled. 1630 */ 1631static int 1632receive_data(FILE *instr, FILE *outstr) 1633{ 1634 int c; 1635 int cnt; 1636 char buf[BUFSIZ]; 1637 struct sigaction sa, sa_saved; 1638 volatile int bare_lfs = 0; 1639 1640 transflag++; 1641 switch (type) { 1642 1643 case TYPE_I: 1644 case TYPE_L: 1645 memset(&sa, 0, sizeof(sa)); 1646 sigfillset(&sa.sa_mask); 1647 sa.sa_flags = SA_RESTART; 1648 sa.sa_handler = lostconn; 1649 (void) sigaction(SIGALRM, &sa, &sa_saved); 1650 do { 1651 (void) alarm ((unsigned) timeout); 1652 cnt = read(fileno(instr), buf, sizeof(buf)); 1653 (void) alarm (0); 1654 if (recvurg) 1655 goto got_oob; 1656 1657 if (cnt > 0) { 1658 if (write(fileno(outstr), buf, cnt) != cnt) 1659 goto file_err; 1660 byte_count += cnt; 1661 } 1662 } while (cnt > 0); 1663 (void) sigaction(SIGALRM, &sa_saved, NULL); 1664 if (cnt < 0) 1665 goto data_err; 1666 transflag = 0; 1667 return (0); 1668 1669 case TYPE_E: 1670 reply(553, "TYPE E not implemented."); 1671 transflag = 0; 1672 return (-1); 1673 1674 case TYPE_A: 1675 while ((c = getc(instr)) != EOF) { 1676 if (recvurg) 1677 goto got_oob; 1678 byte_count++; 1679 if (c == '\n') 1680 bare_lfs++; 1681 while (c == '\r') { 1682 if (ferror(outstr)) 1683 goto data_err; 1684 if ((c = getc(instr)) != '\n') { 1685 (void) putc ('\r', outstr); 1686 if (c == '\0' || c == EOF) 1687 goto contin2; 1688 } 1689 } 1690 (void) putc(c, outstr); 1691 contin2: ; 1692 } 1693 fflush(outstr); 1694 if (ferror(instr)) 1695 goto data_err; 1696 if (ferror(outstr)) 1697 goto file_err; 1698 transflag = 0; 1699 if (bare_lfs) { 1700 lreply(226, 1701 "WARNING! %d bare linefeeds received in ASCII mode", 1702 bare_lfs); 1703 printf(" File may not have transferred correctly.\r\n"); 1704 } 1705 return (0); 1706 default: 1707 reply(550, "Unimplemented TYPE %d in receive_data", type); 1708 transflag = 0; 1709 return (-1); 1710 } 1711 1712data_err: 1713 transflag = 0; 1714 perror_reply(426, "Data Connection"); 1715 return (-1); 1716 1717file_err: 1718 transflag = 0; 1719 perror_reply(452, "Error writing file"); 1720 return (-1); 1721 1722got_oob: 1723 myoob(); 1724 recvurg = 0; 1725 transflag = 0; 1726 return (-1); 1727} 1728 1729void 1730statfilecmd(char *filename) 1731{ 1732 FILE *fin; 1733 int c; 1734 int atstart; 1735 char line[LINE_MAX]; 1736 1737 (void)snprintf(line, sizeof(line), "/bin/ls -lgA %s", filename); 1738 fin = ftpd_popen(line, "r"); 1739 lreply(211, "status of %s:", filename); 1740 atstart = 1; 1741 while ((c = getc(fin)) != EOF) { 1742 if (c == '\n') { 1743 if (ferror(stdout)){ 1744 perror_reply(421, "control connection"); 1745 (void) ftpd_pclose(fin); 1746 dologout(1); 1747 /* NOTREACHED */ 1748 } 1749 if (ferror(fin)) { 1750 perror_reply(551, filename); 1751 (void) ftpd_pclose(fin); 1752 return; 1753 } 1754 (void) putc('\r', stdout); 1755 } 1756 if (atstart && isdigit(c)) 1757 (void) putc(' ', stdout); 1758 (void) putc(c, stdout); 1759 atstart = (c == '\n'); 1760 } 1761 (void) ftpd_pclose(fin); 1762 reply(211, "End of Status"); 1763} 1764 1765void 1766statcmd(void) 1767{ 1768 union sockunion *su; 1769 u_char *a, *p; 1770 char hbuf[MAXHOSTNAMELEN]; 1771 int ispassive; 1772 1773 lreply(211, "%s FTP server status:", hostname); 1774 printf(" %s\r\n", version); 1775 getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len, 1776 hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST); 1777 printf(" Connected to %s", remotehost); 1778 if (strcmp(remotehost, hbuf) != 0) 1779 printf(" (%s)", hbuf); 1780 printf("\r\n"); 1781 if (logged_in) { 1782 if (guest) 1783 printf(" Logged in anonymously\r\n"); 1784 else 1785 printf(" Logged in as %s\r\n", pw->pw_name); 1786 } else if (askpasswd) 1787 printf(" Waiting for password\r\n"); 1788 else 1789 printf(" Waiting for user name\r\n"); 1790 printf(" TYPE: %s", typenames[type]); 1791 if (type == TYPE_A || type == TYPE_E) 1792 printf(", FORM: %s", formnames[form]); 1793 if (type == TYPE_L) 1794#if NBBY == 8 1795 printf(" %d", NBBY); 1796#else 1797 printf(" %d", bytesize); /* need definition! */ 1798#endif 1799 printf("; STRUcture: %s; transfer MODE: %s\r\n", 1800 strunames[stru], modenames[mode]); 1801 ispassive = 0; 1802 if (data != -1) 1803 printf(" Data connection open\r\n"); 1804 else if (pdata != -1) { 1805 printf(" in Passive mode\r\n"); 1806 su = (union sockunion *)&pasv_addr; 1807 ispassive++; 1808 goto printaddr; 1809 } else if (usedefault == 0) { 1810 su = (union sockunion *)&data_dest; 1811printaddr: 1812 /* PASV/PORT */ 1813 if (su->su_family == AF_INET) { 1814 if (ispassive) 1815 printf("211- PASV "); 1816 else 1817 printf("211- PORT "); 1818 a = (u_char *) &su->su_sin.sin_addr; 1819 p = (u_char *) &su->su_sin.sin_port; 1820 printf("(%u,%u,%u,%u,%u,%u)\r\n", 1821 a[0], a[1], a[2], a[3], 1822 p[0], p[1]); 1823 } 1824 1825 /* LPSV/LPRT */ 1826 { 1827 int alen, af, i; 1828 1829 alen = 0; 1830 switch (su->su_family) { 1831 case AF_INET: 1832 a = (u_char *) &su->su_sin.sin_addr; 1833 p = (u_char *) &su->su_sin.sin_port; 1834 alen = sizeof(su->su_sin.sin_addr); 1835 af = 4; 1836 break; 1837 case AF_INET6: 1838 a = (u_char *) &su->su_sin6.sin6_addr; 1839 p = (u_char *) &su->su_sin6.sin6_port; 1840 alen = sizeof(su->su_sin6.sin6_addr); 1841 af = 6; 1842 break; 1843 default: 1844 af = 0; 1845 break; 1846 } 1847 if (af) { 1848 if (ispassive) 1849 printf("211- LPSV "); 1850 else 1851 printf("211- LPRT "); 1852 printf("(%u,%u", af, alen); 1853 for (i = 0; i < alen; i++) 1854 printf(",%u", a[i]); 1855 printf(",%u,%u,%u)\r\n", 2, p[0], p[1]); 1856 } 1857 } 1858 1859 /* EPRT/EPSV */ 1860 { 1861 u_char af; 1862 1863 switch (su->su_family) { 1864 case AF_INET: 1865 af = 1; 1866 break; 1867 case AF_INET6: 1868 af = 2; 1869 break; 1870 default: 1871 af = 0; 1872 break; 1873 } 1874 if (af) { 1875 char hbuf[MAXHOSTNAMELEN], pbuf[10]; 1876 union sockunion tmp = *su; 1877 1878 if (tmp.su_family == AF_INET6) 1879 tmp.su_sin6.sin6_scope_id = 0; 1880 if (getnameinfo((struct sockaddr *)&tmp, tmp.su_len, 1881 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), 1882 NI_NUMERICHOST | NI_NUMERICSERV) == 0) { 1883 if (ispassive) 1884 printf("211- EPSV "); 1885 else 1886 printf("211- EPRT "); 1887 printf("(|%u|%s|%s|)\r\n", 1888 af, hbuf, pbuf); 1889 } 1890 } 1891 } 1892 } else 1893 printf(" No data connection\r\n"); 1894 reply(211, "End of status"); 1895} 1896 1897void 1898fatal(char *s) 1899{ 1900 1901 reply(451, "Error in server: %s", s); 1902 reply(221, "Closing connection due to server error."); 1903 dologout(0); 1904 /* NOTREACHED */ 1905} 1906 1907void 1908reply(int n, const char *fmt, ...) 1909{ 1910 char *buf, *p, *next; 1911 int rval; 1912 va_list ap; 1913 1914 va_start(ap, fmt); 1915 rval = vasprintf(&buf, fmt, ap); 1916 va_end(ap); 1917 if (rval == -1 || buf == NULL) { 1918 printf("412 Local resource failure: malloc\r\n"); 1919 fflush(stdout); 1920 dologout(1); 1921 } 1922 next = buf; 1923 while ((p = strsep(&next, "\n\r"))) { 1924 printf("%d%s %s\r\n", n, (next != '\0') ? "-" : "", p); 1925 if (debug) 1926 syslog(LOG_DEBUG, "<--- %d%s %s", n, 1927 (next != '\0') ? "-" : "", p); 1928 } 1929 (void)fflush(stdout); 1930 free(buf); 1931} 1932 1933 1934void 1935reply_r(int n, const char *fmt, ...) 1936{ 1937 char *p, *next; 1938 char msg[BUFSIZ]; 1939 char buf[BUFSIZ]; 1940 va_list ap; 1941 struct syslog_data sdata = SYSLOG_DATA_INIT; 1942 1943 va_start(ap, fmt); 1944 vsnprintf(msg, sizeof(msg), fmt, ap); 1945 va_end(ap); 1946 1947 next = msg; 1948 1949 while ((p = strsep(&next, "\n\r"))) { 1950 snprintf(buf, sizeof(buf), "%d%s %s\r\n", n, 1951 (next != '\0') ? "-" : "", p); 1952 write(STDOUT_FILENO, buf, strlen(buf)); 1953 if (debug) { 1954 buf[strlen(buf) - 2] = '\0'; 1955 syslog_r(LOG_DEBUG, &sdata, "<--- %s", buf); 1956 } 1957 } 1958} 1959 1960void 1961lreply(int n, const char *fmt, ...) 1962{ 1963 va_list ap; 1964 1965 va_start(ap, fmt); 1966 (void)printf("%d- ", n); 1967 (void)vprintf(fmt, ap); 1968 va_end(ap); 1969 (void)printf("\r\n"); 1970 (void)fflush(stdout); 1971 if (debug) { 1972 va_start(ap, fmt); 1973 syslog(LOG_DEBUG, "<--- %d- ", n); 1974 vsyslog(LOG_DEBUG, fmt, ap); 1975 va_end(ap); 1976 } 1977} 1978 1979static void 1980ack(char *s) 1981{ 1982 1983 reply(250, "%s command successful.", s); 1984} 1985 1986void 1987nack(char *s) 1988{ 1989 1990 reply(502, "%s command not implemented.", s); 1991} 1992 1993/* ARGSUSED */ 1994void 1995yyerror(char *s) 1996{ 1997 char *cp; 1998 1999 if ((cp = strchr(cbuf,'\n'))) 2000 *cp = '\0'; 2001 reply(500, "'%s': command not understood.", cbuf); 2002} 2003 2004void 2005delete(char *name) 2006{ 2007 struct stat st; 2008 2009 LOGCMD("delete", name); 2010 if (stat(name, &st) < 0) { 2011 perror_reply(550, name); 2012 return; 2013 } 2014 if ((st.st_mode&S_IFMT) == S_IFDIR) { 2015 if (rmdir(name) < 0) { 2016 perror_reply(550, name); 2017 return; 2018 } 2019 goto done; 2020 } 2021 if (unlink(name) < 0) { 2022 perror_reply(550, name); 2023 return; 2024 } 2025done: 2026 ack("DELE"); 2027} 2028 2029void 2030cwd(char *path) 2031{ 2032 FILE *message; 2033 2034 if (chdir(path) < 0) 2035 perror_reply(550, path); 2036 else { 2037 if ((message = fopen(_PATH_CWDMESG, "r")) != NULL) { 2038 char *cp, line[LINE_MAX]; 2039 2040 while (fgets(line, sizeof(line), message) != NULL) { 2041 if ((cp = strchr(line, '\n')) != NULL) 2042 *cp = '\0'; 2043 lreply(250, "%s", line); 2044 } 2045 (void) fflush(stdout); 2046 (void) fclose(message); 2047 } 2048 ack("CWD"); 2049 } 2050} 2051 2052void 2053replydirname(const char *name, const char *message) 2054{ 2055 char *p, *ep; 2056 char npath[MAXPATHLEN * 2]; 2057 2058 p = npath; 2059 ep = &npath[sizeof(npath) - 1]; 2060 while (*name) { 2061 if (*name == '"') { 2062 if (ep - p < 2) 2063 break; 2064 *p++ = *name++; 2065 *p++ = '"'; 2066 } else { 2067 if (ep - p < 1) 2068 break; 2069 *p++ = *name++; 2070 } 2071 } 2072 *p = '\0'; 2073 reply(257, "\"%s\" %s", npath, message); 2074} 2075 2076void 2077makedir(char *name) 2078{ 2079 2080 LOGCMD("mkdir", name); 2081 if (mkdir(name, 0777) < 0) 2082 perror_reply(550, name); 2083 else 2084 replydirname(name, "directory created."); 2085} 2086 2087void 2088removedir(char *name) 2089{ 2090 2091 LOGCMD("rmdir", name); 2092 if (rmdir(name) < 0) 2093 perror_reply(550, name); 2094 else 2095 ack("RMD"); 2096} 2097 2098void 2099pwd(void) 2100{ 2101 char path[MAXPATHLEN]; 2102 2103 if (getcwd(path, sizeof(path)) == NULL) 2104 perror_reply(550, "Can't get current directory"); 2105 else 2106 replydirname(path, "is current directory."); 2107} 2108 2109char * 2110renamefrom(char *name) 2111{ 2112 struct stat st; 2113 2114 if (stat(name, &st) < 0) { 2115 perror_reply(550, name); 2116 return ((char *)0); 2117 } 2118 reply(350, "File exists, ready for destination name"); 2119 return (name); 2120} 2121 2122void 2123renamecmd(char *from, char *to) 2124{ 2125 2126 LOGCMD2("rename", from, to); 2127 if (rename(from, to) < 0) 2128 perror_reply(550, "rename"); 2129 else 2130 ack("RNTO"); 2131} 2132 2133static void 2134dolog(struct sockaddr *sa) 2135{ 2136 char hbuf[sizeof(remotehost)]; 2137 2138 getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), NULL, 0, 0); 2139 (void) strlcpy(remotehost, hbuf, sizeof(remotehost)); 2140 2141#ifdef HASSETPROCTITLE 2142 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost); 2143 setproctitle("%s", proctitle); 2144#endif /* HASSETPROCTITLE */ 2145 2146 if (logging) 2147 syslog(LOG_INFO, "connection from %s", remotehost); 2148} 2149 2150/* 2151 * Record logout in wtmp file and exit with supplied status. 2152 * NOTE: because this is called from signal handlers it cannot 2153 * use stdio (or call other functions that use stdio). 2154 */ 2155void 2156dologout(int status) 2157{ 2158 2159 transflag = 0; 2160 2161 if (logged_in) { 2162 sigprocmask(SIG_BLOCK, &allsigs, NULL); 2163 ftpdlogwtmp(ttyline, "", ""); 2164 if (doutmp) 2165 ftpd_logout(utmp.ut_line); 2166 } 2167 /* beware of flushing buffers after a SIGPIPE */ 2168 _exit(status); 2169} 2170 2171static void 2172sigurg(int signo) 2173{ 2174 2175 recvurg = 1; 2176} 2177 2178static void 2179myoob(void) 2180{ 2181 char *cp; 2182 2183 /* only process if transfer occurring */ 2184 if (!transflag) 2185 return; 2186 cp = tmpline; 2187 if (getline(cp, 7, stdin) == NULL) { 2188 reply(221, "You could at least say goodbye."); 2189 dologout(0); 2190 } 2191 upper(cp); 2192 if (strcmp(cp, "ABOR\r\n") == 0) { 2193 tmpline[0] = '\0'; 2194 reply(426, "Transfer aborted. Data connection closed."); 2195 reply(226, "Abort successful"); 2196 } 2197 if (strcmp(cp, "STAT\r\n") == 0) { 2198 tmpline[0] = '\0'; 2199 if (file_size != (off_t) -1) 2200 reply(213, "Status: %qd of %qd bytes transferred", 2201 byte_count, file_size); 2202 else 2203 reply(213, "Status: %qd bytes transferred", byte_count); 2204 } 2205} 2206 2207/* 2208 * Note: a response of 425 is not mentioned as a possible response to 2209 * the PASV command in RFC959. However, it has been blessed as 2210 * a legitimate response by Jon Postel in a telephone conversation 2211 * with Rick Adams on 25 Jan 89. 2212 */ 2213void 2214passive(void) 2215{ 2216 socklen_t len; 2217 int on; 2218 u_char *p, *a; 2219 2220 if (pw == NULL) { 2221 reply(530, "Please login with USER and PASS"); 2222 return; 2223 } 2224 if (pdata >= 0) 2225 close(pdata); 2226 /* 2227 * XXX 2228 * At this point, it would be nice to have an algorithm that 2229 * inserted a growing delay in an attack scenario. Such a thing 2230 * would look like continual passive sockets being opened, but 2231 * nothing serious being done with them. They're not used to 2232 * move data; the entire attempt is just to use tcp FIN_WAIT 2233 * resources. 2234 */ 2235 pdata = socket(AF_INET, SOCK_STREAM, 0); 2236 if (pdata < 0) { 2237 perror_reply(425, "Can't open passive connection"); 2238 return; 2239 } 2240 2241 on = IP_PORTRANGE_HIGH; 2242 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE, 2243 (char *)&on, sizeof(on)) < 0) 2244 goto pasv_error; 2245 2246 pasv_addr = ctrl_addr; 2247 pasv_addr.su_sin.sin_port = 0; 2248 if (bind(pdata, (struct sockaddr *)&pasv_addr, 2249 pasv_addr.su_len) < 0) 2250 goto pasv_error; 2251 2252 len = sizeof(pasv_addr); 2253 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0) 2254 goto pasv_error; 2255 if (listen(pdata, 1) < 0) 2256 goto pasv_error; 2257 a = (u_char *) &pasv_addr.su_sin.sin_addr; 2258 p = (u_char *) &pasv_addr.su_sin.sin_port; 2259 2260 reply(227, "Entering Passive Mode (%u,%u,%u,%u,%u,%u)", a[0], 2261 a[1], a[2], a[3], p[0], p[1]); 2262 return; 2263 2264pasv_error: 2265 (void) close(pdata); 2266 pdata = -1; 2267 perror_reply(425, "Can't open passive connection"); 2268 return; 2269} 2270 2271/* 2272 * convert protocol identifier to/from AF 2273 */ 2274int 2275lpsvproto2af(int proto) 2276{ 2277 2278 switch (proto) { 2279 case 4: return AF_INET; 2280#ifdef INET6 2281 case 6: return AF_INET6; 2282#endif 2283 default: return -1; 2284 } 2285} 2286 2287int 2288af2lpsvproto(int af) 2289{ 2290 2291 switch (af) { 2292 case AF_INET: return 4; 2293#ifdef INET6 2294 case AF_INET6: return 6; 2295#endif 2296 default: return -1; 2297 } 2298} 2299 2300int 2301epsvproto2af(int proto) 2302{ 2303 2304 switch (proto) { 2305 case 1: return AF_INET; 2306#ifdef INET6 2307 case 2: return AF_INET6; 2308#endif 2309 default: return -1; 2310 } 2311} 2312 2313int 2314af2epsvproto(int af) 2315{ 2316 2317 switch (af) { 2318 case AF_INET: return 1; 2319#ifdef INET6 2320 case AF_INET6: return 2; 2321#endif 2322 default: return -1; 2323 } 2324} 2325 2326/* 2327 * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...) 2328 * 229 Entering Extended Passive Mode (|||port|) 2329 */ 2330void 2331long_passive(char *cmd, int pf) 2332{ 2333 socklen_t len; 2334 int on; 2335 u_char *p, *a; 2336 2337 if (!logged_in) { 2338 syslog(LOG_NOTICE, "long passive but not logged in"); 2339 reply(503, "Login with USER first."); 2340 return; 2341 } 2342 2343 if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) { 2344 /* 2345 * XXX 2346 * only EPRT/EPSV ready clients will understand this 2347 */ 2348 if (strcmp(cmd, "EPSV") != 0) 2349 reply(501, "Network protocol mismatch"); /*XXX*/ 2350 else 2351 epsv_protounsupp("Network protocol mismatch"); 2352 2353 return; 2354 } 2355 2356 if (pdata >= 0) 2357 close(pdata); 2358 /* 2359 * XXX 2360 * At this point, it would be nice to have an algorithm that 2361 * inserted a growing delay in an attack scenario. Such a thing 2362 * would look like continual passive sockets being opened, but 2363 * nothing serious being done with them. They not used to move 2364 * data; the entire attempt is just to use tcp FIN_WAIT 2365 * resources. 2366 */ 2367 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0); 2368 if (pdata < 0) { 2369 perror_reply(425, "Can't open passive connection"); 2370 return; 2371 } 2372 2373 switch (ctrl_addr.su_family) { 2374 case AF_INET: 2375 on = IP_PORTRANGE_HIGH; 2376 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE, 2377 (char *)&on, sizeof(on)) < 0) 2378 goto pasv_error; 2379 break; 2380 case AF_INET6: 2381 on = IPV6_PORTRANGE_HIGH; 2382 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE, 2383 (char *)&on, sizeof(on)) < 0) 2384 goto pasv_error; 2385 break; 2386 } 2387 2388 pasv_addr = ctrl_addr; 2389 pasv_addr.su_port = 0; 2390 if (bind(pdata, (struct sockaddr *) &pasv_addr, pasv_addr.su_len) < 0) 2391 goto pasv_error; 2392 len = pasv_addr.su_len; 2393 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0) 2394 goto pasv_error; 2395 if (listen(pdata, 1) < 0) 2396 goto pasv_error; 2397 p = (u_char *) &pasv_addr.su_port; 2398 2399 if (strcmp(cmd, "LPSV") == 0) { 2400 switch (pasv_addr.su_family) { 2401 case AF_INET: 2402 a = (u_char *) &pasv_addr.su_sin.sin_addr; 2403 reply(228, 2404 "Entering Long Passive Mode (%u,%u,%u,%u,%u,%u,%u,%u,%u)", 2405 4, 4, a[0], a[1], a[2], a[3], 2, p[0], p[1]); 2406 return; 2407 case AF_INET6: 2408 a = (u_char *) &pasv_addr.su_sin6.sin6_addr; 2409 reply(228, 2410 "Entering Long Passive Mode (%u,%u,%u,%u,%u,%u," 2411 "%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u)", 2412 6, 16, a[0], a[1], a[2], a[3], a[4], 2413 a[5], a[6], a[7], a[8], a[9], a[10], 2414 a[11], a[12], a[13], a[14], a[15], 2415 2, p[0], p[1]); 2416 return; 2417 } 2418 } else if (strcmp(cmd, "EPSV") == 0) { 2419 switch (pasv_addr.su_family) { 2420 case AF_INET: 2421 case AF_INET6: 2422 reply(229, "Entering Extended Passive Mode (|||%u|)", 2423 ntohs(pasv_addr.su_port)); 2424 return; 2425 } 2426 } else { 2427 /* more proper error code? */ 2428 } 2429 2430 pasv_error: 2431 (void) close(pdata); 2432 pdata = -1; 2433 perror_reply(425, "Can't open passive connection"); 2434 return; 2435} 2436 2437/* 2438 * EPRT |proto|addr|port| 2439 */ 2440int 2441extended_port(const char *arg) 2442{ 2443 char *tmp = NULL; 2444 char *result[3]; 2445 char *p, *q; 2446 char delim; 2447 struct addrinfo hints; 2448 struct addrinfo *res = NULL; 2449 int i; 2450 unsigned long proto; 2451 2452 if (epsvall) { 2453 reply(501, "EPRT disallowed after EPSV ALL"); 2454 return -1; 2455 } 2456 2457 usedefault = 0; 2458 if (pdata >= 0) { 2459 (void) close(pdata); 2460 pdata = -1; 2461 } 2462 2463 tmp = strdup(arg); 2464 if (!tmp) { 2465 fatal("not enough core."); 2466 /*NOTREACHED*/ 2467 } 2468 p = tmp; 2469 delim = p[0]; 2470 p++; 2471 memset(result, 0, sizeof(result)); 2472 for (i = 0; i < 3; i++) { 2473 q = strchr(p, delim); 2474 if (!q || *q != delim) 2475 goto parsefail; 2476 *q++ = '\0'; 2477 result[i] = p; 2478 p = q; 2479 } 2480 2481 /* some more sanity check */ 2482 p = NULL; 2483 (void)strtoul(result[2], &p, 10); 2484 if (!*result[2] || *p) 2485 goto protounsupp; 2486 p = NULL; 2487 proto = strtoul(result[0], &p, 10); 2488 if (!*result[0] || *p) 2489 goto protounsupp; 2490 2491 memset(&hints, 0, sizeof(hints)); 2492 hints.ai_family = epsvproto2af((int)proto); 2493 if (hints.ai_family < 0) 2494 goto protounsupp; 2495 hints.ai_socktype = SOCK_STREAM; 2496 hints.ai_flags = AI_NUMERICHOST; /*no DNS*/ 2497 if (getaddrinfo(result[1], result[2], &hints, &res)) 2498 goto parsefail; 2499 if (res->ai_next) 2500 goto parsefail; 2501 if (sizeof(data_dest) < res->ai_addrlen) 2502 goto parsefail; 2503 memcpy(&data_dest, res->ai_addr, res->ai_addrlen); 2504 if (his_addr.su_family == AF_INET6 && 2505 data_dest.su_family == AF_INET6) { 2506 /* XXX more sanity checks! */ 2507 data_dest.su_sin6.sin6_scope_id = 2508 his_addr.su_sin6.sin6_scope_id; 2509 } 2510 if (pdata >= 0) { 2511 (void) close(pdata); 2512 pdata = -1; 2513 } 2514 reply(200, "EPRT command successful."); 2515 2516 if (tmp) 2517 free(tmp); 2518 if (res) 2519 freeaddrinfo(res); 2520 return 0; 2521 2522parsefail: 2523 reply(500, "Invalid argument, rejected."); 2524 usedefault = 1; 2525 if (tmp) 2526 free(tmp); 2527 if (res) 2528 freeaddrinfo(res); 2529 return -1; 2530 2531protounsupp: 2532 epsv_protounsupp("Protocol not supported"); 2533 usedefault = 1; 2534 if (tmp) 2535 free(tmp); 2536 if (res) 2537 freeaddrinfo(res); 2538 return -1; 2539} 2540 2541/* 2542 * 522 Protocol not supported (proto,...) 2543 * as we assume address family for control and data connections are the same, 2544 * we do not return the list of address families we support - instead, we 2545 * return the address family of the control connection. 2546 */ 2547void 2548epsv_protounsupp(const char *message) 2549{ 2550 int proto; 2551 2552 proto = af2epsvproto(ctrl_addr.su_family); 2553 if (proto < 0) 2554 reply(501, "%s", message); /*XXX*/ 2555 else 2556 reply(522, "%s, use (%d)", message, proto); 2557} 2558 2559/* 2560 * Generate unique name for file with basename "local". 2561 * The file named "local" is already known to exist. 2562 * Generates failure reply on error. 2563 */ 2564static int 2565guniquefd(char *local, char **nam) 2566{ 2567 static char new[MAXPATHLEN]; 2568 struct stat st; 2569 int count, len, fd; 2570 char *cp; 2571 2572 cp = strrchr(local, '/'); 2573 if (cp) 2574 *cp = '\0'; 2575 if (stat(cp ? local : ".", &st) < 0) { 2576 perror_reply(553, cp ? local : "."); 2577 return (-1); 2578 } 2579 if (cp) 2580 *cp = '/'; 2581 len = strlcpy(new, local, sizeof(new)); 2582 if (len+2+1 >= sizeof(new)-1) 2583 return (-1); 2584 cp = new + len; 2585 *cp++ = '.'; 2586 for (count = 1; count < 100; count++) { 2587 (void)snprintf(cp, sizeof(new) - (cp - new), "%d", count); 2588 fd = open(new, O_RDWR|O_CREAT|O_EXCL, 0666); 2589 if (fd == -1) 2590 continue; 2591 if (nam) 2592 *nam = new; 2593 return (fd); 2594 } 2595 reply(452, "Unique file name cannot be created."); 2596 return (-1); 2597} 2598 2599/* 2600 * Format and send reply containing system error number. 2601 */ 2602void 2603perror_reply(int code, char *string) 2604{ 2605 2606 reply(code, "%s: %s.", string, strerror(errno)); 2607} 2608 2609static char *onefile[] = { 2610 "", 2611 0 2612}; 2613 2614void 2615send_file_list(char *whichf) 2616{ 2617 struct stat st; 2618 DIR *dirp = NULL; 2619 struct dirent *dir; 2620 FILE *dout = NULL; 2621 char **dirlist; 2622 char *dirname; 2623 int simple = 0; 2624 volatile int freeglob = 0; 2625 glob_t gl; 2626 2627 if (strpbrk(whichf, "~{[*?") != NULL) { 2628 memset(&gl, 0, sizeof(gl)); 2629 freeglob = 1; 2630 if (glob(whichf, 2631 GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE|GLOB_LIMIT, 2632 0, &gl)) { 2633 reply(550, "not found"); 2634 goto out; 2635 } else if (gl.gl_pathc == 0) { 2636 errno = ENOENT; 2637 perror_reply(550, whichf); 2638 goto out; 2639 } 2640 dirlist = gl.gl_pathv; 2641 } else { 2642 onefile[0] = whichf; 2643 dirlist = onefile; 2644 simple = 1; 2645 } 2646 2647 while ((dirname = *dirlist++)) { 2648 if (stat(dirname, &st) < 0) { 2649 /* 2650 * If user typed "ls -l", etc, and the client 2651 * used NLST, do what the user meant. 2652 */ 2653 if (dirname[0] == '-' && *dirlist == NULL && 2654 transflag == 0) { 2655 retrieve("/bin/ls %s", dirname); 2656 goto out; 2657 } 2658 perror_reply(550, whichf); 2659 if (dout != NULL) { 2660 (void) fclose(dout); 2661 transflag = 0; 2662 data = -1; 2663 pdata = -1; 2664 } 2665 goto out; 2666 } 2667 2668 if (S_ISREG(st.st_mode)) { 2669 if (dout == NULL) { 2670 dout = dataconn("file list", (off_t)-1, "w"); 2671 if (dout == NULL) 2672 goto out; 2673 transflag++; 2674 } 2675 fprintf(dout, "%s%s\n", dirname, 2676 type == TYPE_A ? "\r" : ""); 2677 byte_count += strlen(dirname) + 1; 2678 continue; 2679 } else if (!S_ISDIR(st.st_mode)) 2680 continue; 2681 2682 if ((dirp = opendir(dirname)) == NULL) 2683 continue; 2684 2685 while ((dir = readdir(dirp)) != NULL) { 2686 char nbuf[MAXPATHLEN]; 2687 2688 if (recvurg) { 2689 myoob(); 2690 recvurg = 0; 2691 transflag = 0; 2692 goto out; 2693 } 2694 2695 if (dir->d_name[0] == '.' && dir->d_namlen == 1) 2696 continue; 2697 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' && 2698 dir->d_namlen == 2) 2699 continue; 2700 2701 snprintf(nbuf, sizeof(nbuf), "%s/%s", dirname, 2702 dir->d_name); 2703 2704 /* 2705 * We have to do a stat to insure it's 2706 * not a directory or special file. 2707 */ 2708 if (simple || (stat(nbuf, &st) == 0 && 2709 S_ISREG(st.st_mode))) { 2710 if (dout == NULL) { 2711 dout = dataconn("file list", (off_t)-1, 2712 "w"); 2713 if (dout == NULL) 2714 goto out; 2715 transflag++; 2716 } 2717 if (nbuf[0] == '.' && nbuf[1] == '/') 2718 fprintf(dout, "%s%s\n", &nbuf[2], 2719 type == TYPE_A ? "\r" : ""); 2720 else 2721 fprintf(dout, "%s%s\n", nbuf, 2722 type == TYPE_A ? "\r" : ""); 2723 byte_count += strlen(nbuf) + 1; 2724 } 2725 } 2726 (void) closedir(dirp); 2727 } 2728 2729 if (dout == NULL) 2730 reply(550, "No files found."); 2731 else if (ferror(dout) != 0) 2732 perror_reply(550, "Data connection"); 2733 else 2734 reply(226, "Transfer complete."); 2735 2736 transflag = 0; 2737 if (dout != NULL) 2738 (void) fclose(dout); 2739 else { 2740 if (pdata >= 0) 2741 close(pdata); 2742 } 2743 data = -1; 2744 pdata = -1; 2745out: 2746 if (freeglob) { 2747 freeglob = 0; 2748 globfree(&gl); 2749 } 2750} 2751 2752static void 2753reapchild(int signo) 2754{ 2755 int save_errno = errno; 2756 int rval; 2757 2758 do { 2759 rval = waitpid(-1, NULL, WNOHANG); 2760 } while (rval > 0 || (rval == -1 && errno == EINTR)); 2761 errno = save_errno; 2762} 2763 2764void 2765logxfer(char *name, off_t size, time_t start) 2766{ 2767 char buf[400 + MAXHOSTNAMELEN*4 + MAXPATHLEN*4]; 2768 char dir[MAXPATHLEN], path[MAXPATHLEN], rpath[MAXPATHLEN]; 2769 char vremotehost[MAXHOSTNAMELEN*4], vpath[MAXPATHLEN*4]; 2770 char *vpw; 2771 time_t now; 2772 int len; 2773 2774 if ((statfd >= 0) && (getcwd(dir, sizeof(dir)) != NULL)) { 2775 time(&now); 2776 2777 vpw = malloc(strlen(guest ? guestpw : pw->pw_name) * 4 + 1); 2778 if (vpw == NULL) 2779 return; 2780 2781 snprintf(path, sizeof(path), "%s/%s", dir, name); 2782 if (realpath(path, rpath) == NULL) 2783 strlcpy(rpath, path, sizeof(rpath)); 2784 strvis(vpath, rpath, VIS_SAFE|VIS_NOSLASH); 2785 2786 strvis(vremotehost, remotehost, VIS_SAFE|VIS_NOSLASH); 2787 strvis(vpw, guest? guestpw : pw->pw_name, VIS_SAFE|VIS_NOSLASH); 2788 2789 if ((len = snprintf(buf, sizeof(buf), 2790 "%.24s %d %s %qd %s %c %s %c %c %s ftp %d %s %s\n", 2791 ctime(&now), now - start + (now == start), 2792 vremotehost, (long long)size, vpath, 2793 ((type == TYPE_A) ? 'a' : 'b'), "*" /* none yet */, 2794 'o', ((guest) ? 'a' : 'r'), 2795 vpw, 0 /* none yet */, 2796 ((guest) ? "*" : pw->pw_name), dhostname)) >= sizeof(buf) 2797 || len < 0) { 2798 if ((len = strlen(buf)) == 0) 2799 return; /* should not happen */ 2800 buf[len - 1] = '\n'; 2801 } 2802 write(statfd, buf, len); 2803 free(vpw); 2804 } 2805} 2806 2807void 2808set_slave_signals(void) 2809{ 2810 struct sigaction sa; 2811 2812 sigemptyset(&sa.sa_mask); 2813 sa.sa_flags = SA_RESTART; 2814 2815 sa.sa_handler = SIG_DFL; 2816 (void) sigaction(SIGCHLD, &sa, NULL); 2817 2818 sa.sa_handler = sigurg; 2819 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */ 2820 (void) sigaction(SIGURG, &sa, NULL); 2821 2822 sigfillset(&sa.sa_mask); /* block all signals in handler */ 2823 sa.sa_flags = SA_RESTART; 2824 sa.sa_handler = sigquit; 2825 (void) sigaction(SIGHUP, &sa, NULL); 2826 (void) sigaction(SIGINT, &sa, NULL); 2827 (void) sigaction(SIGQUIT, &sa, NULL); 2828 (void) sigaction(SIGTERM, &sa, NULL); 2829 2830 sa.sa_handler = lostconn; 2831 (void) sigaction(SIGPIPE, &sa, NULL); 2832 2833 sa.sa_handler = toolong; 2834 (void) sigaction(SIGALRM, &sa, NULL); 2835 2836#ifdef F_SETOWN 2837 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1) 2838 syslog(LOG_ERR, "fcntl F_SETOWN: %m"); 2839#endif 2840} 2841 2842#if defined(TCPWRAPPERS) 2843static int 2844check_host(struct sockaddr *sa) 2845{ 2846 struct sockaddr_in *sin; 2847 struct hostent *hp; 2848 char *addr; 2849 2850 if (sa->sa_family != AF_INET) 2851 return 1; /*XXX*/ 2852 2853 sin = (struct sockaddr_in *)sa; 2854 hp = gethostbyaddr((char *)&sin->sin_addr, 2855 sizeof(struct in_addr), AF_INET); 2856 addr = inet_ntoa(sin->sin_addr); 2857 if (hp) { 2858 if (!hosts_ctl("ftpd", hp->h_name, addr, STRING_UNKNOWN)) { 2859 syslog(LOG_NOTICE, "tcpwrappers rejected: %s [%s]", 2860 hp->h_name, addr); 2861 return (0); 2862 } 2863 } else { 2864 if (!hosts_ctl("ftpd", STRING_UNKNOWN, addr, STRING_UNKNOWN)) { 2865 syslog(LOG_NOTICE, "tcpwrappers rejected: [%s]", addr); 2866 return (0); 2867 } 2868 } 2869 return (1); 2870} 2871#endif /* TCPWRAPPERS */ 2872 2873/* 2874 * Allocate space and return a copy of the specified dir. 2875 * If 'dir' begins with a tilde (~), expand it. 2876 */ 2877char * 2878copy_dir(char *dir, struct passwd *pw) 2879{ 2880 char *cp; 2881 char *newdir; 2882 char *user = NULL; 2883 size_t dirsiz; 2884 2885 /* Nothing to expand */ 2886 if (dir[0] != '~') 2887 return (strdup(dir)); 2888 2889 /* "dir" is of form ~user/some/dir, lookup user. */ 2890 if (dir[1] != '/' && dir[1] != '\0') { 2891 if ((cp = strchr(dir + 1, '/')) == NULL) 2892 cp = dir + strlen(dir); 2893 if ((user = malloc(cp - dir)) == NULL) 2894 return (NULL); 2895 strlcpy(user, dir + 1, cp - dir); 2896 2897 /* Only do lookup if it is a different user. */ 2898 if (strcmp(user, pw->pw_name) != 0) { 2899 if ((pw = getpwnam(user)) == NULL) { 2900 /* No such user, interpret literally */ 2901 free(user); 2902 return(strdup(dir)); 2903 } 2904 } 2905 } 2906 2907 /* 2908 * If there is no directory separator (/) then it is just pw_dir. 2909 * Otherwise, replace ~foo with pw_dir. 2910 */ 2911 if ((cp = strchr(dir + 1, '/')) == NULL) { 2912 newdir = strdup(pw->pw_dir); 2913 } else { 2914 dirsiz = strlen(cp) + strlen(pw->pw_dir) + 1; 2915 if ((newdir = malloc(dirsiz)) == NULL) { 2916 free(user); 2917 return (NULL); 2918 } 2919 strlcpy(newdir, pw->pw_dir, dirsiz); 2920 strlcat(newdir, cp, dirsiz); 2921 } 2922 2923 if (user) 2924 free(user); 2925 return(newdir); 2926} 2927