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