1 /* $NetBSD: ftpd.c,v 1.200 2013/07/31 19:50:47 christos Exp $ */ 2 3 /* 4 * Copyright (c) 1997-2009 The NetBSD Foundation, Inc. 5 * All rights reserved. 6 * 7 * This code is derived from software contributed to The NetBSD Foundation 8 * by Luke Mewburn. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 * POSSIBILITY OF SUCH DAMAGE. 30 */ 31 32 /* 33 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994 34 * The Regents of the University of California. All rights reserved. 35 * 36 * Redistribution and use in source and binary forms, with or without 37 * modification, are permitted provided that the following conditions 38 * are met: 39 * 1. Redistributions of source code must retain the above copyright 40 * notice, this list of conditions and the following disclaimer. 41 * 2. Redistributions in binary form must reproduce the above copyright 42 * notice, this list of conditions and the following disclaimer in the 43 * documentation and/or other materials provided with the distribution. 44 * 3. Neither the name of the University nor the names of its contributors 45 * may be used to endorse or promote products derived from this software 46 * without specific prior written permission. 47 * 48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 51 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 58 * SUCH DAMAGE. 59 */ 60 61 /* 62 * Copyright (C) 1997 and 1998 WIDE Project. 63 * All rights reserved. 64 * 65 * Redistribution and use in source and binary forms, with or without 66 * modification, are permitted provided that the following conditions 67 * are met: 68 * 1. Redistributions of source code must retain the above copyright 69 * notice, this list of conditions and the following disclaimer. 70 * 2. Redistributions in binary form must reproduce the above copyright 71 * notice, this list of conditions and the following disclaimer in the 72 * documentation and/or other materials provided with the distribution. 73 * 3. Neither the name of the project nor the names of its contributors 74 * may be used to endorse or promote products derived from this software 75 * without specific prior written permission. 76 * 77 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND 78 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 79 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 80 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE 81 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 82 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 83 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 84 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 85 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 86 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 87 * SUCH DAMAGE. 88 */ 89 90 #include <sys/cdefs.h> 91 #ifndef lint 92 __COPYRIGHT("@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\ 93 The Regents of the University of California. All rights reserved."); 94 #endif /* not lint */ 95 96 #ifndef lint 97 #if 0 98 static char sccsid[] = "@(#)ftpd.c 8.5 (Berkeley) 4/28/95"; 99 #else 100 __RCSID("$NetBSD: ftpd.c,v 1.200 2013/07/31 19:50:47 christos Exp $"); 101 #endif 102 #endif /* not lint */ 103 104 /* 105 * FTP server. 106 */ 107 #include <sys/param.h> 108 #include <sys/stat.h> 109 #include <sys/ioctl.h> 110 #include <sys/socket.h> 111 #include <sys/wait.h> 112 #include <sys/mman.h> 113 #include <sys/resource.h> 114 115 #include <netinet/in.h> 116 #include <netinet/in_systm.h> 117 #include <netinet/ip.h> 118 119 #define FTP_NAMES 120 #include <arpa/ftp.h> 121 #include <arpa/inet.h> 122 #include <arpa/telnet.h> 123 124 #include <ctype.h> 125 #include <dirent.h> 126 #include <err.h> 127 #include <errno.h> 128 #include <fcntl.h> 129 #include <fnmatch.h> 130 #include <glob.h> 131 #include <grp.h> 132 #include <limits.h> 133 #include <netdb.h> 134 #include <pwd.h> 135 #include <poll.h> 136 #include <signal.h> 137 #include <stdarg.h> 138 #include <stdio.h> 139 #include <stdlib.h> 140 #include <string.h> 141 #include <syslog.h> 142 #include <time.h> 143 #include <tzfile.h> 144 #include <unistd.h> 145 #include <util.h> 146 #ifdef SUPPORT_UTMP 147 #include <utmp.h> 148 #endif 149 #ifdef SUPPORT_UTMPX 150 #include <utmpx.h> 151 #endif 152 #ifdef SKEY 153 #include <skey.h> 154 #endif 155 #ifdef KERBEROS5 156 #include <com_err.h> 157 #include <krb5/krb5.h> 158 #endif 159 160 #ifdef LOGIN_CAP 161 #include <login_cap.h> 162 #endif 163 164 #ifdef USE_PAM 165 #include <security/pam_appl.h> 166 #endif 167 168 #define GLOBAL 169 #include "extern.h" 170 #include "pathnames.h" 171 #include "version.h" 172 173 static sig_atomic_t transflag; 174 static sig_atomic_t urgflag; 175 176 int data; 177 int Dflag; 178 int sflag; 179 int stru; /* avoid C keyword */ 180 int mode; 181 int dataport; /* use specific data port */ 182 int dopidfile; /* maintain pid file */ 183 int doutmp; /* update utmp file */ 184 int dowtmp; /* update wtmp file */ 185 int doxferlog; /* syslog/write wu-ftpd style xferlog entries */ 186 int xferlogfd; /* fd to write wu-ftpd xferlog entries to */ 187 int getnameopts; /* flags for use with getname() */ 188 int dropprivs; /* if privileges should or have been dropped */ 189 int mapped; /* IPv4 connection on AF_INET6 socket */ 190 off_t file_size; 191 off_t byte_count; 192 static char ttyline[20]; 193 194 #ifdef USE_PAM 195 static int auth_pam(void); 196 pam_handle_t *pamh = NULL; 197 #endif 198 199 #ifdef SUPPORT_UTMP 200 static struct utmp utmp; /* for utmp */ 201 #endif 202 #ifdef SUPPORT_UTMPX 203 static struct utmpx utmpx; /* for utmpx */ 204 #endif 205 206 static const char *anondir = NULL; 207 static const char *confdir = _DEFAULT_CONFDIR; 208 209 static char *curname; /* current USER name */ 210 static size_t curname_len; /* length of curname (include NUL) */ 211 212 #if defined(KERBEROS) || defined(KERBEROS5) 213 int has_ccache = 0; 214 int notickets = 1; 215 char *krbtkfile_env = NULL; 216 char *tty = ttyline; 217 int login_krb5_forwardable_tgt = 0; 218 #endif 219 220 int epsvall = 0; 221 222 /* 223 * Timeout intervals for retrying connections 224 * to hosts that don't accept PORT cmds. This 225 * is a kludge, but given the problems with TCP... 226 */ 227 #define SWAITMAX 90 /* wait at most 90 seconds */ 228 #define SWAITINT 5 /* interval between retries */ 229 230 int swaitmax = SWAITMAX; 231 int swaitint = SWAITINT; 232 233 enum send_status { 234 SS_SUCCESS, 235 SS_ABORTED, /* transfer aborted */ 236 SS_NO_TRANSFER, /* no transfer made yet */ 237 SS_FILE_ERROR, /* file read error */ 238 SS_DATA_ERROR /* data send error */ 239 }; 240 241 static int bind_pasv_addr(void); 242 static int checkuser(const char *, const char *, int, int, char **); 243 static int checkaccess(const char *); 244 static int checkpassword(const struct passwd *, const char *); 245 static void do_pass(int, int, const char *); 246 static void end_login(void); 247 static FILE *getdatasock(const char *); 248 static char *gunique(const char *); 249 static void login_utmp(const char *, const char *, const char *, 250 struct sockinet *); 251 static void logremotehost(struct sockinet *); 252 __dead static void lostconn(int); 253 __dead static void toolong(int); 254 __dead static void sigquit(int); 255 static void sigurg(int); 256 static int handleoobcmd(void); 257 static int receive_data(FILE *, FILE *); 258 static int send_data(FILE *, FILE *, const struct stat *, int); 259 static struct passwd *sgetpwnam(const char *); 260 static int write_data(int, char *, size_t, off_t *, struct timeval *, 261 int); 262 static enum send_status 263 send_data_with_read(int, int, const struct stat *, int); 264 #if !defined(__minix) 265 static enum send_status 266 send_data_with_mmap(int, int, const struct stat *, int); 267 static void logrusage(const struct rusage *, const struct rusage *); 268 #endif /* !defined(__minix) */ 269 static void logout_utmp(void); 270 271 int main(int, char *[]); 272 273 #if defined(KERBEROS) 274 int klogin(struct passwd *, char *, char *, char *); 275 void kdestroy(void); 276 #endif 277 #if defined(KERBEROS5) 278 int k5login(struct passwd *, char *, char *, char *); 279 void k5destroy(void); 280 #endif 281 282 int 283 main(int argc, char *argv[]) 284 { 285 int ch, on = 1, tos, keepalive; 286 socklen_t addrlen; 287 #ifdef KERBEROS5 288 krb5_error_code kerror; 289 #endif 290 char *p; 291 const char *xferlogname = NULL; 292 long l; 293 struct sigaction sa; 294 sa_family_t af = AF_UNSPEC; 295 296 connections = 1; 297 ftpd_debug = 0; 298 logging = 0; 299 pdata = -1; 300 Dflag = 0; 301 sflag = 0; 302 dataport = 0; 303 dopidfile = 1; /* default: DO use a pid file to count users */ 304 doutmp = 0; /* default: Do NOT log to utmp */ 305 dowtmp = 1; /* default: DO log to wtmp */ 306 doxferlog = 0; /* default: Do NOT syslog xferlog */ 307 xferlogfd = -1; /* default: Do NOT write xferlog file */ 308 getnameopts = 0; /* default: xlate addrs to name */ 309 dropprivs = 0; 310 mapped = 0; 311 usedefault = 1; 312 emailaddr = NULL; 313 hostname[0] = '\0'; 314 homedir[0] = '\0'; 315 gidcount = 0; 316 is_oob = 0; 317 version = FTPD_VERSION; 318 319 /* 320 * LOG_NDELAY sets up the logging connection immediately, 321 * necessary for anonymous ftp's that chroot and can't do it later. 322 */ 323 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP); 324 325 while ((ch = getopt(argc, argv, 326 "46a:c:C:Dde:h:HlL:nP:qQrst:T:uUvV:wWX")) != -1) { 327 switch (ch) { 328 case '4': 329 af = AF_INET; 330 break; 331 332 case '6': 333 af = AF_INET6; 334 break; 335 336 case 'a': 337 anondir = optarg; 338 break; 339 340 case 'c': 341 confdir = optarg; 342 break; 343 344 case 'C': 345 if ((p = strchr(optarg, '@')) != NULL) { 346 *p++ = '\0'; 347 strlcpy(remotehost, p, MAXHOSTNAMELEN + 1); 348 if (inet_pton(AF_INET, p, 349 &his_addr.su_addr) == 1) { 350 his_addr.su_family = AF_INET; 351 his_addr.su_len = 352 sizeof(his_addr.si_su.su_sin); 353 #ifdef INET6 354 } else if (inet_pton(AF_INET6, p, 355 &his_addr.su_6addr) == 1) { 356 his_addr.su_family = AF_INET6; 357 his_addr.su_len = 358 sizeof(his_addr.si_su.su_sin6); 359 #endif 360 } else 361 his_addr.su_family = AF_UNSPEC; 362 } 363 pw = sgetpwnam(optarg); 364 exit(checkaccess(optarg) ? 0 : 1); 365 /* NOTREACHED */ 366 367 case 'D': 368 Dflag = 1; 369 break; 370 371 case 'd': 372 case 'v': /* deprecated */ 373 ftpd_debug = 1; 374 break; 375 376 case 'e': 377 emailaddr = optarg; 378 break; 379 380 case 'h': 381 strlcpy(hostname, optarg, sizeof(hostname)); 382 break; 383 384 case 'H': 385 if (gethostname(hostname, sizeof(hostname)) == -1) 386 hostname[0] = '\0'; 387 hostname[sizeof(hostname) - 1] = '\0'; 388 break; 389 390 case 'l': 391 logging++; /* > 1 == extra logging */ 392 break; 393 394 case 'L': 395 xferlogname = optarg; 396 break; 397 398 case 'n': 399 getnameopts = NI_NUMERICHOST; 400 break; 401 402 case 'P': 403 errno = 0; 404 p = NULL; 405 l = strtol(optarg, &p, 10); 406 if (errno || *optarg == '\0' || *p != '\0' || 407 l < IPPORT_RESERVED || 408 l > IPPORT_ANONMAX) { 409 syslog(LOG_WARNING, "Invalid dataport %s", 410 optarg); 411 dataport = 0; 412 } 413 dataport = (int)l; 414 break; 415 416 case 'q': 417 dopidfile = 1; 418 break; 419 420 case 'Q': 421 dopidfile = 0; 422 break; 423 424 case 'r': 425 dropprivs = 1; 426 break; 427 428 case 's': 429 sflag = 1; 430 break; 431 432 case 't': 433 case 'T': 434 syslog(LOG_WARNING, 435 "-%c has been deprecated in favour of ftpd.conf", 436 ch); 437 break; 438 439 case 'u': 440 doutmp = 1; 441 break; 442 443 case 'U': 444 doutmp = 0; 445 break; 446 447 case 'V': 448 if (EMPTYSTR(optarg) || strcmp(optarg, "-") == 0) 449 version = NULL; 450 else 451 version = ftpd_strdup(optarg); 452 break; 453 454 case 'w': 455 dowtmp = 1; 456 break; 457 458 case 'W': 459 dowtmp = 0; 460 break; 461 462 case 'X': 463 doxferlog |= 1; 464 break; 465 466 default: 467 if (optopt == 'a' || optopt == 'C') 468 exit(1); 469 syslog(LOG_WARNING, "unknown flag -%c ignored", optopt); 470 break; 471 } 472 } 473 if (EMPTYSTR(confdir)) 474 confdir = _DEFAULT_CONFDIR; 475 476 if (dowtmp) { 477 #ifdef SUPPORT_UTMPX 478 ftpd_initwtmpx(); 479 #endif 480 #ifdef SUPPORT_UTMP 481 ftpd_initwtmp(); 482 #endif 483 } 484 errno = 0; 485 #if !defined(__minix) 486 l = sysconf(_SC_LOGIN_NAME_MAX); 487 if (l == -1 && errno != 0) { 488 syslog(LOG_ERR, "sysconf _SC_LOGIN_NAME_MAX: %m"); 489 exit(1); 490 } else if (l <= 0) { 491 syslog(LOG_WARNING, "using conservative LOGIN_NAME_MAX value"); 492 curname_len = _POSIX_LOGIN_NAME_MAX; 493 } else 494 curname_len = (size_t)l; 495 #else 496 curname_len = _POSIX_LOGIN_NAME_MAX; 497 #endif /* !defined(__minix) */ 498 curname = malloc(curname_len); 499 if (curname == NULL) { 500 syslog(LOG_ERR, "malloc: %m"); 501 exit(1); 502 } 503 curname[0] = '\0'; 504 505 if (Dflag) { 506 int error, fd, i, n, *socks; 507 struct pollfd *fds; 508 struct addrinfo hints, *res, *res0; 509 510 if (daemon(1, 0) == -1) { 511 syslog(LOG_ERR, "failed to daemonize: %m"); 512 exit(1); 513 } 514 (void)memset(&sa, 0, sizeof(sa)); 515 sa.sa_handler = SIG_IGN; 516 sa.sa_flags = SA_NOCLDWAIT; 517 sigemptyset(&sa.sa_mask); 518 (void)sigaction(SIGCHLD, &sa, NULL); 519 520 (void)memset(&hints, 0, sizeof(hints)); 521 hints.ai_flags = AI_PASSIVE; 522 hints.ai_family = af; 523 hints.ai_socktype = SOCK_STREAM; 524 error = getaddrinfo(NULL, "ftp", &hints, &res0); 525 if (error) { 526 syslog(LOG_ERR, "getaddrinfo: %s", gai_strerror(error)); 527 exit(1); 528 } 529 530 for (n = 0, res = res0; res != NULL; res = res->ai_next) 531 n++; 532 if (n == 0) { 533 syslog(LOG_ERR, "no addresses available"); 534 exit(1); 535 } 536 socks = malloc(n * sizeof(int)); 537 fds = malloc(n * sizeof(struct pollfd)); 538 if (socks == NULL || fds == NULL) { 539 syslog(LOG_ERR, "malloc: %m"); 540 exit(1); 541 } 542 543 for (n = 0, res = res0; res != NULL; res = res->ai_next) { 544 socks[n] = socket(res->ai_family, res->ai_socktype, 545 res->ai_protocol); 546 if (socks[n] == -1) 547 continue; 548 (void)setsockopt(socks[n], SOL_SOCKET, SO_REUSEADDR, 549 &on, sizeof(on)); 550 if (bind(socks[n], res->ai_addr, res->ai_addrlen) 551 == -1) { 552 (void)close(socks[n]); 553 continue; 554 } 555 if (listen(socks[n], 12) == -1) { 556 (void)close(socks[n]); 557 continue; 558 } 559 560 fds[n].fd = socks[n]; 561 fds[n].events = POLLIN; 562 n++; 563 } 564 if (n == 0) { 565 syslog(LOG_ERR, "%m"); 566 exit(1); 567 } 568 freeaddrinfo(res0); 569 570 if (pidfile(NULL) == -1) 571 syslog(LOG_ERR, "failed to write a pid file: %m"); 572 573 for (;;) { 574 if (poll(fds, n, INFTIM) == -1) { 575 if (errno == EINTR) 576 continue; 577 syslog(LOG_ERR, "poll: %m"); 578 exit(1); 579 } 580 for (i = 0; i < n; i++) { 581 if (fds[i].revents & POLLIN) { 582 fd = accept(fds[i].fd, NULL, NULL); 583 if (fd == -1) { 584 syslog(LOG_ERR, "accept: %m"); 585 continue; 586 } 587 switch (fork()) { 588 case -1: 589 syslog(LOG_ERR, "fork: %m"); 590 break; 591 case 0: 592 goto child; 593 /* NOTREACHED */ 594 } 595 (void)close(fd); 596 } 597 } 598 } 599 child: 600 (void)dup2(fd, STDIN_FILENO); 601 (void)dup2(fd, STDOUT_FILENO); 602 (void)dup2(fd, STDERR_FILENO); 603 for (i = 0; i < n; i++) 604 (void)close(socks[i]); 605 } 606 607 memset((char *)&his_addr, 0, sizeof(his_addr)); 608 addrlen = sizeof(his_addr.si_su); 609 if (getpeername(0, (struct sockaddr *)&his_addr.si_su, &addrlen) < 0) { 610 syslog((errno == ENOTCONN) ? LOG_NOTICE : LOG_ERR, 611 "getpeername (%s): %m",argv[0]); 612 exit(1); 613 } 614 his_addr.su_len = addrlen; 615 memset((char *)&ctrl_addr, 0, sizeof(ctrl_addr)); 616 addrlen = sizeof(ctrl_addr.si_su); 617 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) { 618 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]); 619 exit(1); 620 } 621 ctrl_addr.su_len = addrlen; 622 #ifdef INET6 623 if (his_addr.su_family == AF_INET6 624 && IN6_IS_ADDR_V4MAPPED(&his_addr.su_6addr)) { 625 #if 1 626 /* 627 * IPv4 control connection arrived to AF_INET6 socket. 628 * I hate to do this, but this is the easiest solution. 629 * 630 * The assumption is untrue on SIIT environment. 631 */ 632 struct sockinet tmp_addr; 633 const int off = sizeof(struct in6_addr) - sizeof(struct in_addr); 634 635 tmp_addr = his_addr; 636 memset(&his_addr, 0, sizeof(his_addr)); 637 his_addr.su_family = AF_INET; 638 his_addr.su_len = sizeof(his_addr.si_su.su_sin); 639 memcpy(&his_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off], 640 sizeof(his_addr.su_addr)); 641 his_addr.su_port = tmp_addr.su_port; 642 643 tmp_addr = ctrl_addr; 644 memset(&ctrl_addr, 0, sizeof(ctrl_addr)); 645 ctrl_addr.su_family = AF_INET; 646 ctrl_addr.su_len = sizeof(ctrl_addr.si_su.su_sin); 647 memcpy(&ctrl_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off], 648 sizeof(ctrl_addr.su_addr)); 649 ctrl_addr.su_port = tmp_addr.su_port; 650 #else 651 while (fgets(line, sizeof(line), fd) != NULL) { 652 if ((cp = strchr(line, '\n')) != NULL) 653 *cp = '\0'; 654 reply(-530, "%s", line); 655 } 656 (void) fflush(stdout); 657 (void) fclose(fd); 658 reply(530, 659 "Connection from IPv4 mapped address is not supported."); 660 exit(0); 661 #endif 662 663 mapped = 1; 664 } else 665 #endif /* INET6 */ 666 mapped = 0; 667 #ifdef IP_TOS 668 if (!mapped && his_addr.su_family == AF_INET) { 669 tos = IPTOS_LOWDELAY; 670 if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos, 671 sizeof(int)) < 0) 672 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m"); 673 } 674 #endif 675 /* if the hostname hasn't been given, attempt to determine it */ 676 if (hostname[0] == '\0') { 677 if (getnameinfo((struct sockaddr *)&ctrl_addr.si_su, 678 ctrl_addr.su_len, hostname, sizeof(hostname), NULL, 0, 679 getnameopts) != 0) 680 (void)gethostname(hostname, sizeof(hostname)); 681 hostname[sizeof(hostname) - 1] = '\0'; 682 } 683 684 /* set this here so klogin can use it... */ 685 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid()); 686 687 (void) freopen(_PATH_DEVNULL, "w", stderr); 688 689 memset(&sa, 0, sizeof(sa)); 690 sa.sa_handler = SIG_DFL; 691 sa.sa_flags = SA_RESTART; 692 sigemptyset(&sa.sa_mask); 693 (void) sigaction(SIGCHLD, &sa, NULL); 694 695 sa.sa_handler = sigquit; 696 sa.sa_flags = SA_RESTART; 697 sigfillset(&sa.sa_mask); /* block all sigs in these handlers */ 698 (void) sigaction(SIGHUP, &sa, NULL); 699 (void) sigaction(SIGINT, &sa, NULL); 700 (void) sigaction(SIGQUIT, &sa, NULL); 701 (void) sigaction(SIGTERM, &sa, NULL); 702 sa.sa_handler = lostconn; 703 (void) sigaction(SIGPIPE, &sa, NULL); 704 sa.sa_handler = toolong; 705 (void) sigaction(SIGALRM, &sa, NULL); 706 sa.sa_handler = sigurg; 707 #if !defined(__minix) 708 (void) sigaction(SIGURG, &sa, NULL); 709 710 /* Try to handle urgent data inline */ 711 #ifdef SO_OOBINLINE 712 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0) 713 syslog(LOG_WARNING, "setsockopt: %m"); 714 #endif 715 /* Set keepalives on the socket to detect dropped connections. */ 716 #ifdef SO_KEEPALIVE 717 keepalive = 1; 718 if (setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepalive, 719 sizeof(int)) < 0) 720 syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m"); 721 #endif 722 #endif /* !defined(__minix) */ 723 724 #ifdef F_SETOWN 725 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1) 726 syslog(LOG_WARNING, "fcntl F_SETOWN: %m"); 727 #endif 728 logremotehost(&his_addr); 729 /* 730 * Set up default state 731 */ 732 data = -1; 733 type = TYPE_A; 734 form = FORM_N; 735 stru = STRU_F; 736 mode = MODE_S; 737 tmpline[0] = '\0'; 738 hasyyerrored = 0; 739 740 #ifdef KERBEROS5 741 kerror = krb5_init_context(&kcontext); 742 if (kerror) { 743 syslog(LOG_ERR, "%s when initializing Kerberos context", 744 error_message(kerror)); 745 exit(0); 746 } 747 #endif /* KERBEROS5 */ 748 749 init_curclass(); 750 curclass.timeout = 300; /* 5 minutes, as per login(1) */ 751 curclass.type = CLASS_REAL; 752 753 /* If logins are disabled, print out the message. */ 754 if (display_file(_PATH_NOLOGIN, 530)) { 755 reply(530, "System not available."); 756 exit(0); 757 } 758 (void)display_file(conffilename(_NAME_FTPWELCOME), 220); 759 /* reply(220,) must follow */ 760 if (EMPTYSTR(version)) 761 reply(220, "%s FTP server ready.", hostname); 762 else 763 reply(220, "%s FTP server (%s) ready.", hostname, version); 764 765 if (xferlogname != NULL) { 766 xferlogfd = open(xferlogname, O_WRONLY | O_APPEND | O_CREAT, 767 0660); 768 if (xferlogfd == -1) 769 syslog(LOG_WARNING, "open xferlog `%s': %m", 770 xferlogname); 771 else 772 doxferlog |= 2; 773 } 774 775 ftp_loop(); 776 /* NOTREACHED */ 777 } 778 779 static void 780 lostconn(int signo __unused) 781 { 782 783 if (ftpd_debug) 784 syslog(LOG_DEBUG, "lost connection"); 785 dologout(1); 786 } 787 788 static void 789 toolong(int signo __unused) 790 { 791 792 /* XXXSIGRACE */ 793 reply(421, 794 "Timeout (" LLF " seconds): closing control connection.", 795 (LLT)curclass.timeout); 796 if (logging) 797 syslog(LOG_INFO, "User %s timed out after " LLF " seconds", 798 (pw ? pw->pw_name : "unknown"), (LLT)curclass.timeout); 799 dologout(1); 800 } 801 802 static void 803 sigquit(int signo) 804 { 805 806 if (ftpd_debug) 807 syslog(LOG_DEBUG, "got signal %d", signo); 808 dologout(1); 809 } 810 811 static void 812 sigurg(int signo __unused) 813 { 814 815 urgflag = 1; 816 } 817 818 819 /* 820 * Save the result of a getpwnam. Used for USER command, since 821 * the data returned must not be clobbered by any other command 822 * (e.g., globbing). 823 */ 824 static struct passwd * 825 sgetpwnam(const char *name) 826 { 827 static struct passwd save; 828 struct passwd *p; 829 830 if ((p = getpwnam(name)) == NULL) 831 return (p); 832 if (save.pw_name) { 833 free((char *)save.pw_name); 834 memset(save.pw_passwd, 0, strlen(save.pw_passwd)); 835 free((char *)save.pw_passwd); 836 free((char *)save.pw_gecos); 837 free((char *)save.pw_dir); 838 free((char *)save.pw_shell); 839 } 840 save = *p; 841 save.pw_name = ftpd_strdup(p->pw_name); 842 save.pw_passwd = ftpd_strdup(p->pw_passwd); 843 save.pw_gecos = ftpd_strdup(p->pw_gecos); 844 save.pw_dir = ftpd_strdup(p->pw_dir); 845 save.pw_shell = ftpd_strdup(p->pw_shell); 846 return (&save); 847 } 848 849 static int login_attempts; /* number of failed login attempts */ 850 static int askpasswd; /* had USER command, ask for PASSwd */ 851 static int permitted; /* USER permitted */ 852 853 /* 854 * USER command. 855 * Sets global passwd pointer pw if named account exists and is acceptable; 856 * sets askpasswd if a PASS command is expected. If logged in previously, 857 * need to reset state. If name is "ftp" or "anonymous", the name is not in 858 * _NAME_FTPUSERS, and ftp account exists, set guest and pw, then just return. 859 * If account doesn't exist, ask for passwd anyway. Otherwise, check user 860 * requesting login privileges. Disallow anyone who does not have a standard 861 * shell as returned by getusershell(). Disallow anyone mentioned in the file 862 * _NAME_FTPUSERS to allow people such as root and uucp to be avoided. 863 */ 864 void 865 user(const char *name) 866 { 867 char *class; 868 #ifdef LOGIN_CAP 869 login_cap_t *lc = NULL; 870 #endif 871 #ifdef USE_PAM 872 int e; 873 #endif 874 875 class = NULL; 876 if (logged_in) { 877 switch (curclass.type) { 878 case CLASS_GUEST: 879 reply(530, "Can't change user from guest login."); 880 return; 881 case CLASS_CHROOT: 882 reply(530, "Can't change user from chroot user."); 883 return; 884 case CLASS_REAL: 885 if (dropprivs) { 886 reply(530, "Can't change user."); 887 return; 888 } 889 end_login(); 890 break; 891 default: 892 abort(); 893 } 894 } 895 896 #if defined(KERBEROS) 897 kdestroy(); 898 #endif 899 #if defined(KERBEROS5) 900 k5destroy(); 901 #endif 902 903 curclass.type = CLASS_REAL; 904 askpasswd = 0; 905 permitted = 0; 906 907 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) { 908 /* need `pw' setup for checkaccess() and checkuser () */ 909 if ((pw = sgetpwnam("ftp")) == NULL) 910 reply(530, "User %s unknown.", name); 911 else if (! checkaccess("ftp") || ! checkaccess("anonymous")) 912 reply(530, "User %s access denied.", name); 913 else { 914 curclass.type = CLASS_GUEST; 915 askpasswd = 1; 916 reply(331, 917 "Guest login ok, type your name as password."); 918 } 919 if (!askpasswd) { 920 if (logging) 921 syslog(LOG_NOTICE, 922 "ANONYMOUS FTP LOGIN REFUSED FROM %s", 923 remoteloghost); 924 end_login(); 925 goto cleanup_user; 926 } 927 name = "ftp"; 928 } else 929 pw = sgetpwnam(name); 930 931 strlcpy(curname, name, curname_len); 932 933 /* check user in /etc/ftpusers, and setup class */ 934 permitted = checkuser(_NAME_FTPUSERS, curname, 1, 0, &class); 935 936 /* check user in /etc/ftpchroot */ 937 #ifdef LOGIN_CAP 938 lc = login_getpwclass(pw); 939 #endif 940 if (checkuser(_NAME_FTPCHROOT, curname, 0, 0, NULL) 941 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */ 942 || login_getcapbool(lc, "ftp-chroot", 0) 943 #endif 944 ) { 945 if (curclass.type == CLASS_GUEST) { 946 syslog(LOG_NOTICE, 947 "Can't change guest user to chroot class; remove entry in %s", 948 _NAME_FTPCHROOT); 949 exit(1); 950 } 951 curclass.type = CLASS_CHROOT; 952 } 953 954 /* determine default class */ 955 if (class == NULL) { 956 switch (curclass.type) { 957 case CLASS_GUEST: 958 class = ftpd_strdup("guest"); 959 break; 960 case CLASS_CHROOT: 961 class = ftpd_strdup("chroot"); 962 break; 963 case CLASS_REAL: 964 class = ftpd_strdup("real"); 965 break; 966 default: 967 syslog(LOG_ERR, "unknown curclass.type %d; aborting", 968 curclass.type); 969 abort(); 970 } 971 } 972 /* parse ftpd.conf, setting up various parameters */ 973 parse_conf(class); 974 /* if not guest user, check for valid shell */ 975 if (pw == NULL) 976 permitted = 0; 977 else { 978 const char *cp, *shell; 979 980 if ((shell = pw->pw_shell) == NULL || *shell == 0) 981 shell = _PATH_BSHELL; 982 while ((cp = getusershell()) != NULL) 983 if (strcmp(cp, shell) == 0) 984 break; 985 endusershell(); 986 if (cp == NULL && curclass.type != CLASS_GUEST) 987 permitted = 0; 988 } 989 990 /* deny quickly (after USER not PASS) if requested */ 991 if (CURCLASS_FLAGS_ISSET(denyquick) && !permitted) { 992 reply(530, "User %s may not use FTP.", curname); 993 if (logging) 994 syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s", 995 remoteloghost, curname); 996 end_login(); 997 goto cleanup_user; 998 } 999 1000 /* if haven't asked yet (i.e, not anon), ask now */ 1001 if (!askpasswd) { 1002 askpasswd = 1; 1003 #ifdef USE_PAM 1004 e = auth_pam(); /* this does reply(331, ...) */ 1005 do_pass(1, e, ""); 1006 goto cleanup_user; 1007 #else /* !USE_PAM */ 1008 #ifdef SKEY 1009 if (skey_haskey(curname) == 0) { 1010 const char *myskey; 1011 1012 myskey = skey_keyinfo(curname); 1013 reply(331, "Password [ %s ] required for %s.", 1014 myskey ? myskey : "error getting challenge", 1015 curname); 1016 } else 1017 #endif 1018 reply(331, "Password required for %s.", curname); 1019 #endif /* !USE_PAM */ 1020 } 1021 1022 cleanup_user: 1023 #ifdef LOGIN_CAP 1024 login_close(lc); 1025 #endif 1026 /* 1027 * Delay before reading passwd after first failed 1028 * attempt to slow down passwd-guessing programs. 1029 */ 1030 if (login_attempts) 1031 sleep((unsigned) login_attempts); 1032 1033 if (class) 1034 free(class); 1035 } 1036 1037 /* 1038 * Determine whether something is to happen (allow access, chroot) 1039 * for a user. Each line is a shell-style glob followed by 1040 * `yes' or `no'. 1041 * 1042 * For backward compatibility, `allow' and `deny' are synonymns 1043 * for `yes' and `no', respectively. 1044 * 1045 * Each glob is matched against the username in turn, and the first 1046 * match found is used. If no match is found, the result is the 1047 * argument `def'. If a match is found but without and explicit 1048 * `yes'/`no', the result is the opposite of def. 1049 * 1050 * If the file doesn't exist at all, the result is the argument 1051 * `nofile' 1052 * 1053 * Any line starting with `#' is considered a comment and ignored. 1054 * 1055 * Returns 0 if the user is denied, or 1 if they are allowed. 1056 * 1057 * NOTE: needs struct passwd *pw setup before use. 1058 */ 1059 static int 1060 checkuser(const char *fname, const char *name, int def, int nofile, 1061 char **retclass) 1062 { 1063 FILE *fd; 1064 int retval; 1065 char *word, *perm, *class, *buf, *p; 1066 size_t len, line; 1067 1068 retval = def; 1069 if (retclass != NULL) 1070 *retclass = NULL; 1071 if ((fd = fopen(conffilename(fname), "r")) == NULL) 1072 return nofile; 1073 1074 line = 0; 1075 for (; 1076 (buf = fparseln(fd, &len, &line, NULL, FPARSELN_UNESCCOMM | 1077 FPARSELN_UNESCCONT | FPARSELN_UNESCESC)) != NULL; 1078 free(buf), buf = NULL) { 1079 word = perm = class = NULL; 1080 p = buf; 1081 if (len < 1) 1082 continue; 1083 if (p[len - 1] == '\n') 1084 p[--len] = '\0'; 1085 if (EMPTYSTR(p)) 1086 continue; 1087 1088 NEXTWORD(p, word); 1089 NEXTWORD(p, perm); 1090 NEXTWORD(p, class); 1091 if (EMPTYSTR(word)) 1092 continue; 1093 if (!EMPTYSTR(class)) { 1094 if (strcasecmp(class, "all") == 0 || 1095 strcasecmp(class, "none") == 0) { 1096 syslog(LOG_WARNING, 1097 "%s line %d: illegal user-defined class `%s' - skipping entry", 1098 fname, (int)line, class); 1099 continue; 1100 } 1101 } 1102 1103 /* have a host specifier */ 1104 if ((p = strchr(word, '@')) != NULL) { 1105 unsigned char net[16], mask[16], *addr; 1106 int addrlen, bits, bytes, a; 1107 1108 *p++ = '\0'; 1109 /* check against network or CIDR */ 1110 memset(net, 0x00, sizeof(net)); 1111 if ((bits = inet_net_pton(his_addr.su_family, p, net, 1112 sizeof(net))) != -1) { 1113 #ifdef INET6 1114 if (his_addr.su_family == AF_INET) { 1115 #endif 1116 addrlen = 4; 1117 addr = (unsigned char *)&his_addr.su_addr; 1118 #ifdef INET6 1119 } else { 1120 addrlen = 16; 1121 addr = (unsigned char *)&his_addr.su_6addr; 1122 } 1123 #endif 1124 bytes = bits / 8; 1125 bits = bits % 8; 1126 if (bytes > 0) 1127 memset(mask, 0xFF, bytes); 1128 if (bytes < addrlen) 1129 mask[bytes] = 0xFF << (8 - bits); 1130 if (bytes + 1 < addrlen) 1131 memset(mask + bytes + 1, 0x00, 1132 addrlen - bytes - 1); 1133 for (a = 0; a < addrlen; a++) 1134 if ((addr[a] & mask[a]) != net[a]) 1135 break; 1136 if (a < addrlen) 1137 continue; 1138 1139 /* check against hostname glob */ 1140 } else if (fnmatch(p, remotehost, FNM_CASEFOLD) != 0) 1141 continue; 1142 } 1143 1144 /* have a group specifier */ 1145 if ((p = strchr(word, ':')) != NULL) { 1146 gid_t *groups, *ng; 1147 int gsize, i, found; 1148 1149 if (pw == NULL) 1150 continue; /* no match for unknown user */ 1151 *p++ = '\0'; 1152 groups = NULL; 1153 gsize = 16; 1154 do { 1155 ng = realloc(groups, gsize * sizeof(gid_t)); 1156 if (ng == NULL) 1157 fatal( 1158 "Local resource failure: realloc"); 1159 groups = ng; 1160 } while (getgrouplist(pw->pw_name, pw->pw_gid, 1161 groups, &gsize) == -1); 1162 found = 0; 1163 for (i = 0; i < gsize; i++) { 1164 struct group *g; 1165 1166 if ((g = getgrgid(groups[i])) == NULL) 1167 continue; 1168 if (fnmatch(p, g->gr_name, 0) == 0) { 1169 found = 1; 1170 break; 1171 } 1172 } 1173 free(groups); 1174 if (!found) 1175 continue; 1176 } 1177 1178 /* check against username glob */ 1179 if (fnmatch(word, name, 0) != 0) 1180 continue; 1181 1182 if (perm != NULL && 1183 ((strcasecmp(perm, "allow") == 0) || 1184 (strcasecmp(perm, "yes") == 0))) 1185 retval = 1; 1186 else if (perm != NULL && 1187 ((strcasecmp(perm, "deny") == 0) || 1188 (strcasecmp(perm, "no") == 0))) 1189 retval = 0; 1190 else 1191 retval = !def; 1192 if (!EMPTYSTR(class) && retclass != NULL) 1193 *retclass = ftpd_strdup(class); 1194 free(buf); 1195 break; 1196 } 1197 (void) fclose(fd); 1198 return (retval); 1199 } 1200 1201 /* 1202 * Check if user is allowed by /etc/ftpusers 1203 * returns 1 for yes, 0 for no 1204 * 1205 * NOTE: needs struct passwd *pw setup (for checkuser()) 1206 */ 1207 static int 1208 checkaccess(const char *name) 1209 { 1210 1211 return (checkuser(_NAME_FTPUSERS, name, 1, 0, NULL)); 1212 } 1213 1214 static void 1215 login_utmp(const char *line, const char *name, const char *host, 1216 struct sockinet *haddr) 1217 { 1218 #if defined(SUPPORT_UTMPX) || defined(SUPPORT_UTMP) 1219 struct timeval tv; 1220 (void)gettimeofday(&tv, NULL); 1221 #endif 1222 #ifdef SUPPORT_UTMPX 1223 if (doutmp) { 1224 (void)memset(&utmpx, 0, sizeof(utmpx)); 1225 utmpx.ut_tv = tv; 1226 utmpx.ut_pid = getpid(); 1227 utmpx.ut_id[0] = 'f'; 1228 utmpx.ut_id[1] = 't'; 1229 utmpx.ut_id[2] = 'p'; 1230 utmpx.ut_id[3] = '*'; 1231 utmpx.ut_type = USER_PROCESS; 1232 (void)strncpy(utmpx.ut_name, name, sizeof(utmpx.ut_name)); 1233 (void)strncpy(utmpx.ut_line, line, sizeof(utmpx.ut_line)); 1234 (void)strncpy(utmpx.ut_host, host, sizeof(utmpx.ut_host)); 1235 (void)memcpy(&utmpx.ut_ss, &haddr->si_su, haddr->su_len); 1236 ftpd_loginx(&utmpx); 1237 } 1238 if (dowtmp) 1239 ftpd_logwtmpx(line, name, host, haddr, 0, USER_PROCESS); 1240 #endif 1241 #ifdef SUPPORT_UTMP 1242 if (doutmp) { 1243 (void)memset(&utmp, 0, sizeof(utmp)); 1244 (void)time(&utmp.ut_time); 1245 (void)strncpy(utmp.ut_name, name, sizeof(utmp.ut_name)); 1246 (void)strncpy(utmp.ut_line, line, sizeof(utmp.ut_line)); 1247 (void)strncpy(utmp.ut_host, host, sizeof(utmp.ut_host)); 1248 ftpd_login(&utmp); 1249 } 1250 if (dowtmp) 1251 ftpd_logwtmp(line, name, host); 1252 #endif 1253 } 1254 1255 static void 1256 logout_utmp(void) 1257 { 1258 #ifdef SUPPORT_UTMPX 1259 int okwtmpx = dowtmp; 1260 #endif 1261 #ifdef SUPPORT_UTMP 1262 int okwtmp = dowtmp; 1263 #endif 1264 if (logged_in) { 1265 #ifdef SUPPORT_UTMPX 1266 if (doutmp) 1267 okwtmpx &= ftpd_logoutx(ttyline, 0, DEAD_PROCESS); 1268 if (okwtmpx) 1269 ftpd_logwtmpx(ttyline, "", "", NULL, 0, DEAD_PROCESS); 1270 #endif 1271 #ifdef SUPPORT_UTMP 1272 if (doutmp) 1273 okwtmp &= ftpd_logout(ttyline); 1274 if (okwtmp) 1275 ftpd_logwtmp(ttyline, "", ""); 1276 #endif 1277 } 1278 } 1279 1280 /* 1281 * Terminate login as previous user (if any), resetting state; 1282 * used when USER command is given or login fails. 1283 */ 1284 static void 1285 end_login(void) 1286 { 1287 #ifdef USE_PAM 1288 int e; 1289 #endif 1290 logout_utmp(); 1291 show_chdir_messages(-1); /* flush chdir cache */ 1292 if (pw != NULL && pw->pw_passwd != NULL) 1293 memset(pw->pw_passwd, 0, strlen(pw->pw_passwd)); 1294 pw = NULL; 1295 logged_in = 0; 1296 askpasswd = 0; 1297 permitted = 0; 1298 quietmessages = 0; 1299 gidcount = 0; 1300 curclass.type = CLASS_REAL; 1301 (void) seteuid((uid_t)0); 1302 #ifdef LOGIN_CAP 1303 setusercontext(NULL, getpwuid(0), 0, 1304 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK); 1305 #endif 1306 #ifdef USE_PAM 1307 if (pamh) { 1308 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS) 1309 syslog(LOG_ERR, "pam_setcred: %s", 1310 pam_strerror(pamh, e)); 1311 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS) 1312 syslog(LOG_ERR, "pam_close_session: %s", 1313 pam_strerror(pamh, e)); 1314 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) 1315 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e)); 1316 pamh = NULL; 1317 } 1318 #endif 1319 } 1320 1321 void 1322 pass(const char *passwd) 1323 { 1324 do_pass(0, 0, passwd); 1325 } 1326 1327 /* 1328 * Perform the passwd confirmation and login. 1329 * 1330 * If pass_checked is zero, confirm passwd is correct, & ignore pass_rval. 1331 * This is the traditional PASS implementation. 1332 * 1333 * If pass_checked is non-zero, use pass_rval and ignore passwd. 1334 * This is used by auth_pam() which has already parsed PASS. 1335 * This only applies to curclass.type != CLASS_GUEST. 1336 */ 1337 static void 1338 do_pass(int pass_checked, int pass_rval, const char *passwd) 1339 { 1340 int rval; 1341 char root[MAXPATHLEN]; 1342 #ifdef LOGIN_CAP 1343 login_cap_t *lc = NULL; 1344 #endif 1345 #ifdef USE_PAM 1346 int e; 1347 #endif 1348 1349 rval = 1; 1350 1351 if (logged_in || askpasswd == 0) { 1352 reply(503, "Login with USER first."); 1353 return; 1354 } 1355 askpasswd = 0; 1356 if (curclass.type != CLASS_GUEST) { 1357 /* "ftp" is the only account allowed with no password */ 1358 if (pw == NULL) { 1359 rval = 1; /* failure below */ 1360 goto skip; 1361 } 1362 if (pass_checked) { /* password validated in user() */ 1363 rval = pass_rval; 1364 goto skip; 1365 } 1366 #ifdef USE_PAM 1367 syslog(LOG_ERR, "do_pass: USE_PAM shouldn't get here"); 1368 rval = 1; 1369 goto skip; 1370 #endif 1371 #if defined(KERBEROS) 1372 if (klogin(pw, "", hostname, (char *)passwd) == 0) { 1373 rval = 0; 1374 goto skip; 1375 } 1376 #endif 1377 #if defined(KERBEROS5) 1378 if (k5login(pw, "", hostname, (char *)passwd) == 0) { 1379 rval = 0; 1380 goto skip; 1381 } 1382 #endif 1383 #ifdef SKEY 1384 if (skey_haskey(pw->pw_name) == 0) { 1385 char *p; 1386 int r; 1387 1388 p = ftpd_strdup(passwd); 1389 r = skey_passcheck(pw->pw_name, p); 1390 free(p); 1391 if (r != -1) { 1392 rval = 0; 1393 goto skip; 1394 } 1395 } 1396 #endif 1397 if (!sflag) 1398 rval = checkpassword(pw, passwd); 1399 else 1400 rval = 1; 1401 1402 skip: 1403 1404 /* 1405 * If rval > 0, the user failed the authentication check 1406 * above. If rval == 0, either Kerberos or local 1407 * authentication succeeded. 1408 */ 1409 if (rval) { 1410 reply(530, "%s", rval == 2 ? "Password expired." : 1411 "Login incorrect."); 1412 if (logging) { 1413 syslog(LOG_NOTICE, 1414 "FTP LOGIN FAILED FROM %s", remoteloghost); 1415 syslog(LOG_AUTHPRIV | LOG_NOTICE, 1416 "FTP LOGIN FAILED FROM %s, %s", 1417 remoteloghost, curname); 1418 } 1419 pw = NULL; 1420 if (login_attempts++ >= 5) { 1421 syslog(LOG_NOTICE, 1422 "repeated login failures from %s", 1423 remoteloghost); 1424 exit(0); 1425 } 1426 return; 1427 } 1428 } 1429 1430 /* password ok; check if anything else prevents login */ 1431 if (! permitted) { 1432 reply(530, "User %s may not use FTP.", pw->pw_name); 1433 if (logging) 1434 syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s", 1435 remoteloghost, pw->pw_name); 1436 goto bad; 1437 } 1438 1439 login_attempts = 0; /* this time successful */ 1440 if (setegid((gid_t)pw->pw_gid) < 0) { 1441 reply(550, "Can't set gid."); 1442 goto bad; 1443 } 1444 #ifdef LOGIN_CAP 1445 if ((lc = login_getpwclass(pw)) != NULL) { 1446 #ifdef notyet 1447 char remote_ip[NI_MAXHOST]; 1448 1449 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len, 1450 remote_ip, sizeof(remote_ip) - 1, NULL, 0, 1451 NI_NUMERICHOST)) 1452 *remote_ip = 0; 1453 remote_ip[sizeof(remote_ip) - 1] = 0; 1454 if (!auth_hostok(lc, remotehost, remote_ip)) { 1455 syslog(LOG_INFO|LOG_AUTH, 1456 "FTP LOGIN FAILED (HOST) as %s: permission denied.", 1457 pw->pw_name); 1458 reply(530, "Permission denied."); 1459 pw = NULL; 1460 return; 1461 } 1462 if (!auth_timeok(lc, time(NULL))) { 1463 reply(530, "Login not available right now."); 1464 pw = NULL; 1465 return; 1466 } 1467 #endif 1468 } 1469 setsid(); 1470 setusercontext(lc, pw, 0, 1471 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY| 1472 LOGIN_SETRESOURCES|LOGIN_SETUMASK); 1473 #else 1474 (void) initgroups(pw->pw_name, pw->pw_gid); 1475 /* cache groups for cmds.c::matchgroup() */ 1476 #endif 1477 #ifdef USE_PAM 1478 if (pamh) { 1479 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) { 1480 syslog(LOG_ERR, "pam_open_session: %s", 1481 pam_strerror(pamh, e)); 1482 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) 1483 != PAM_SUCCESS) { 1484 syslog(LOG_ERR, "pam_setcred: %s", 1485 pam_strerror(pamh, e)); 1486 } 1487 } 1488 #endif 1489 gidcount = getgroups(0, NULL); 1490 if (gidlist) 1491 free(gidlist); 1492 gidlist = malloc(gidcount * sizeof *gidlist); 1493 gidcount = getgroups(gidcount, gidlist); 1494 1495 /* open utmp/wtmp before chroot */ 1496 login_utmp(ttyline, pw->pw_name, remotehost, &his_addr); 1497 1498 logged_in = 1; 1499 1500 connections = 1; 1501 if (dopidfile) 1502 count_users(); 1503 if (curclass.limit != -1 && connections > curclass.limit) { 1504 if (! EMPTYSTR(curclass.limitfile)) 1505 (void)display_file(conffilename(curclass.limitfile), 1506 530); 1507 reply(530, 1508 "User %s access denied, connection limit of " LLF 1509 " reached.", 1510 pw->pw_name, (LLT)curclass.limit); 1511 syslog(LOG_NOTICE, 1512 "Maximum connection limit of " LLF 1513 " for class %s reached, login refused for %s", 1514 (LLT)curclass.limit, curclass.classname, pw->pw_name); 1515 goto bad; 1516 } 1517 1518 homedir[0] = '/'; 1519 switch (curclass.type) { 1520 case CLASS_GUEST: 1521 /* 1522 * We MUST do a chdir() after the chroot. Otherwise 1523 * the old current directory will be accessible as "." 1524 * outside the new root! 1525 */ 1526 format_path(root, 1527 curclass.chroot ? curclass.chroot : 1528 anondir ? anondir : 1529 pw->pw_dir); 1530 format_path(homedir, 1531 curclass.homedir ? curclass.homedir : 1532 "/"); 1533 if (EMPTYSTR(homedir)) 1534 homedir[0] = '/'; 1535 if (EMPTYSTR(root) || chroot(root) < 0) { 1536 syslog(LOG_NOTICE, 1537 "GUEST user %s: can't chroot to %s: %m", 1538 pw->pw_name, root); 1539 goto bad_guest; 1540 } 1541 if (chdir(homedir) < 0) { 1542 syslog(LOG_NOTICE, 1543 "GUEST user %s: can't chdir to %s: %m", 1544 pw->pw_name, homedir); 1545 bad_guest: 1546 reply(550, "Can't set guest privileges."); 1547 goto bad; 1548 } 1549 break; 1550 case CLASS_CHROOT: 1551 format_path(root, 1552 curclass.chroot ? curclass.chroot : 1553 pw->pw_dir); 1554 format_path(homedir, 1555 curclass.homedir ? curclass.homedir : 1556 "/"); 1557 if (EMPTYSTR(homedir)) 1558 homedir[0] = '/'; 1559 if (EMPTYSTR(root) || chroot(root) < 0) { 1560 syslog(LOG_NOTICE, 1561 "CHROOT user %s: can't chroot to %s: %m", 1562 pw->pw_name, root); 1563 goto bad_chroot; 1564 } 1565 if (chdir(homedir) < 0) { 1566 syslog(LOG_NOTICE, 1567 "CHROOT user %s: can't chdir to %s: %m", 1568 pw->pw_name, homedir); 1569 bad_chroot: 1570 reply(550, "Can't change root."); 1571 goto bad; 1572 } 1573 break; 1574 case CLASS_REAL: 1575 /* only chroot REAL if explicitly requested */ 1576 if (! EMPTYSTR(curclass.chroot)) { 1577 format_path(root, curclass.chroot); 1578 if (EMPTYSTR(root) || chroot(root) < 0) { 1579 syslog(LOG_NOTICE, 1580 "REAL user %s: can't chroot to %s: %m", 1581 pw->pw_name, root); 1582 goto bad_chroot; 1583 } 1584 } 1585 format_path(homedir, 1586 curclass.homedir ? curclass.homedir : 1587 pw->pw_dir); 1588 if (EMPTYSTR(homedir) || chdir(homedir) < 0) { 1589 if (chdir("/") < 0) { 1590 syslog(LOG_NOTICE, 1591 "REAL user %s: can't chdir to %s: %m", 1592 pw->pw_name, 1593 !EMPTYSTR(homedir) ? homedir : "/"); 1594 reply(530, 1595 "User %s: can't change directory to %s.", 1596 pw->pw_name, 1597 !EMPTYSTR(homedir) ? homedir : "/"); 1598 goto bad; 1599 } else { 1600 reply(-230, 1601 "No directory! Logging in with home=/"); 1602 homedir[0] = '/'; 1603 } 1604 } 1605 break; 1606 } 1607 #ifndef LOGIN_CAP 1608 setsid(); 1609 #if !defined(__minix) 1610 setlogin(pw->pw_name); 1611 #endif 1612 #endif /* !defined(__minix) */ 1613 if (dropprivs || 1614 (curclass.type != CLASS_REAL && 1615 ntohs(ctrl_addr.su_port) > IPPORT_RESERVED + 1)) { 1616 dropprivs++; 1617 if (setgid((gid_t)pw->pw_gid) < 0) { 1618 reply(550, "Can't set gid."); 1619 goto bad; 1620 } 1621 if (setuid((uid_t)pw->pw_uid) < 0) { 1622 reply(550, "Can't set uid."); 1623 goto bad; 1624 } 1625 } else { 1626 if (seteuid((uid_t)pw->pw_uid) < 0) { 1627 reply(550, "Can't set uid."); 1628 goto bad; 1629 } 1630 } 1631 setenv("HOME", homedir, 1); 1632 1633 if (curclass.type == CLASS_GUEST && passwd[0] == '-') 1634 quietmessages = 1; 1635 1636 /* 1637 * Display a login message, if it exists. 1638 * N.B. reply(230,) must follow the message. 1639 */ 1640 if (! EMPTYSTR(curclass.motd)) 1641 (void)display_file(conffilename(curclass.motd), 230); 1642 show_chdir_messages(230); 1643 if (curclass.type == CLASS_GUEST) { 1644 char *p; 1645 1646 reply(230, "Guest login ok, access restrictions apply."); 1647 #if defined(HAVE_SETPROCTITLE) 1648 snprintf(proctitle, sizeof(proctitle), 1649 "%s: anonymous/%s", remotehost, passwd); 1650 setproctitle("%s", proctitle); 1651 #endif /* defined(HAVE_SETPROCTITLE) */ 1652 if (logging) 1653 syslog(LOG_INFO, 1654 "ANONYMOUS FTP LOGIN FROM %s, %s (class: %s, type: %s)", 1655 remoteloghost, passwd, 1656 curclass.classname, CURCLASSTYPE); 1657 /* store guest password reply into pw_passwd */ 1658 REASSIGN(pw->pw_passwd, ftpd_strdup(passwd)); 1659 for (p = pw->pw_passwd; *p; p++) 1660 if (!isgraph((unsigned char)*p)) 1661 *p = '_'; 1662 } else { 1663 reply(230, "User %s logged in.", pw->pw_name); 1664 #if defined(HAVE_SETPROCTITLE) 1665 snprintf(proctitle, sizeof(proctitle), 1666 "%s: %s", remotehost, pw->pw_name); 1667 setproctitle("%s", proctitle); 1668 #endif /* defined(HAVE_SETPROCTITLE) */ 1669 if (logging) 1670 syslog(LOG_INFO, 1671 "FTP LOGIN FROM %s as %s (class: %s, type: %s)", 1672 remoteloghost, pw->pw_name, 1673 curclass.classname, CURCLASSTYPE); 1674 } 1675 (void) umask(curclass.umask); 1676 #ifdef LOGIN_CAP 1677 login_close(lc); 1678 #endif 1679 return; 1680 1681 bad: 1682 #ifdef LOGIN_CAP 1683 login_close(lc); 1684 #endif 1685 /* Forget all about it... */ 1686 end_login(); 1687 } 1688 1689 void 1690 retrieve(const char *argv[], const char *name) 1691 { 1692 FILE *fin, *dout; 1693 struct stat st; 1694 int (*closefunc)(FILE *) = NULL; 1695 int dolog, sendrv, closerv, stderrfd, isconversion, isdata, isls; 1696 struct timeval start, finish, td, *tdp; 1697 #if !defined(__minix) 1698 struct rusage rusage_before, rusage_after; 1699 #endif /* !defined(__minix) */ 1700 const char *dispname; 1701 const char *error; 1702 1703 sendrv = closerv = stderrfd = -1; 1704 isconversion = isdata = isls = dolog = 0; 1705 tdp = NULL; 1706 dispname = name; 1707 fin = dout = NULL; 1708 error = NULL; 1709 if (argv == NULL) { /* if not running a command ... */ 1710 dolog = 1; 1711 isdata = 1; 1712 fin = fopen(name, "r"); 1713 closefunc = fclose; 1714 if (fin == NULL) /* doesn't exist?; try a conversion */ 1715 argv = do_conversion(name); 1716 if (argv != NULL) { 1717 isconversion++; 1718 syslog(LOG_DEBUG, "get command: '%s' on '%s'", 1719 argv[0], name); 1720 } 1721 } 1722 if (argv != NULL) { 1723 char temp[MAXPATHLEN]; 1724 1725 if (strcmp(argv[0], INTERNAL_LS) == 0) { 1726 isls = 1; 1727 stderrfd = -1; 1728 } else { 1729 (void)snprintf(temp, sizeof(temp), "%s", TMPFILE); 1730 stderrfd = mkstemp(temp); 1731 if (stderrfd != -1) 1732 (void)unlink(temp); 1733 } 1734 dispname = argv[0]; 1735 fin = ftpd_popen(argv, "r", stderrfd); 1736 closefunc = ftpd_pclose; 1737 st.st_size = -1; 1738 st.st_blksize = BUFSIZ; 1739 } 1740 if (fin == NULL) { 1741 if (errno != 0) { 1742 perror_reply(550, dispname); 1743 if (dolog) 1744 logxfer("get", -1, name, NULL, NULL, 1745 strerror(errno)); 1746 } 1747 goto cleanupretrieve; 1748 } 1749 byte_count = -1; 1750 if (argv == NULL 1751 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) { 1752 error = "Not a plain file"; 1753 reply(550, "%s: %s.", dispname, error); 1754 goto done; 1755 } 1756 if (restart_point) { 1757 if (type == TYPE_A) { 1758 off_t i; 1759 int c; 1760 1761 for (i = 0; i < restart_point; i++) { 1762 if ((c=getc(fin)) == EOF) { 1763 error = strerror(errno); 1764 perror_reply(550, dispname); 1765 goto done; 1766 } 1767 if (c == '\n') 1768 i++; 1769 } 1770 } else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) { 1771 error = strerror(errno); 1772 perror_reply(550, dispname); 1773 goto done; 1774 } 1775 } 1776 dout = dataconn(dispname, st.st_size, "w"); 1777 if (dout == NULL) 1778 goto done; 1779 1780 #if !defined(__minix) 1781 (void)getrusage(RUSAGE_SELF, &rusage_before); 1782 #endif /* !defined(__minix) */ 1783 (void)gettimeofday(&start, NULL); 1784 sendrv = send_data(fin, dout, &st, isdata); 1785 (void)gettimeofday(&finish, NULL); 1786 #if !defined(__minix) 1787 (void)getrusage(RUSAGE_SELF, &rusage_after); 1788 #endif /* !defined(__minix) */ 1789 closedataconn(dout); /* close now to affect timing stats */ 1790 timersub(&finish, &start, &td); 1791 tdp = &td; 1792 done: 1793 if (dolog) { 1794 logxfer("get", byte_count, name, NULL, tdp, error); 1795 #if !defined(__minix) 1796 if (tdp != NULL) 1797 logrusage(&rusage_before, &rusage_after); 1798 #endif /* !defined(__minix) */ 1799 } 1800 closerv = (*closefunc)(fin); 1801 if (sendrv == 0) { 1802 FILE *errf; 1803 struct stat sb; 1804 1805 if (!isls && argv != NULL && closerv != 0) { 1806 reply(-226, 1807 "Command returned an exit status of %d", 1808 closerv); 1809 if (isconversion) 1810 syslog(LOG_WARNING, 1811 "retrieve command: '%s' returned %d", 1812 argv[0], closerv); 1813 } 1814 if (!isls && argv != NULL && stderrfd != -1 && 1815 (fstat(stderrfd, &sb) == 0) && sb.st_size > 0 && 1816 ((errf = fdopen(stderrfd, "r")) != NULL)) { 1817 char *cp, line[LINE_MAX]; 1818 1819 reply(-226, "Command error messages:"); 1820 rewind(errf); 1821 while (fgets(line, sizeof(line), errf) != NULL) { 1822 if ((cp = strchr(line, '\n')) != NULL) 1823 *cp = '\0'; 1824 reply(0, " %s", line); 1825 } 1826 (void) fflush(stdout); 1827 (void) fclose(errf); 1828 /* a reply(226,) must follow */ 1829 } 1830 reply(226, "Transfer complete."); 1831 } 1832 cleanupretrieve: 1833 if (stderrfd != -1) 1834 (void)close(stderrfd); 1835 if (isconversion) 1836 free(argv); 1837 } 1838 1839 void 1840 store(const char *name, const char *fmode, int unique) 1841 { 1842 FILE *fout, *din; 1843 struct stat st; 1844 int (*closefunc)(FILE *); 1845 struct timeval start, finish, td, *tdp; 1846 const char *desc, *error; 1847 1848 din = NULL; 1849 desc = (*fmode == 'w') ? "put" : "append"; 1850 error = NULL; 1851 if (unique && stat(name, &st) == 0 && 1852 (name = gunique(name)) == NULL) { 1853 logxfer(desc, -1, name, NULL, NULL, 1854 "cannot create unique file"); 1855 goto cleanupstore; 1856 } 1857 1858 if (restart_point) 1859 fmode = "r+"; 1860 fout = fopen(name, fmode); 1861 closefunc = fclose; 1862 tdp = NULL; 1863 if (fout == NULL) { 1864 perror_reply(553, name); 1865 logxfer(desc, -1, name, NULL, NULL, strerror(errno)); 1866 goto cleanupstore; 1867 } 1868 byte_count = -1; 1869 if (restart_point) { 1870 if (type == TYPE_A) { 1871 off_t i; 1872 int c; 1873 1874 for (i = 0; i < restart_point; i++) { 1875 if ((c=getc(fout)) == EOF) { 1876 error = strerror(errno); 1877 perror_reply(550, name); 1878 goto done; 1879 } 1880 if (c == '\n') 1881 i++; 1882 } 1883 /* 1884 * We must do this seek to "current" position 1885 * because we are changing from reading to 1886 * writing. 1887 */ 1888 if (fseek(fout, 0L, SEEK_CUR) < 0) { 1889 error = strerror(errno); 1890 perror_reply(550, name); 1891 goto done; 1892 } 1893 } else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) { 1894 error = strerror(errno); 1895 perror_reply(550, name); 1896 goto done; 1897 } 1898 } 1899 din = dataconn(name, (off_t)-1, "r"); 1900 if (din == NULL) 1901 goto done; 1902 (void)gettimeofday(&start, NULL); 1903 if (receive_data(din, fout) == 0) { 1904 if (unique) 1905 reply(226, "Transfer complete (unique file name:%s).", 1906 name); 1907 else 1908 reply(226, "Transfer complete."); 1909 } 1910 (void)gettimeofday(&finish, NULL); 1911 closedataconn(din); /* close now to affect timing stats */ 1912 timersub(&finish, &start, &td); 1913 tdp = &td; 1914 done: 1915 logxfer(desc, byte_count, name, NULL, tdp, error); 1916 (*closefunc)(fout); 1917 cleanupstore: 1918 ; 1919 } 1920 1921 static FILE * 1922 getdatasock(const char *fmode) 1923 { 1924 int on, s, t, tries; 1925 in_port_t port; 1926 1927 on = 1; 1928 if (data >= 0) 1929 return (fdopen(data, fmode)); 1930 if (! dropprivs) 1931 (void) seteuid((uid_t)0); 1932 s = socket(ctrl_addr.su_family, SOCK_STREAM, 0); 1933 if (s < 0) 1934 goto bad; 1935 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, 1936 (char *) &on, sizeof(on)) < 0) 1937 goto bad; 1938 if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, 1939 (char *) &on, sizeof(on)) < 0) 1940 goto bad; 1941 /* anchor socket to avoid multi-homing problems */ 1942 data_source = ctrl_addr; 1943 /* 1944 * By default source port for PORT connctions is 1945 * ctrlport-1 (see RFC959 section 5.2). 1946 * However, if privs have been dropped and that 1947 * would be < IPPORT_RESERVED, use a random port 1948 * instead. 1949 */ 1950 if (dataport) 1951 port = dataport; 1952 else 1953 port = ntohs(ctrl_addr.su_port) - 1; 1954 if (dropprivs && port < IPPORT_RESERVED) 1955 port = 0; /* use random port */ 1956 data_source.su_port = htons(port); 1957 1958 for (tries = 1; ; tries++) { 1959 if (bind(s, (struct sockaddr *)&data_source.si_su, 1960 data_source.su_len) >= 0) 1961 break; 1962 if (errno != EADDRINUSE || tries > 10) 1963 goto bad; 1964 sleep(tries); 1965 } 1966 if (! dropprivs) 1967 (void) seteuid((uid_t)pw->pw_uid); 1968 #ifdef IP_TOS 1969 if (!mapped && ctrl_addr.su_family == AF_INET) { 1970 on = IPTOS_THROUGHPUT; 1971 if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on, 1972 sizeof(int)) < 0) 1973 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m"); 1974 } 1975 #endif 1976 return (fdopen(s, fmode)); 1977 bad: 1978 /* Return the real value of errno (close may change it) */ 1979 t = errno; 1980 if (! dropprivs) 1981 (void) seteuid((uid_t)pw->pw_uid); 1982 (void) close(s); 1983 errno = t; 1984 return (NULL); 1985 } 1986 1987 FILE * 1988 dataconn(const char *name, off_t size, const char *fmode) 1989 { 1990 char sizebuf[32]; 1991 FILE *file; 1992 int retry, tos, keepalive, conerrno; 1993 1994 file_size = size; 1995 byte_count = 0; 1996 if (size != (off_t) -1) 1997 (void)snprintf(sizebuf, sizeof(sizebuf), " (" LLF " byte%s)", 1998 (LLT)size, PLURAL(size)); 1999 else 2000 sizebuf[0] = '\0'; 2001 if (pdata >= 0) { 2002 struct sockinet from; 2003 int s; 2004 socklen_t fromlen = sizeof(from.su_len); 2005 2006 (void) alarm(curclass.timeout); 2007 s = accept(pdata, (struct sockaddr *)&from.si_su, &fromlen); 2008 (void) alarm(0); 2009 if (s < 0) { 2010 reply(425, "Can't open data connection."); 2011 (void) close(pdata); 2012 pdata = -1; 2013 return (NULL); 2014 } 2015 (void) close(pdata); 2016 pdata = s; 2017 #if !defined(__minix) 2018 switch (from.su_family) { 2019 case AF_INET: 2020 #ifdef IP_TOS 2021 if (!mapped) { 2022 tos = IPTOS_THROUGHPUT; 2023 (void) setsockopt(s, IPPROTO_IP, IP_TOS, 2024 (char *)&tos, sizeof(int)); 2025 } 2026 break; 2027 #endif 2028 } 2029 #endif /* !defined(__minix) */ 2030 /* Set keepalives on the socket to detect dropped conns. */ 2031 #ifdef SO_KEEPALIVE 2032 keepalive = 1; 2033 (void) setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, 2034 (char *)&keepalive, sizeof(int)); 2035 #endif 2036 reply(150, "Opening %s mode data connection for '%s'%s.", 2037 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf); 2038 return (fdopen(pdata, fmode)); 2039 } 2040 if (data >= 0) { 2041 reply(125, "Using existing data connection for '%s'%s.", 2042 name, sizebuf); 2043 usedefault = 1; 2044 return (fdopen(data, fmode)); 2045 } 2046 if (usedefault) 2047 data_dest = his_addr; 2048 usedefault = 1; 2049 retry = conerrno = 0; 2050 do { 2051 file = getdatasock(fmode); 2052 if (file == NULL) { 2053 char hbuf[NI_MAXHOST]; 2054 char pbuf[NI_MAXSERV]; 2055 2056 if (getnameinfo((struct sockaddr *)&data_source.si_su, 2057 data_source.su_len, hbuf, sizeof(hbuf), pbuf, 2058 sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV)) 2059 strlcpy(hbuf, "?", sizeof(hbuf)); 2060 reply(425, "Can't create data socket (%s,%s): %s.", 2061 hbuf, pbuf, strerror(errno)); 2062 return (NULL); 2063 } 2064 data = fileno(file); 2065 conerrno = 0; 2066 if (connect(data, (struct sockaddr *)&data_dest.si_su, 2067 data_dest.su_len) == 0) 2068 break; 2069 conerrno = errno; 2070 (void) fclose(file); 2071 file = NULL; 2072 data = -1; 2073 if (conerrno == EADDRINUSE) { 2074 sleep((unsigned) swaitint); 2075 retry += swaitint; 2076 } else { 2077 break; 2078 } 2079 } while (retry <= swaitmax); 2080 if (conerrno != 0) { 2081 perror_reply(425, "Can't build data connection"); 2082 return (NULL); 2083 } 2084 reply(150, "Opening %s mode data connection for '%s'%s.", 2085 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf); 2086 return (file); 2087 } 2088 2089 void 2090 closedataconn(FILE *fd) 2091 { 2092 2093 if (fd == NULL) 2094 return; 2095 (void)fclose(fd); 2096 data = -1; 2097 if (pdata >= 0) 2098 (void)close(pdata); 2099 pdata = -1; 2100 } 2101 2102 int 2103 write_data(int fd, char *buf, size_t size, off_t *bufrem, 2104 struct timeval *then, int isdata) 2105 { 2106 struct timeval now, td; 2107 ssize_t c; 2108 2109 while (size > 0) { 2110 c = size; 2111 if (curclass.writesize) { 2112 if (curclass.writesize < c) 2113 c = curclass.writesize; 2114 } 2115 if (curclass.rateget) { 2116 if (*bufrem < c) 2117 c = *bufrem; 2118 } 2119 (void) alarm(curclass.timeout); 2120 c = write(fd, buf, c); 2121 if (c <= 0) 2122 return (1); 2123 buf += c; 2124 size -= c; 2125 byte_count += c; 2126 if (isdata) { 2127 total_data_out += c; 2128 total_data += c; 2129 } 2130 total_bytes_out += c; 2131 total_bytes += c; 2132 if (curclass.rateget) { 2133 *bufrem -= c; 2134 if (*bufrem == 0) { 2135 (void)gettimeofday(&now, NULL); 2136 timersub(&now, then, &td); 2137 if (td.tv_sec == 0) { 2138 usleep(1000000 - td.tv_usec); 2139 (void)gettimeofday(then, NULL); 2140 } else 2141 *then = now; 2142 *bufrem = curclass.rateget; 2143 } 2144 } 2145 } 2146 return (0); 2147 } 2148 2149 static enum send_status 2150 send_data_with_read(int filefd, int netfd, const struct stat *st, int isdata) 2151 { 2152 struct timeval then; 2153 off_t bufrem; 2154 ssize_t readsize; 2155 char *buf; 2156 int c, error; 2157 2158 if (curclass.readsize > 0) 2159 readsize = curclass.readsize; 2160 else 2161 readsize = st->st_blksize; 2162 if ((buf = malloc(readsize)) == NULL) { 2163 perror_reply(451, "Local resource failure: malloc"); 2164 return (SS_NO_TRANSFER); 2165 } 2166 2167 if (curclass.rateget) { 2168 bufrem = curclass.rateget; 2169 (void)gettimeofday(&then, NULL); 2170 } else 2171 bufrem = readsize; 2172 for (;;) { 2173 (void) alarm(curclass.timeout); 2174 c = read(filefd, buf, readsize); 2175 if (c == 0) 2176 error = SS_SUCCESS; 2177 else if (c < 0) 2178 error = SS_FILE_ERROR; 2179 else if (write_data(netfd, buf, c, &bufrem, &then, isdata)) 2180 error = SS_DATA_ERROR; 2181 else if (urgflag && handleoobcmd()) 2182 error = SS_ABORTED; 2183 else 2184 continue; 2185 2186 free(buf); 2187 return (error); 2188 } 2189 } 2190 2191 static enum send_status 2192 send_data_with_mmap(int filefd, int netfd, const struct stat *st, int isdata) 2193 { 2194 struct timeval then; 2195 off_t bufrem, filesize, off, origoff; 2196 ssize_t mapsize, winsize; 2197 int error, sendbufsize, sendlowat; 2198 void *win; 2199 2200 bufrem = 0; 2201 if (curclass.sendbufsize) { 2202 sendbufsize = curclass.sendbufsize; 2203 if (setsockopt(netfd, SOL_SOCKET, SO_SNDBUF, 2204 &sendbufsize, sizeof(int)) == -1) 2205 syslog(LOG_WARNING, "setsockopt(SO_SNDBUF, %d): %m", 2206 sendbufsize); 2207 } 2208 2209 if (curclass.sendlowat) { 2210 sendlowat = curclass.sendlowat; 2211 if (setsockopt(netfd, SOL_SOCKET, SO_SNDLOWAT, 2212 &sendlowat, sizeof(int)) == -1) 2213 syslog(LOG_WARNING, "setsockopt(SO_SNDLOWAT, %d): %m", 2214 sendlowat); 2215 } 2216 2217 winsize = curclass.mmapsize; 2218 filesize = st->st_size; 2219 if (ftpd_debug) 2220 syslog(LOG_INFO, "mmapsize = " LLF ", writesize = " LLF, 2221 (LLT)winsize, (LLT)curclass.writesize); 2222 if (winsize <= 0) 2223 goto try_read; 2224 2225 off = lseek(filefd, (off_t)0, SEEK_CUR); 2226 if (off == -1) 2227 goto try_read; 2228 2229 origoff = off; 2230 if (curclass.rateget) { 2231 bufrem = curclass.rateget; 2232 (void)gettimeofday(&then, NULL); 2233 } else 2234 bufrem = winsize; 2235 while (1) { 2236 mapsize = MIN(filesize - off, winsize); 2237 if (mapsize == 0) 2238 break; 2239 win = mmap(NULL, mapsize, PROT_READ, 2240 MAP_FILE|MAP_SHARED, filefd, off); 2241 if (win == MAP_FAILED) { 2242 if (off == origoff) 2243 goto try_read; 2244 return (SS_FILE_ERROR); 2245 } 2246 #ifndef __minix 2247 (void) madvise(win, mapsize, MADV_SEQUENTIAL); 2248 #endif 2249 error = write_data(netfd, win, mapsize, &bufrem, &then, 2250 isdata); 2251 #ifndef __minix 2252 (void) madvise(win, mapsize, MADV_DONTNEED); 2253 #endif 2254 munmap(win, mapsize); 2255 if (urgflag && handleoobcmd()) 2256 return (SS_ABORTED); 2257 if (error) 2258 return (SS_DATA_ERROR); 2259 off += mapsize; 2260 } 2261 return (SS_SUCCESS); 2262 2263 try_read: 2264 return (send_data_with_read(filefd, netfd, st, isdata)); 2265 } 2266 2267 /* 2268 * Transfer the contents of "instr" to "outstr" peer using the appropriate 2269 * encapsulation of the data subject to Mode, Structure, and Type. 2270 * 2271 * NB: Form isn't handled. 2272 */ 2273 static int 2274 send_data(FILE *instr, FILE *outstr, const struct stat *st, int isdata) 2275 { 2276 int c, filefd, netfd, rval; 2277 2278 urgflag = 0; 2279 transflag = 1; 2280 rval = -1; 2281 2282 switch (type) { 2283 2284 case TYPE_A: 2285 /* XXXLUKEM: rate limit ascii send (get) */ 2286 (void) alarm(curclass.timeout); 2287 while ((c = getc(instr)) != EOF) { 2288 if (urgflag && handleoobcmd()) 2289 goto cleanup_send_data; 2290 byte_count++; 2291 if (c == '\n') { 2292 if (ferror(outstr)) 2293 goto data_err; 2294 (void) putc('\r', outstr); 2295 if (isdata) { 2296 total_data_out++; 2297 total_data++; 2298 } 2299 total_bytes_out++; 2300 total_bytes++; 2301 } 2302 (void) putc(c, outstr); 2303 if (isdata) { 2304 total_data_out++; 2305 total_data++; 2306 } 2307 total_bytes_out++; 2308 total_bytes++; 2309 if ((byte_count % 4096) == 0) 2310 (void) alarm(curclass.timeout); 2311 } 2312 (void) alarm(0); 2313 fflush(outstr); 2314 if (ferror(instr)) 2315 goto file_err; 2316 if (ferror(outstr)) 2317 goto data_err; 2318 rval = 0; 2319 goto cleanup_send_data; 2320 2321 case TYPE_I: 2322 case TYPE_L: 2323 filefd = fileno(instr); 2324 netfd = fileno(outstr); 2325 switch (send_data_with_mmap(filefd, netfd, st, isdata)) { 2326 2327 case SS_SUCCESS: 2328 break; 2329 2330 case SS_ABORTED: 2331 case SS_NO_TRANSFER: 2332 goto cleanup_send_data; 2333 2334 case SS_FILE_ERROR: 2335 goto file_err; 2336 2337 case SS_DATA_ERROR: 2338 goto data_err; 2339 } 2340 rval = 0; 2341 goto cleanup_send_data; 2342 2343 default: 2344 reply(550, "Unimplemented TYPE %d in send_data", type); 2345 goto cleanup_send_data; 2346 } 2347 2348 data_err: 2349 (void) alarm(0); 2350 perror_reply(426, "Data connection"); 2351 goto cleanup_send_data; 2352 2353 file_err: 2354 (void) alarm(0); 2355 perror_reply(551, "Error on input file"); 2356 goto cleanup_send_data; 2357 2358 cleanup_send_data: 2359 (void) alarm(0); 2360 transflag = 0; 2361 urgflag = 0; 2362 if (isdata) { 2363 total_files_out++; 2364 total_files++; 2365 } 2366 total_xfers_out++; 2367 total_xfers++; 2368 return (rval); 2369 } 2370 2371 /* 2372 * Transfer data from peer to "outstr" using the appropriate encapulation of 2373 * the data subject to Mode, Structure, and Type. 2374 * 2375 * N.B.: Form isn't handled. 2376 */ 2377 static int 2378 receive_data(FILE *instr, FILE *outstr) 2379 { 2380 int c, netfd, filefd, rval; 2381 int volatile bare_lfs; 2382 off_t byteswritten; 2383 char *buf; 2384 ssize_t readsize; 2385 struct sigaction sa, sa_saved; 2386 struct stat st; 2387 2388 memset(&sa, 0, sizeof(sa)); 2389 sigfillset(&sa.sa_mask); 2390 sa.sa_flags = SA_RESTART; 2391 sa.sa_handler = lostconn; 2392 (void) sigaction(SIGALRM, &sa, &sa_saved); 2393 2394 bare_lfs = 0; 2395 urgflag = 0; 2396 transflag = 1; 2397 rval = -1; 2398 byteswritten = 0; 2399 buf = NULL; 2400 2401 #define FILESIZECHECK(x) \ 2402 do { \ 2403 if (curclass.maxfilesize != -1 && \ 2404 (x) > curclass.maxfilesize) { \ 2405 errno = EFBIG; \ 2406 goto file_err; \ 2407 } \ 2408 } while (0) 2409 2410 switch (type) { 2411 2412 case TYPE_I: 2413 case TYPE_L: 2414 netfd = fileno(instr); 2415 filefd = fileno(outstr); 2416 (void) alarm(curclass.timeout); 2417 if (curclass.readsize) 2418 readsize = curclass.readsize; 2419 else if (fstat(filefd, &st) != -1) 2420 readsize = (ssize_t)st.st_blksize; 2421 else 2422 readsize = BUFSIZ; 2423 if ((buf = malloc(readsize)) == NULL) { 2424 perror_reply(451, "Local resource failure: malloc"); 2425 goto cleanup_recv_data; 2426 } 2427 if (curclass.rateput) { 2428 while (1) { 2429 int d; 2430 struct timeval then, now, td; 2431 off_t bufrem; 2432 2433 (void)gettimeofday(&then, NULL); 2434 errno = c = d = 0; 2435 for (bufrem = curclass.rateput; bufrem > 0; ) { 2436 if ((c = read(netfd, buf, 2437 MIN(readsize, bufrem))) <= 0) 2438 goto recvdone; 2439 if (urgflag && handleoobcmd()) 2440 goto cleanup_recv_data; 2441 FILESIZECHECK(byte_count + c); 2442 if ((d = write(filefd, buf, c)) != c) 2443 goto file_err; 2444 (void) alarm(curclass.timeout); 2445 bufrem -= c; 2446 byte_count += c; 2447 total_data_in += c; 2448 total_data += c; 2449 total_bytes_in += c; 2450 total_bytes += c; 2451 } 2452 (void)gettimeofday(&now, NULL); 2453 timersub(&now, &then, &td); 2454 if (td.tv_sec == 0) 2455 usleep(1000000 - td.tv_usec); 2456 } 2457 } else { 2458 while ((c = read(netfd, buf, readsize)) > 0) { 2459 if (urgflag && handleoobcmd()) 2460 goto cleanup_recv_data; 2461 FILESIZECHECK(byte_count + c); 2462 if (write(filefd, buf, c) != c) 2463 goto file_err; 2464 (void) alarm(curclass.timeout); 2465 byte_count += c; 2466 total_data_in += c; 2467 total_data += c; 2468 total_bytes_in += c; 2469 total_bytes += c; 2470 } 2471 } 2472 recvdone: 2473 if (c < 0) 2474 goto data_err; 2475 rval = 0; 2476 goto cleanup_recv_data; 2477 2478 case TYPE_E: 2479 reply(553, "TYPE E not implemented."); 2480 goto cleanup_recv_data; 2481 2482 case TYPE_A: 2483 (void) alarm(curclass.timeout); 2484 /* XXXLUKEM: rate limit ascii receive (put) */ 2485 while ((c = getc(instr)) != EOF) { 2486 if (urgflag && handleoobcmd()) 2487 goto cleanup_recv_data; 2488 byte_count++; 2489 total_data_in++; 2490 total_data++; 2491 total_bytes_in++; 2492 total_bytes++; 2493 if ((byte_count % 4096) == 0) 2494 (void) alarm(curclass.timeout); 2495 if (c == '\n') 2496 bare_lfs++; 2497 while (c == '\r') { 2498 if (ferror(outstr)) 2499 goto data_err; 2500 if ((c = getc(instr)) != '\n') { 2501 byte_count++; 2502 total_data_in++; 2503 total_data++; 2504 total_bytes_in++; 2505 total_bytes++; 2506 if ((byte_count % 4096) == 0) 2507 (void) alarm(curclass.timeout); 2508 byteswritten++; 2509 FILESIZECHECK(byteswritten); 2510 (void) putc ('\r', outstr); 2511 if (c == '\0' || c == EOF) 2512 goto contin2; 2513 } 2514 } 2515 byteswritten++; 2516 FILESIZECHECK(byteswritten); 2517 (void) putc(c, outstr); 2518 contin2: ; 2519 } 2520 (void) alarm(0); 2521 fflush(outstr); 2522 if (ferror(instr)) 2523 goto data_err; 2524 if (ferror(outstr)) 2525 goto file_err; 2526 if (bare_lfs) { 2527 reply(-226, 2528 "WARNING! %d bare linefeeds received in ASCII mode", 2529 bare_lfs); 2530 reply(0, "File may not have transferred correctly."); 2531 } 2532 rval = 0; 2533 goto cleanup_recv_data; 2534 2535 default: 2536 reply(550, "Unimplemented TYPE %d in receive_data", type); 2537 goto cleanup_recv_data; 2538 } 2539 #undef FILESIZECHECK 2540 2541 data_err: 2542 (void) alarm(0); 2543 perror_reply(426, "Data Connection"); 2544 goto cleanup_recv_data; 2545 2546 file_err: 2547 (void) alarm(0); 2548 perror_reply(452, "Error writing file"); 2549 goto cleanup_recv_data; 2550 2551 cleanup_recv_data: 2552 (void) alarm(0); 2553 (void) sigaction(SIGALRM, &sa_saved, NULL); 2554 if (buf) 2555 free(buf); 2556 transflag = 0; 2557 urgflag = 0; 2558 total_files_in++; 2559 total_files++; 2560 total_xfers_in++; 2561 total_xfers++; 2562 return (rval); 2563 } 2564 2565 void 2566 statcmd(void) 2567 { 2568 struct sockinet *su = NULL; 2569 static char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV]; 2570 unsigned char *a, *p; 2571 int ispassive, af; 2572 off_t otbi, otbo, otb; 2573 2574 a = p = NULL; 2575 2576 reply(-211, "%s FTP server status:", hostname); 2577 reply(0, "Version: %s", EMPTYSTR(version) ? "<suppressed>" : version); 2578 hbuf[0] = '\0'; 2579 if (!getnameinfo((struct sockaddr *)&his_addr.si_su, his_addr.su_len, 2580 hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST) 2581 && strcmp(remotehost, hbuf) != 0) 2582 reply(0, "Connected to %s (%s)", remotehost, hbuf); 2583 else 2584 reply(0, "Connected to %s", remotehost); 2585 2586 if (logged_in) { 2587 if (curclass.type == CLASS_GUEST) 2588 reply(0, "Logged in anonymously"); 2589 else 2590 reply(0, "Logged in as %s%s", pw->pw_name, 2591 curclass.type == CLASS_CHROOT ? " (chroot)" : ""); 2592 } else if (askpasswd) 2593 reply(0, "Waiting for password"); 2594 else 2595 reply(0, "Waiting for user name"); 2596 cprintf(stdout, " TYPE: %s", typenames[type]); 2597 if (type == TYPE_A || type == TYPE_E) 2598 cprintf(stdout, ", FORM: %s", formnames[form]); 2599 if (type == TYPE_L) { 2600 #if NBBY == 8 2601 cprintf(stdout, " %d", NBBY); 2602 #else 2603 /* XXX: `bytesize' needs to be defined in this case */ 2604 cprintf(stdout, " %d", bytesize); 2605 #endif 2606 } 2607 cprintf(stdout, "; STRUcture: %s; transfer MODE: %s\r\n", 2608 strunames[stru], modenames[mode]); 2609 ispassive = 0; 2610 if (data != -1) { 2611 reply(0, "Data connection open"); 2612 su = NULL; 2613 } else if (pdata != -1) { 2614 reply(0, "in Passive mode"); 2615 if (curclass.advertise.su_len != 0) 2616 su = &curclass.advertise; 2617 else 2618 su = &pasv_addr; 2619 ispassive = 1; 2620 goto printaddr; 2621 } else if (usedefault == 0) { 2622 su = (struct sockinet *)&data_dest; 2623 2624 if (epsvall) { 2625 reply(0, "EPSV only mode (EPSV ALL)"); 2626 goto epsvonly; 2627 } 2628 printaddr: 2629 /* PASV/PORT */ 2630 if (su->su_family == AF_INET) { 2631 a = (unsigned char *) &su->su_addr; 2632 p = (unsigned char *) &su->su_port; 2633 #define UC(b) (((int) b) & 0xff) 2634 reply(0, "%s (%d,%d,%d,%d,%d,%d)", 2635 ispassive ? "PASV" : "PORT" , 2636 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]), 2637 UC(p[0]), UC(p[1])); 2638 } 2639 2640 /* LPSV/LPRT */ 2641 { 2642 int alen, i; 2643 2644 alen = 0; 2645 switch (su->su_family) { 2646 case AF_INET: 2647 a = (unsigned char *) &su->su_addr; 2648 p = (unsigned char *) &su->su_port; 2649 alen = sizeof(su->su_addr); 2650 af = 4; 2651 break; 2652 #ifdef INET6 2653 case AF_INET6: 2654 a = (unsigned char *) &su->su_6addr; 2655 p = (unsigned char *) &su->su_port; 2656 alen = sizeof(su->su_6addr); 2657 af = 6; 2658 break; 2659 #endif 2660 default: 2661 af = 0; 2662 break; 2663 } 2664 if (af) { 2665 cprintf(stdout, " %s (%d,%d", 2666 ispassive ? "LPSV" : "LPRT", af, alen); 2667 for (i = 0; i < alen; i++) 2668 cprintf(stdout, ",%d", UC(a[i])); 2669 cprintf(stdout, ",%d,%d,%d)\r\n", 2670 2, UC(p[0]), UC(p[1])); 2671 #undef UC 2672 } 2673 } 2674 2675 /* EPRT/EPSV */ 2676 epsvonly: 2677 af = af2epsvproto(su->su_family); 2678 hbuf[0] = '\0'; 2679 if (af > 0) { 2680 struct sockinet tmp; 2681 2682 tmp = *su; 2683 #ifdef INET6 2684 if (tmp.su_family == AF_INET6) 2685 tmp.su_scope_id = 0; 2686 #endif 2687 if (getnameinfo((struct sockaddr *)&tmp.si_su, 2688 tmp.su_len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), 2689 NI_NUMERICHOST | NI_NUMERICSERV) == 0) 2690 reply(0, "%s (|%d|%s|%s|)", 2691 ispassive ? "EPSV" : "EPRT", 2692 af, hbuf, sbuf); 2693 } 2694 } else 2695 reply(0, "No data connection"); 2696 2697 if (logged_in) { 2698 reply(0, 2699 "Data sent: " LLF " byte%s in " LLF " file%s", 2700 (LLT)total_data_out, PLURAL(total_data_out), 2701 (LLT)total_files_out, PLURAL(total_files_out)); 2702 reply(0, 2703 "Data received: " LLF " byte%s in " LLF " file%s", 2704 (LLT)total_data_in, PLURAL(total_data_in), 2705 (LLT)total_files_in, PLURAL(total_files_in)); 2706 reply(0, 2707 "Total data: " LLF " byte%s in " LLF " file%s", 2708 (LLT)total_data, PLURAL(total_data), 2709 (LLT)total_files, PLURAL(total_files)); 2710 } 2711 otbi = total_bytes_in; 2712 otbo = total_bytes_out; 2713 otb = total_bytes; 2714 reply(0, "Traffic sent: " LLF " byte%s in " LLF " transfer%s", 2715 (LLT)otbo, PLURAL(otbo), 2716 (LLT)total_xfers_out, PLURAL(total_xfers_out)); 2717 reply(0, "Traffic received: " LLF " byte%s in " LLF " transfer%s", 2718 (LLT)otbi, PLURAL(otbi), 2719 (LLT)total_xfers_in, PLURAL(total_xfers_in)); 2720 reply(0, "Total traffic: " LLF " byte%s in " LLF " transfer%s", 2721 (LLT)otb, PLURAL(otb), 2722 (LLT)total_xfers, PLURAL(total_xfers)); 2723 2724 if (logged_in && !CURCLASS_FLAGS_ISSET(private)) { 2725 struct ftpconv *cp; 2726 2727 reply(0, "%s", ""); 2728 reply(0, "Class: %s, type: %s", 2729 curclass.classname, CURCLASSTYPE); 2730 reply(0, "Check PORT/LPRT commands: %sabled", 2731 CURCLASS_FLAGS_ISSET(checkportcmd) ? "en" : "dis"); 2732 if (! EMPTYSTR(curclass.display)) 2733 reply(0, "Display file: %s", curclass.display); 2734 if (! EMPTYSTR(curclass.notify)) 2735 reply(0, "Notify fileglob: %s", curclass.notify); 2736 reply(0, "Idle timeout: " LLF ", maximum timeout: " LLF, 2737 (LLT)curclass.timeout, (LLT)curclass.maxtimeout); 2738 reply(0, "Current connections: %d", connections); 2739 if (curclass.limit == -1) 2740 reply(0, "Maximum connections: unlimited"); 2741 else 2742 reply(0, "Maximum connections: " LLF, 2743 (LLT)curclass.limit); 2744 if (curclass.limitfile) 2745 reply(0, "Connection limit exceeded message file: %s", 2746 conffilename(curclass.limitfile)); 2747 if (! EMPTYSTR(curclass.chroot)) 2748 reply(0, "Chroot format: %s", curclass.chroot); 2749 reply(0, "Deny bad ftpusers(5) quickly: %sabled", 2750 CURCLASS_FLAGS_ISSET(denyquick) ? "en" : "dis"); 2751 if (! EMPTYSTR(curclass.homedir)) 2752 reply(0, "Homedir format: %s", curclass.homedir); 2753 if (curclass.maxfilesize == -1) 2754 reply(0, "Maximum file size: unlimited"); 2755 else 2756 reply(0, "Maximum file size: " LLF, 2757 (LLT)curclass.maxfilesize); 2758 if (! EMPTYSTR(curclass.motd)) 2759 reply(0, "MotD file: %s", conffilename(curclass.motd)); 2760 reply(0, 2761 "Modify commands (CHMOD, DELE, MKD, RMD, RNFR, UMASK): %sabled", 2762 CURCLASS_FLAGS_ISSET(modify) ? "en" : "dis"); 2763 reply(0, "Upload commands (APPE, STOR, STOU): %sabled", 2764 CURCLASS_FLAGS_ISSET(upload) ? "en" : "dis"); 2765 reply(0, "Sanitize file names: %sabled", 2766 CURCLASS_FLAGS_ISSET(sanenames) ? "en" : "dis"); 2767 reply(0, "PASV/LPSV/EPSV connections: %sabled", 2768 CURCLASS_FLAGS_ISSET(passive) ? "en" : "dis"); 2769 if (curclass.advertise.su_len != 0) { 2770 char buf[50]; /* big enough for IPv6 address */ 2771 const char *bp; 2772 2773 bp = inet_ntop(curclass.advertise.su_family, 2774 (void *)&curclass.advertise.su_addr, 2775 buf, sizeof(buf)); 2776 if (bp != NULL) 2777 reply(0, "PASV advertise address: %s", bp); 2778 } 2779 if (curclass.portmin && curclass.portmax) 2780 reply(0, "PASV port range: " LLF " - " LLF, 2781 (LLT)curclass.portmin, (LLT)curclass.portmax); 2782 if (curclass.rateget) 2783 reply(0, "Rate get limit: " LLF " bytes/sec", 2784 (LLT)curclass.rateget); 2785 else 2786 reply(0, "Rate get limit: disabled"); 2787 if (curclass.rateput) 2788 reply(0, "Rate put limit: " LLF " bytes/sec", 2789 (LLT)curclass.rateput); 2790 else 2791 reply(0, "Rate put limit: disabled"); 2792 if (curclass.mmapsize) 2793 reply(0, "Mmap size: " LLF, (LLT)curclass.mmapsize); 2794 else 2795 reply(0, "Mmap size: disabled"); 2796 if (curclass.readsize) 2797 reply(0, "Read size: " LLF, (LLT)curclass.readsize); 2798 else 2799 reply(0, "Read size: default"); 2800 if (curclass.writesize) 2801 reply(0, "Write size: " LLF, (LLT)curclass.writesize); 2802 else 2803 reply(0, "Write size: default"); 2804 if (curclass.recvbufsize) 2805 reply(0, "Receive buffer size: " LLF, 2806 (LLT)curclass.recvbufsize); 2807 else 2808 reply(0, "Receive buffer size: default"); 2809 if (curclass.sendbufsize) 2810 reply(0, "Send buffer size: " LLF, 2811 (LLT)curclass.sendbufsize); 2812 else 2813 reply(0, "Send buffer size: default"); 2814 if (curclass.sendlowat) 2815 reply(0, "Send low water mark: " LLF, 2816 (LLT)curclass.sendlowat); 2817 else 2818 reply(0, "Send low water mark: default"); 2819 reply(0, "Umask: %.04o", curclass.umask); 2820 for (cp = curclass.conversions; cp != NULL; cp=cp->next) { 2821 if (cp->suffix == NULL || cp->types == NULL || 2822 cp->command == NULL) 2823 continue; 2824 reply(0, "Conversion: %s [%s] disable: %s, command: %s", 2825 cp->suffix, cp->types, cp->disable, cp->command); 2826 } 2827 } 2828 2829 reply(211, "End of status"); 2830 } 2831 2832 void 2833 fatal(const char *s) 2834 { 2835 2836 reply(451, "Error in server: %s\n", s); 2837 reply(221, "Closing connection due to server error."); 2838 dologout(0); 2839 /* NOTREACHED */ 2840 } 2841 2842 /* 2843 * reply() -- 2844 * depending on the value of n, display fmt with a trailing CRLF and 2845 * prefix of: 2846 * n < -1 prefix the message with abs(n) + "-" (initial line) 2847 * n == 0 prefix the message with 4 spaces (middle lines) 2848 * n > 0 prefix the message with n + " " (final line) 2849 */ 2850 void 2851 reply(int n, const char *fmt, ...) 2852 { 2853 char msg[MAXPATHLEN * 2 + 100]; 2854 size_t b; 2855 va_list ap; 2856 2857 if (n == 0) 2858 b = snprintf(msg, sizeof(msg), " "); 2859 else if (n < 0) 2860 b = snprintf(msg, sizeof(msg), "%d-", -n); 2861 else 2862 b = snprintf(msg, sizeof(msg), "%d ", n); 2863 va_start(ap, fmt); 2864 vsnprintf(msg + b, sizeof(msg) - b, fmt, ap); 2865 va_end(ap); 2866 cprintf(stdout, "%s\r\n", msg); 2867 (void)fflush(stdout); 2868 if (ftpd_debug) 2869 syslog(LOG_DEBUG, "<--- %s", msg); 2870 } 2871 2872 static void 2873 logremotehost(struct sockinet *who) 2874 { 2875 2876 #if defined(HAVE_SOCKADDR_SNPRINTF) 2877 char abuf[BUFSIZ]; 2878 #endif 2879 2880 struct sockaddr *sa = (struct sockaddr *)&who->si_su; 2881 if (getnameinfo(sa, who->su_len, remotehost, sizeof(remotehost), NULL, 2882 0, getnameopts)) 2883 strlcpy(remotehost, "?", sizeof(remotehost)); 2884 #if defined(HAVE_SOCKADDR_SNPRINTF) 2885 sockaddr_snprintf(abuf, sizeof(abuf), "%a", sa); 2886 snprintf(remoteloghost, sizeof(remoteloghost), "%s(%s)", remotehost, 2887 abuf); 2888 #else 2889 strlcpy(remoteloghost, remotehost, sizeof(remoteloghost)); 2890 #endif 2891 2892 #if defined(HAVE_SETPROCTITLE) 2893 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost); 2894 setproctitle("%s", proctitle); 2895 #endif /* defined(HAVE_SETPROCTITLE) */ 2896 if (logging) 2897 syslog(LOG_INFO, "connection from %s to %s", 2898 remoteloghost, hostname); 2899 } 2900 2901 /* 2902 * Record logout in wtmp file and exit with supplied status. 2903 * NOTE: because this is called from signal handlers it cannot 2904 * use stdio (or call other functions that use stdio). 2905 */ 2906 void 2907 dologout(int status) 2908 { 2909 /* 2910 * Prevent reception of SIGURG from resulting in a resumption 2911 * back to the main program loop. 2912 */ 2913 transflag = 0; 2914 logout_utmp(); 2915 if (logged_in) { 2916 #ifdef KERBEROS 2917 if (!notickets && krbtkfile_env) 2918 unlink(krbtkfile_env); 2919 #endif 2920 } 2921 /* beware of flushing buffers after a SIGPIPE */ 2922 if (xferlogfd != -1) 2923 close(xferlogfd); 2924 _exit(status); 2925 } 2926 2927 void 2928 abor(void) 2929 { 2930 2931 if (!transflag) 2932 return; 2933 tmpline[0] = '\0'; 2934 is_oob = 0; 2935 reply(426, "Transfer aborted. Data connection closed."); 2936 reply(226, "Abort successful"); 2937 transflag = 0; /* flag that the transfer has aborted */ 2938 } 2939 2940 void 2941 statxfer(void) 2942 { 2943 2944 if (!transflag) 2945 return; 2946 tmpline[0] = '\0'; 2947 is_oob = 0; 2948 if (file_size != (off_t) -1) 2949 reply(213, 2950 "Status: " LLF " of " LLF " byte%s transferred", 2951 (LLT)byte_count, (LLT)file_size, 2952 PLURAL(byte_count)); 2953 else 2954 reply(213, "Status: " LLF " byte%s transferred", 2955 (LLT)byte_count, PLURAL(byte_count)); 2956 } 2957 2958 /* 2959 * Call when urgflag != 0 to handle Out Of Band commands. 2960 * Returns non zero if the OOB command aborted the transfer 2961 * by setting transflag to 0. (c.f., "ABOR"). 2962 */ 2963 static int 2964 handleoobcmd(void) 2965 { 2966 char *cp; 2967 int ret; 2968 2969 if (!urgflag) 2970 return (0); 2971 urgflag = 0; 2972 /* only process if transfer occurring */ 2973 if (!transflag) 2974 return (0); 2975 cp = tmpline; 2976 ret = get_line(cp, sizeof(tmpline)-1, stdin); 2977 if (ret == -1) { 2978 reply(221, "You could at least say goodbye."); 2979 dologout(0); 2980 } else if (ret == -2) { 2981 /* Ignore truncated command */ 2982 /* XXX: abort xfer with "500 command too long", & return 1 ? */ 2983 return 0; 2984 } 2985 /* 2986 * Manually parse OOB commands, because we can't 2987 * recursively call the yacc parser... 2988 */ 2989 if (strcasecmp(cp, "ABOR\r\n") == 0) { 2990 abor(); 2991 } else if (strcasecmp(cp, "STAT\r\n") == 0) { 2992 statxfer(); 2993 } else { 2994 /* XXX: error with "500 unknown command" ? */ 2995 } 2996 return (transflag == 0); 2997 } 2998 2999 static int 3000 bind_pasv_addr(void) 3001 { 3002 static int passiveport; 3003 int port, len; 3004 3005 len = pasv_addr.su_len; 3006 if (curclass.portmin == 0 && curclass.portmax == 0) { 3007 pasv_addr.su_port = 0; 3008 return (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len)); 3009 } 3010 3011 if (passiveport == 0) { 3012 srand(getpid()); 3013 passiveport = rand() % (curclass.portmax - curclass.portmin) 3014 + curclass.portmin; 3015 } 3016 3017 port = passiveport; 3018 while (1) { 3019 port++; 3020 if (port > curclass.portmax) 3021 port = curclass.portmin; 3022 else if (port == passiveport) { 3023 errno = EAGAIN; 3024 return (-1); 3025 } 3026 pasv_addr.su_port = htons(port); 3027 if (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len) == 0) 3028 break; 3029 if (errno != EADDRINUSE) 3030 return (-1); 3031 } 3032 passiveport = port; 3033 return (0); 3034 } 3035 3036 /* 3037 * Note: a response of 425 is not mentioned as a possible response to 3038 * the PASV command in RFC959. However, it has been blessed as 3039 * a legitimate response by Jon Postel in a telephone conversation 3040 * with Rick Adams on 25 Jan 89. 3041 */ 3042 void 3043 passive(void) 3044 { 3045 socklen_t len; 3046 int recvbufsize; 3047 char *p, *a; 3048 3049 if (pdata >= 0) 3050 close(pdata); 3051 pdata = socket(AF_INET, SOCK_STREAM, 0); 3052 if (pdata < 0 || !logged_in) { 3053 perror_reply(425, "Can't open passive connection"); 3054 return; 3055 } 3056 pasv_addr = ctrl_addr; 3057 3058 if (bind_pasv_addr() < 0) 3059 goto pasv_error; 3060 len = pasv_addr.su_len; 3061 if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0) 3062 goto pasv_error; 3063 pasv_addr.su_len = len; 3064 if (curclass.recvbufsize) { 3065 recvbufsize = curclass.recvbufsize; 3066 if (setsockopt(pdata, SOL_SOCKET, SO_RCVBUF, &recvbufsize, 3067 sizeof(int)) == -1) 3068 syslog(LOG_WARNING, "setsockopt(SO_RCVBUF, %d): %m", 3069 recvbufsize); 3070 } 3071 if (listen(pdata, 1) < 0) 3072 goto pasv_error; 3073 if (curclass.advertise.su_len != 0) 3074 a = (char *) &curclass.advertise.su_addr; 3075 else 3076 a = (char *) &pasv_addr.su_addr; 3077 p = (char *) &pasv_addr.su_port; 3078 3079 #define UC(b) (((int) b) & 0xff) 3080 3081 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]), 3082 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1])); 3083 return; 3084 3085 pasv_error: 3086 (void) close(pdata); 3087 pdata = -1; 3088 perror_reply(425, "Can't open passive connection"); 3089 return; 3090 } 3091 3092 /* 3093 * convert protocol identifier to/from AF 3094 */ 3095 int 3096 lpsvproto2af(int proto) 3097 { 3098 3099 switch (proto) { 3100 case 4: 3101 return AF_INET; 3102 #ifdef INET6 3103 case 6: 3104 return AF_INET6; 3105 #endif 3106 default: 3107 return -1; 3108 } 3109 } 3110 3111 int 3112 af2lpsvproto(int af) 3113 { 3114 3115 switch (af) { 3116 case AF_INET: 3117 return 4; 3118 #ifdef INET6 3119 case AF_INET6: 3120 return 6; 3121 #endif 3122 default: 3123 return -1; 3124 } 3125 } 3126 3127 int 3128 epsvproto2af(int proto) 3129 { 3130 3131 switch (proto) { 3132 case 1: 3133 return AF_INET; 3134 #ifdef INET6 3135 case 2: 3136 return AF_INET6; 3137 #endif 3138 default: 3139 return -1; 3140 } 3141 } 3142 3143 int 3144 af2epsvproto(int af) 3145 { 3146 3147 switch (af) { 3148 case AF_INET: 3149 return 1; 3150 #ifdef INET6 3151 case AF_INET6: 3152 return 2; 3153 #endif 3154 default: 3155 return -1; 3156 } 3157 } 3158 3159 /* 3160 * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...) 3161 * 229 Entering Extended Passive Mode (|||port|) 3162 */ 3163 void 3164 long_passive(const char *cmd, int pf) 3165 { 3166 socklen_t len; 3167 char *p, *a; 3168 3169 if (!logged_in) { 3170 syslog(LOG_NOTICE, "long passive but not logged in"); 3171 reply(503, "Login with USER first."); 3172 return; 3173 } 3174 3175 if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) { 3176 /* 3177 * XXX: only EPRT/EPSV ready clients will understand this 3178 */ 3179 if (strcmp(cmd, "EPSV") != 0) 3180 reply(501, "Network protocol mismatch"); /*XXX*/ 3181 else 3182 epsv_protounsupp("Network protocol mismatch"); 3183 3184 return; 3185 } 3186 3187 if (pdata >= 0) 3188 close(pdata); 3189 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0); 3190 if (pdata < 0) { 3191 perror_reply(425, "Can't open passive connection"); 3192 return; 3193 } 3194 pasv_addr = ctrl_addr; 3195 if (bind_pasv_addr() < 0) 3196 goto pasv_error; 3197 len = pasv_addr.su_len; 3198 if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0) 3199 goto pasv_error; 3200 pasv_addr.su_len = len; 3201 if (listen(pdata, 1) < 0) 3202 goto pasv_error; 3203 p = (char *) &pasv_addr.su_port; 3204 3205 #define UC(b) (((int) b) & 0xff) 3206 3207 if (strcmp(cmd, "LPSV") == 0) { 3208 struct sockinet *advert; 3209 3210 if (curclass.advertise.su_len != 0) 3211 advert = &curclass.advertise; 3212 else 3213 advert = &pasv_addr; 3214 switch (advert->su_family) { 3215 case AF_INET: 3216 a = (char *) &advert->su_addr; 3217 reply(228, 3218 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)", 3219 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]), 3220 2, UC(p[0]), UC(p[1])); 3221 return; 3222 #ifdef INET6 3223 case AF_INET6: 3224 a = (char *) &advert->su_6addr; 3225 reply(228, 3226 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)", 3227 6, 16, 3228 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]), 3229 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]), 3230 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]), 3231 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]), 3232 2, UC(p[0]), UC(p[1])); 3233 return; 3234 #endif 3235 } 3236 #undef UC 3237 } else if (strcmp(cmd, "EPSV") == 0) { 3238 switch (pasv_addr.su_family) { 3239 case AF_INET: 3240 #ifdef INET6 3241 case AF_INET6: 3242 #endif 3243 reply(229, "Entering Extended Passive Mode (|||%d|)", 3244 ntohs(pasv_addr.su_port)); 3245 return; 3246 } 3247 } else { 3248 /* more proper error code? */ 3249 } 3250 3251 pasv_error: 3252 (void) close(pdata); 3253 pdata = -1; 3254 perror_reply(425, "Can't open passive connection"); 3255 return; 3256 } 3257 3258 int 3259 extended_port(const char *arg) 3260 { 3261 char *tmp = NULL; 3262 char *result[3]; 3263 char *p, *q; 3264 char delim; 3265 struct addrinfo hints; 3266 struct addrinfo *res = NULL; 3267 int i; 3268 unsigned long proto; 3269 3270 tmp = ftpd_strdup(arg); 3271 p = tmp; 3272 delim = p[0]; 3273 p++; 3274 memset(result, 0, sizeof(result)); 3275 for (i = 0; i < 3; i++) { 3276 q = strchr(p, delim); 3277 if (!q || *q != delim) 3278 goto parsefail; 3279 *q++ = '\0'; 3280 result[i] = p; 3281 p = q; 3282 } 3283 3284 /* some more sanity checks */ 3285 errno = 0; 3286 p = NULL; 3287 (void)strtoul(result[2], &p, 10); 3288 if (errno || !*result[2] || *p) 3289 goto parsefail; 3290 errno = 0; 3291 p = NULL; 3292 proto = strtoul(result[0], &p, 10); 3293 if (errno || !*result[0] || *p) 3294 goto protounsupp; 3295 3296 memset(&hints, 0, sizeof(hints)); 3297 hints.ai_family = epsvproto2af((int)proto); 3298 if (hints.ai_family < 0) 3299 goto protounsupp; 3300 hints.ai_socktype = SOCK_STREAM; 3301 hints.ai_flags = AI_NUMERICHOST; 3302 if (getaddrinfo(result[1], result[2], &hints, &res)) 3303 goto parsefail; 3304 if (res->ai_next) 3305 goto parsefail; 3306 if (sizeof(data_dest) < res->ai_addrlen) 3307 goto parsefail; 3308 memcpy(&data_dest.si_su, res->ai_addr, res->ai_addrlen); 3309 data_dest.su_len = res->ai_addrlen; 3310 #ifdef INET6 3311 if (his_addr.su_family == AF_INET6 && 3312 data_dest.su_family == AF_INET6) { 3313 /* XXX: more sanity checks! */ 3314 data_dest.su_scope_id = his_addr.su_scope_id; 3315 } 3316 #endif 3317 3318 if (tmp != NULL) 3319 free(tmp); 3320 if (res) 3321 freeaddrinfo(res); 3322 return 0; 3323 3324 parsefail: 3325 reply(500, "Invalid argument, rejected."); 3326 usedefault = 1; 3327 if (tmp != NULL) 3328 free(tmp); 3329 if (res) 3330 freeaddrinfo(res); 3331 return -1; 3332 3333 protounsupp: 3334 epsv_protounsupp("Protocol not supported"); 3335 usedefault = 1; 3336 if (tmp != NULL) 3337 free(tmp); 3338 return -1; 3339 } 3340 3341 /* 3342 * 522 Protocol not supported (proto,...) 3343 * as we assume address family for control and data connections are the same, 3344 * we do not return the list of address families we support - instead, we 3345 * return the address family of the control connection. 3346 */ 3347 void 3348 epsv_protounsupp(const char *message) 3349 { 3350 int proto; 3351 3352 proto = af2epsvproto(ctrl_addr.su_family); 3353 if (proto < 0) 3354 reply(501, "%s", message); /* XXX */ 3355 else 3356 reply(522, "%s, use (%d)", message, proto); 3357 } 3358 3359 /* 3360 * Generate unique name for file with basename "local". 3361 * The file named "local" is already known to exist. 3362 * Generates failure reply on error. 3363 * 3364 * XXX: this function should under go changes similar to 3365 * the mktemp(3)/mkstemp(3) changes. 3366 */ 3367 static char * 3368 gunique(const char *local) 3369 { 3370 static char new[MAXPATHLEN]; 3371 struct stat st; 3372 char *cp; 3373 int count; 3374 3375 cp = strrchr(local, '/'); 3376 if (cp) 3377 *cp = '\0'; 3378 if (stat(cp ? local : ".", &st) < 0) { 3379 perror_reply(553, cp ? local : "."); 3380 return (NULL); 3381 } 3382 if (cp) 3383 *cp = '/'; 3384 for (count = 1; count < 100; count++) { 3385 (void)snprintf(new, sizeof(new) - 1, "%s.%d", local, count); 3386 if (stat(new, &st) < 0) 3387 return (new); 3388 } 3389 reply(452, "Unique file name cannot be created."); 3390 return (NULL); 3391 } 3392 3393 /* 3394 * Format and send reply containing system error number. 3395 */ 3396 void 3397 perror_reply(int code, const char *string) 3398 { 3399 int save_errno; 3400 3401 save_errno = errno; 3402 reply(code, "%s: %s.", string, strerror(errno)); 3403 errno = save_errno; 3404 } 3405 3406 static char *onefile[] = { 3407 NULL, 3408 0 3409 }; 3410 3411 void 3412 send_file_list(const char *whichf) 3413 { 3414 struct stat st; 3415 DIR *dirp; 3416 struct dirent *dir; 3417 FILE *volatile dout; 3418 char **volatile dirlist; 3419 char *dirname, *p; 3420 char *notglob; 3421 int volatile simple; 3422 int volatile freeglob; 3423 glob_t gl; 3424 3425 dirp = NULL; 3426 dout = NULL; 3427 notglob = NULL; 3428 simple = 0; 3429 freeglob = 0; 3430 urgflag = 0; 3431 3432 p = NULL; 3433 if (strpbrk(whichf, "~{[*?") != NULL) { 3434 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE|GLOB_LIMIT; 3435 3436 memset(&gl, 0, sizeof(gl)); 3437 freeglob = 1; 3438 if (glob(whichf, flags, 0, &gl)) { 3439 reply(450, "Not found"); 3440 goto cleanup_send_file_list; 3441 } else if (gl.gl_pathc == 0) { 3442 errno = ENOENT; 3443 perror_reply(450, whichf); 3444 goto cleanup_send_file_list; 3445 } 3446 dirlist = gl.gl_pathv; 3447 } else { 3448 notglob = ftpd_strdup(whichf); 3449 onefile[0] = notglob; 3450 dirlist = onefile; 3451 simple = 1; 3452 } 3453 /* XXX: } for vi sm */ 3454 3455 while ((dirname = *dirlist++) != NULL) { 3456 int trailingslash = 0; 3457 3458 if (stat(dirname, &st) < 0) { 3459 /* 3460 * If user typed "ls -l", etc, and the client 3461 * used NLST, do what the user meant. 3462 */ 3463 /* XXX: nuke this support? */ 3464 if (dirname[0] == '-' && *dirlist == NULL && 3465 transflag == 0) { 3466 const char *argv[] = { INTERNAL_LS, "", NULL }; 3467 3468 argv[1] = dirname; 3469 retrieve(argv, dirname); 3470 goto cleanup_send_file_list; 3471 } 3472 perror_reply(450, whichf); 3473 goto cleanup_send_file_list; 3474 } 3475 3476 if (S_ISREG(st.st_mode)) { 3477 /* 3478 * XXXRFC: 3479 * should we follow RFC959 and not work 3480 * for non directories? 3481 */ 3482 if (dout == NULL) { 3483 dout = dataconn("file list", (off_t)-1, "w"); 3484 if (dout == NULL) 3485 goto cleanup_send_file_list; 3486 transflag = 1; 3487 } 3488 cprintf(dout, "%s%s\n", dirname, 3489 type == TYPE_A ? "\r" : ""); 3490 continue; 3491 } else if (!S_ISDIR(st.st_mode)) 3492 continue; 3493 3494 if (dirname[strlen(dirname) - 1] == '/') 3495 trailingslash++; 3496 3497 if ((dirp = opendir(dirname)) == NULL) 3498 continue; 3499 3500 while ((dir = readdir(dirp)) != NULL) { 3501 char nbuf[MAXPATHLEN]; 3502 3503 if (urgflag && handleoobcmd()) 3504 goto cleanup_send_file_list; 3505 3506 if (ISDOTDIR(dir->d_name) || ISDOTDOTDIR(dir->d_name)) 3507 continue; 3508 3509 (void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname, 3510 trailingslash ? "" : "/", dir->d_name); 3511 3512 /* 3513 * We have to do a stat to ensure it's 3514 * not a directory or special file. 3515 */ 3516 /* 3517 * XXXRFC: 3518 * should we follow RFC959 and filter out 3519 * non files ? lukem - NO!, or not until 3520 * our ftp client uses MLS{T,D} for completion. 3521 */ 3522 if (simple || (stat(nbuf, &st) == 0 && 3523 S_ISREG(st.st_mode))) { 3524 if (dout == NULL) { 3525 dout = dataconn("file list", (off_t)-1, 3526 "w"); 3527 if (dout == NULL) 3528 goto cleanup_send_file_list; 3529 transflag = 1; 3530 } 3531 p = nbuf; 3532 if (nbuf[0] == '.' && nbuf[1] == '/') 3533 p = &nbuf[2]; 3534 cprintf(dout, "%s%s\n", p, 3535 type == TYPE_A ? "\r" : ""); 3536 } 3537 } 3538 (void) closedir(dirp); 3539 } 3540 3541 if (dout == NULL) 3542 reply(450, "No files found."); 3543 else if (ferror(dout) != 0) 3544 perror_reply(451, "Data connection"); 3545 else 3546 reply(226, "Transfer complete."); 3547 3548 cleanup_send_file_list: 3549 closedataconn(dout); 3550 transflag = 0; 3551 urgflag = 0; 3552 total_xfers++; 3553 total_xfers_out++; 3554 if (notglob) 3555 free(notglob); 3556 if (freeglob) 3557 globfree(&gl); 3558 } 3559 3560 char * 3561 conffilename(const char *s) 3562 { 3563 static char filename[MAXPATHLEN]; 3564 3565 if (*s == '/') 3566 strlcpy(filename, s, sizeof(filename)); 3567 else 3568 (void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s); 3569 return (filename); 3570 } 3571 3572 /* 3573 * logxfer -- 3574 * if logging > 1, then based on the arguments, syslog a message: 3575 * if bytes != -1 "<command> <file1> = <bytes> bytes" 3576 * else if file2 != NULL "<command> <file1> <file2>" 3577 * else "<command> <file1>" 3578 * if elapsed != NULL, append "in xxx.yyy seconds" 3579 * if error != NULL, append ": " + error 3580 * 3581 * if doxferlog != 0, bytes != -1, and command is "get", "put", 3582 * or "append", syslog and/or write a wu-ftpd style xferlog entry 3583 */ 3584 void 3585 logxfer(const char *command, off_t bytes, const char *file1, const char *file2, 3586 const struct timeval *elapsed, const char *error) 3587 { 3588 char buf[MAXPATHLEN * 2 + 100]; 3589 char realfile1[MAXPATHLEN], realfile2[MAXPATHLEN]; 3590 const char *r1, *r2; 3591 char direction; 3592 size_t len; 3593 time_t now; 3594 3595 if (logging <=1 && !doxferlog) 3596 return; 3597 3598 r1 = r2 = NULL; 3599 if ((r1 = realpath(file1, realfile1)) == NULL) 3600 r1 = file1; 3601 if (file2 != NULL) 3602 if ((r2 = realpath(file2, realfile2)) == NULL) 3603 r2 = file2; 3604 3605 /* 3606 * syslog command 3607 */ 3608 if (logging > 1) { 3609 len = snprintf(buf, sizeof(buf), "%s %s", command, r1); 3610 if (bytes != (off_t)-1) 3611 len += snprintf(buf + len, sizeof(buf) - len, 3612 " = " LLF " byte%s", (LLT) bytes, PLURAL(bytes)); 3613 else if (r2 != NULL) 3614 len += snprintf(buf + len, sizeof(buf) - len, 3615 " %s", r2); 3616 if (elapsed != NULL) 3617 len += snprintf(buf + len, sizeof(buf) - len, 3618 " in " LLF ".%.03ld seconds", 3619 (LLT)elapsed->tv_sec, 3620 (long)(elapsed->tv_usec / 1000)); 3621 if (error != NULL) 3622 len += snprintf(buf + len, sizeof(buf) - len, 3623 ": %s", error); 3624 syslog(LOG_INFO, "%s", buf); 3625 } 3626 3627 /* 3628 * syslog wu-ftpd style log entry, prefixed with "xferlog: " 3629 */ 3630 if (!doxferlog || bytes == -1) 3631 return; 3632 3633 if (strcmp(command, "get") == 0) 3634 direction = 'o'; 3635 else if (strcmp(command, "put") == 0 || strcmp(command, "append") == 0) 3636 direction = 'i'; 3637 else 3638 return; 3639 3640 time(&now); 3641 len = snprintf(buf, sizeof(buf), 3642 "%.24s " LLF " %s " LLF " %s %c %s %c %c %s FTP 0 * %c\n", 3643 3644 /* 3645 * XXX: wu-ftpd puts ' (send)' or ' (recv)' in the syslog message, and removes 3646 * the full date. This may be problematic for accurate log parsing, 3647 * given that syslog messages don't contain the full date. 3648 */ 3649 ctime(&now), 3650 (LLT) 3651 (elapsed == NULL ? 0 : elapsed->tv_sec + (elapsed->tv_usec > 0)), 3652 remotehost, 3653 (LLT) bytes, 3654 r1, 3655 type == TYPE_A ? 'a' : 'b', 3656 "_", /* XXX: take conversions into account? */ 3657 direction, 3658 3659 curclass.type == CLASS_GUEST ? 'a' : 3660 curclass.type == CLASS_CHROOT ? 'g' : 3661 curclass.type == CLASS_REAL ? 'r' : '?', 3662 3663 curclass.type == CLASS_GUEST ? pw->pw_passwd : pw->pw_name, 3664 error != NULL ? 'i' : 'c' 3665 ); 3666 3667 if ((doxferlog & 2) && xferlogfd != -1) 3668 write(xferlogfd, buf, len); 3669 if ((doxferlog & 1)) { 3670 buf[len-1] = '\n'; /* strip \n from syslog message */ 3671 syslog(LOG_INFO, "xferlog: %s", buf); 3672 } 3673 } 3674 3675 #if !defined(__minix) 3676 /* 3677 * Log the resource usage. 3678 * 3679 * XXX: more resource usage to logging? 3680 */ 3681 void 3682 logrusage(const struct rusage *rusage_before, 3683 const struct rusage *rusage_after) 3684 { 3685 struct timeval usrtime, systime; 3686 3687 if (logging <= 1) 3688 return; 3689 3690 timersub(&rusage_after->ru_utime, &rusage_before->ru_utime, &usrtime); 3691 timersub(&rusage_after->ru_stime, &rusage_before->ru_stime, &systime); 3692 syslog(LOG_INFO, LLF ".%.03ldu " LLF ".%.03lds %ld+%ldio %ldpf+%ldw", 3693 (LLT)usrtime.tv_sec, (long)(usrtime.tv_usec / 1000), 3694 (LLT)systime.tv_sec, (long)(systime.tv_usec / 1000), 3695 rusage_after->ru_inblock - rusage_before->ru_inblock, 3696 rusage_after->ru_oublock - rusage_before->ru_oublock, 3697 rusage_after->ru_majflt - rusage_before->ru_majflt, 3698 rusage_after->ru_nswap - rusage_before->ru_nswap); 3699 } 3700 #endif /* !defined(__minix) */ 3701 3702 /* 3703 * Determine if `password' is valid for user given in `pw'. 3704 * Returns 2 if password expired, 1 if otherwise failed, 0 if ok 3705 */ 3706 int 3707 checkpassword(const struct passwd *pwent, const char *password) 3708 { 3709 const char *orig; 3710 char *new; 3711 time_t change, expire, now; 3712 3713 change = expire = 0; 3714 if (pwent == NULL) 3715 return 1; 3716 3717 time(&now); 3718 orig = pwent->pw_passwd; /* save existing password */ 3719 expire = pwent->pw_expire; 3720 change = pwent->pw_change; 3721 if (change == _PASSWORD_CHGNOW) 3722 change = now; 3723 3724 if (orig[0] == '\0') /* don't allow empty passwords */ 3725 return 1; 3726 3727 new = crypt(password, orig); /* encrypt given password */ 3728 if (strcmp(new, orig) != 0) /* compare */ 3729 return 1; 3730 3731 if ((expire && now >= expire) || (change && now >= change)) 3732 return 2; /* check if expired */ 3733 3734 return 0; /* OK! */ 3735 } 3736 3737 char * 3738 ftpd_strdup(const char *s) 3739 { 3740 char *new = strdup(s); 3741 3742 if (new == NULL) 3743 fatal("Local resource failure: malloc"); 3744 /* NOTREACHED */ 3745 return (new); 3746 } 3747 3748 /* 3749 * As per fprintf(), but increment total_bytes and total_bytes_out, 3750 * by the appropriate amount. 3751 */ 3752 void 3753 cprintf(FILE *fd, const char *fmt, ...) 3754 { 3755 off_t b; 3756 va_list ap; 3757 3758 va_start(ap, fmt); 3759 b = vfprintf(fd, fmt, ap); 3760 va_end(ap); 3761 total_bytes += b; 3762 total_bytes_out += b; 3763 } 3764 3765 #ifdef USE_PAM 3766 /* 3767 * the following code is stolen from imap-uw PAM authentication module and 3768 * login.c 3769 */ 3770 typedef struct { 3771 const char *uname; /* user name */ 3772 int triedonce; /* if non-zero, tried before */ 3773 } ftpd_cred_t; 3774 3775 static int 3776 auth_conv(int num_msg, const struct pam_message **msg, 3777 struct pam_response **resp, void *appdata) 3778 { 3779 int i, ret; 3780 size_t n; 3781 ftpd_cred_t *cred = (ftpd_cred_t *) appdata; 3782 struct pam_response *myreply; 3783 char pbuf[FTP_BUFLEN]; 3784 3785 if (num_msg <= 0 || num_msg > PAM_MAX_NUM_MSG) 3786 return (PAM_CONV_ERR); 3787 myreply = calloc(num_msg, sizeof *myreply); 3788 if (myreply == NULL) 3789 return PAM_BUF_ERR; 3790 3791 for (i = 0; i < num_msg; i++) { 3792 myreply[i].resp_retcode = 0; 3793 myreply[i].resp = NULL; 3794 switch (msg[i]->msg_style) { 3795 case PAM_PROMPT_ECHO_ON: /* user */ 3796 myreply[i].resp = ftpd_strdup(cred->uname); 3797 /* PAM frees resp. */ 3798 break; 3799 case PAM_PROMPT_ECHO_OFF: /* authtok (password) */ 3800 /* 3801 * Only send a single 331 reply and 3802 * then expect a PASS. 3803 */ 3804 if (cred->triedonce) { 3805 syslog(LOG_ERR, 3806 "auth_conv: already performed PAM_PROMPT_ECHO_OFF"); 3807 goto fail; 3808 } 3809 cred->triedonce++; 3810 if (msg[i]->msg[0] == '\0') { 3811 (void)strlcpy(pbuf, "password", sizeof(pbuf)); 3812 } else { 3813 /* Uncapitalize msg */ 3814 (void)strlcpy(pbuf, msg[i]->msg, sizeof(pbuf)); 3815 if (isupper((unsigned char)pbuf[0])) 3816 pbuf[0] = tolower( 3817 (unsigned char)pbuf[0]); 3818 /* Remove trailing ':' and whitespace */ 3819 n = strlen(pbuf); 3820 while (n-- > 0) { 3821 if (isspace((unsigned char)pbuf[n]) || 3822 pbuf[n] == ':') 3823 pbuf[n] = '\0'; 3824 else 3825 break; 3826 } 3827 } 3828 /* Send reply, wait for a response. */ 3829 reply(331, "User %s accepted, provide %s.", 3830 cred->uname, pbuf); 3831 (void) alarm(curclass.timeout); 3832 ret = get_line(pbuf, sizeof(pbuf)-1, stdin); 3833 (void) alarm(0); 3834 if (ret == -1) { 3835 reply(221, "You could at least say goodbye."); 3836 dologout(0); 3837 } else if (ret == -2) { 3838 /* XXX: should we do this reply(-530, ..) ? */ 3839 reply(-530, "Command too long."); 3840 goto fail; 3841 } 3842 /* Ensure it is PASS */ 3843 if (strncasecmp(pbuf, "PASS ", 5) != 0) { 3844 syslog(LOG_ERR, 3845 "auth_conv: unexpected reply '%.4s'", pbuf); 3846 /* XXX: should we do this reply(-530, ..) ? */ 3847 reply(-530, "Unexpected reply '%.4s'.", pbuf); 3848 goto fail; 3849 } 3850 /* Strip CRLF from "PASS" reply */ 3851 n = strlen(pbuf); 3852 while (--n >= 5 && 3853 (pbuf[n] == '\r' || pbuf[n] == '\n')) 3854 pbuf[n] = '\0'; 3855 /* Copy password into reply */ 3856 myreply[i].resp = ftpd_strdup(pbuf+5); 3857 /* PAM frees resp. */ 3858 break; 3859 case PAM_TEXT_INFO: 3860 case PAM_ERROR_MSG: 3861 break; 3862 default: /* unknown message style */ 3863 goto fail; 3864 } 3865 } 3866 3867 *resp = myreply; 3868 return PAM_SUCCESS; 3869 3870 fail: 3871 free(myreply); 3872 *resp = NULL; 3873 return PAM_CONV_ERR; 3874 } 3875 3876 /* 3877 * Attempt to authenticate the user using PAM. Returns 0 if the user is 3878 * authenticated, or 1 if not authenticated. If some sort of PAM system 3879 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this 3880 * function returns -1. This can be used as an indication that we should 3881 * fall back to a different authentication mechanism. 3882 * pw maybe be updated to a new user if PAM_USER changes from curname. 3883 */ 3884 static int 3885 auth_pam(void) 3886 { 3887 const char *tmpl_user; 3888 const void *item; 3889 int rval; 3890 int e; 3891 ftpd_cred_t auth_cred = { curname, 0 }; 3892 struct pam_conv conv = { &auth_conv, &auth_cred }; 3893 3894 e = pam_start("ftpd", curname, &conv, &pamh); 3895 if (e != PAM_SUCCESS) { 3896 /* 3897 * In OpenPAM, it's OK to pass NULL to pam_strerror() 3898 * if context creation has failed in the first place. 3899 */ 3900 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e)); 3901 return -1; 3902 } 3903 3904 e = pam_set_item(pamh, PAM_RHOST, remotehost); 3905 if (e != PAM_SUCCESS) { 3906 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s", 3907 pam_strerror(pamh, e)); 3908 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) { 3909 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e)); 3910 } 3911 pamh = NULL; 3912 return -1; 3913 } 3914 3915 e = pam_set_item(pamh, PAM_SOCKADDR, &his_addr); 3916 if (e != PAM_SUCCESS) { 3917 syslog(LOG_ERR, "pam_set_item(PAM_SOCKADDR): %s", 3918 pam_strerror(pamh, e)); 3919 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) { 3920 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e)); 3921 } 3922 pamh = NULL; 3923 return -1; 3924 } 3925 3926 e = pam_authenticate(pamh, 0); 3927 if (ftpd_debug) 3928 syslog(LOG_DEBUG, "pam_authenticate: user '%s' returned %d", 3929 curname, e); 3930 switch (e) { 3931 case PAM_SUCCESS: 3932 /* 3933 * With PAM we support the concept of a "template" 3934 * user. The user enters a login name which is 3935 * authenticated by PAM, usually via a remote service 3936 * such as RADIUS or TACACS+. If authentication 3937 * succeeds, a different but related "template" name 3938 * is used for setting the credentials, shell, and 3939 * home directory. The name the user enters need only 3940 * exist on the remote authentication server, but the 3941 * template name must be present in the local password 3942 * database. 3943 * 3944 * This is supported by two various mechanisms in the 3945 * individual modules. However, from the application's 3946 * point of view, the template user is always passed 3947 * back as a changed value of the PAM_USER item. 3948 */ 3949 if ((e = pam_get_item(pamh, PAM_USER, &item)) == 3950 PAM_SUCCESS) { 3951 tmpl_user = (const char *) item; 3952 if (pw == NULL 3953 || strcmp(pw->pw_name, tmpl_user) != 0) { 3954 pw = sgetpwnam(tmpl_user); 3955 if (ftpd_debug) 3956 syslog(LOG_DEBUG, 3957 "auth_pam: PAM changed " 3958 "user from '%s' to '%s'", 3959 curname, pw->pw_name); 3960 (void)strlcpy(curname, pw->pw_name, 3961 curname_len); 3962 } 3963 } else 3964 syslog(LOG_ERR, "Couldn't get PAM_USER: %s", 3965 pam_strerror(pamh, e)); 3966 rval = 0; 3967 break; 3968 3969 case PAM_AUTH_ERR: 3970 case PAM_USER_UNKNOWN: 3971 case PAM_MAXTRIES: 3972 rval = 1; 3973 break; 3974 3975 default: 3976 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e)); 3977 rval = -1; 3978 break; 3979 } 3980 3981 if (rval == 0) { 3982 e = pam_acct_mgmt(pamh, 0); 3983 if (e != PAM_SUCCESS) { 3984 syslog(LOG_ERR, "pam_acct_mgmt: %s", 3985 pam_strerror(pamh, e)); 3986 rval = 1; 3987 } 3988 } 3989 3990 if (rval != 0) { 3991 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) { 3992 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e)); 3993 } 3994 pamh = NULL; 3995 } 3996 return rval; 3997 } 3998 3999 #endif /* USE_PAM */ 4000