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