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