1 /* $NetBSD: ftpd.c,v 1.187 2008/09/13 03:30:35 lukem Exp $ */
4 * Copyright (c) 1997-2004 The NetBSD Foundation, Inc.
7 * This code is derived from software contributed to The NetBSD Foundation
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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.
40 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
41 * The Regents of the University of California. All rights reserved.
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
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.
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
69 * Copyright (C) 1997 and 1998 WIDE Project.
70 * All rights reserved.
72 * Redistribution and use in source and binary forms, with or without
73 * modification, are permitted provided that the following conditions
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.
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
97 #include <sys/cdefs.h>
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 */
106 static char sccsid[] = "@(#)ftpd.c 8.5 (Berkeley) 4/28/95";
108 __RCSID("$NetBSD: ftpd.c,v 1.176 2006/05/09 20:18:06 mrg Exp $");
110 __FBSDID("$FreeBSD$");
111 #endif /* not lint */
116 #include <sys/param.h>
117 #include <sys/stat.h>
118 #include <sys/ioctl.h>
119 #include <sys/socket.h>
120 #include <sys/wait.h>
121 #include <sys/mman.h>
122 #include <sys/resource.h>
124 #include <netinet/in.h>
125 #include <netinet/in_systm.h>
126 #include <netinet/ip.h>
129 #include <arpa/ftp.h>
130 #include <arpa/inet.h>
131 #include <arpa/telnet.h>
166 #include <krb5/krb5.h>
170 #include <login_cap.h>
174 #include <security/pam_appl.h>
179 #include "pathnames.h"
182 #include "nbsd_pidfile.h"
184 volatile sig_atomic_t transflag;
185 volatile sig_atomic_t urgflag;
190 int stru; /* avoid C keyword */
192 int dataport; /* use specific data port */
193 int dopidfile; /* maintain pid file */
194 int doutmp; /* update utmp file */
195 int dowtmp; /* update wtmp file */
196 int doxferlog; /* syslog/write wu-ftpd style xferlog entries */
197 int xferlogfd; /* fd to write wu-ftpd xferlog entries to */
198 int dropprivs; /* if privileges should or have been dropped */
199 int mapped; /* IPv4 connection on AF_INET6 socket */
202 static char ttyline[20];
205 static int auth_pam(struct passwd **, const char *);
206 pam_handle_t *pamh = NULL;
210 static struct utmp utmp; /* for utmp */
213 static struct utmpx utmpx; /* for utmpx */
216 static const char *anondir = NULL;
217 static const char *confdir = _DEFAULT_CONFDIR;
219 static char *curname; /* current USER name */
220 static size_t curname_len; /* length of curname (include NUL) */
222 #if defined(KERBEROS) || defined(KERBEROS5)
225 char *krbtkfile_env = NULL;
227 int login_krb5_forwardable_tgt = 0;
233 * Timeout intervals for retrying connections
234 * to hosts that don't accept PORT cmds. This
235 * is a kludge, but given the problems with TCP...
237 #define SWAITMAX 90 /* wait at most 90 seconds */
238 #define SWAITINT 5 /* interval between retries */
240 int swaitmax = SWAITMAX;
241 int swaitint = SWAITINT;
245 SS_ABORTED, /* transfer aborted */
246 SS_NO_TRANSFER, /* no transfer made yet */
247 SS_FILE_ERROR, /* file read error */
248 SS_DATA_ERROR /* data send error */
253 static struct opie opiedata;
254 static char opieprompt[OPIE_CHALLENGE_MAX+1];
258 static int bind_pasv_addr(void);
259 static int checkuser(const char *, const char *, int, int, char **);
260 static int checkaccess(const char *);
261 static int checkpassword(const struct passwd *, const char *);
262 static void end_login(void);
263 static FILE *getdatasock(const char *);
264 static char *gunique(const char *);
265 static void login_utmp(const char *, const char *, const char *,
267 static void logremotehost(struct sockinet *);
268 static void lostconn(int);
269 static void toolong(int);
270 static void sigquit(int);
271 static void sigurg(int);
272 static int handleoobcmd(void);
273 static int receive_data(FILE *, FILE *);
274 static int send_data(FILE *, FILE *, const struct stat *, int);
275 static struct passwd *sgetpwnam(const char *);
276 static int write_data(int, char *, size_t, off_t *, struct timeval *,
278 static enum send_status
279 send_data_with_read(int, int, const struct stat *, int);
280 static enum send_status
281 send_data_with_mmap(int, int, const struct stat *, int);
282 static void logrusage(const struct rusage *, const struct rusage *);
283 static void logout_utmp(void);
285 int main(int, char *[]);
287 #if defined(KERBEROS)
288 int klogin(struct passwd *, char *, char *, char *);
291 #if defined(KERBEROS5)
292 int k5login(struct passwd *, char *, char *, char *);
293 void k5destroy(void);
297 main(int argc, char *argv[])
299 int ch, on = 1, tos, keepalive;
302 krb5_error_code kerror;
305 const char *xferlogname = NULL;
308 sa_family_t af = AF_UNSPEC;
317 dopidfile = 1; /* default: DO use a pid file to count users */
318 doutmp = 0; /* default: Do NOT log to utmp */
319 dowtmp = 1; /* default: DO log to wtmp */
320 doxferlog = 0; /* default: Do NOT syslog xferlog */
321 xferlogfd = -1; /* default: Do NOT write xferlog file */
330 version = FTPD_VERSION;
333 * LOG_NDELAY sets up the logging connection immediately,
334 * necessary for anonymous ftp's that chroot and can't do it later.
336 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
338 while ((ch = getopt(argc, argv,
339 "46a:c:C:Dde:h:HlL:P:qQrst:T:uUvV:wWX")) != -1) {
358 pw = sgetpwnam(optarg);
359 exit(checkaccess(optarg) ? 0 : 1);
367 case 'v': /* deprecated */
376 strlcpy(hostname, optarg, sizeof(hostname));
380 if (gethostname(hostname, sizeof(hostname)) == -1)
382 hostname[sizeof(hostname) - 1] = '\0';
386 logging++; /* > 1 == extra logging */
390 xferlogname = optarg;
396 l = strtol(optarg, &p, 10);
397 if (errno || *optarg == '\0' || *p != '\0' ||
398 l < IPPORT_RESERVED ||
399 l > IPPORT_ANONMAX) {
400 syslog(LOG_WARNING, "Invalid dataport %s",
426 "-%c has been deprecated in favour of ftpd.conf",
439 if (EMPTYSTR(optarg) || strcmp(optarg, "-") == 0)
442 version = ftpd_strdup(optarg);
458 if (optopt == 'a' || optopt == 'C')
460 syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
464 if (EMPTYSTR(confdir))
465 confdir = _DEFAULT_CONFDIR;
476 l = sysconf(_SC_LOGIN_NAME_MAX);
477 if (l == -1 && errno != 0) {
478 syslog(LOG_ERR, "sysconf _SC_LOGIN_NAME_MAX: %m");
481 syslog(LOG_WARNING, "using conservative LOGIN_NAME_MAX value");
482 curname_len = _POSIX_LOGIN_NAME_MAX;
484 curname_len = (size_t)l;
485 curname = malloc(curname_len);
486 if (curname == NULL) {
487 syslog(LOG_ERR, "malloc: %m");
493 int error, fd, i, n, *socks;
495 struct addrinfo hints, *res, *res0;
497 if (daemon(1, 0) == -1) {
498 syslog(LOG_ERR, "failed to daemonize: %m");
501 (void)memset(&sa, 0, sizeof(sa));
502 sa.sa_handler = SIG_IGN;
503 sa.sa_flags = SA_NOCLDWAIT;
504 sigemptyset(&sa.sa_mask);
505 (void)sigaction(SIGCHLD, &sa, NULL);
507 (void)memset(&hints, 0, sizeof(hints));
508 hints.ai_flags = AI_PASSIVE;
509 hints.ai_family = af;
510 hints.ai_socktype = SOCK_STREAM;
511 error = getaddrinfo(NULL, "ftp", &hints, &res0);
513 syslog(LOG_ERR, "getaddrinfo: %s", gai_strerror(error));
517 for (n = 0, res = res0; res != NULL; res = res->ai_next)
520 syslog(LOG_ERR, "no addresses available");
523 socks = malloc(n * sizeof(int));
524 fds = malloc(n * sizeof(struct pollfd));
525 if (socks == NULL || fds == NULL) {
526 syslog(LOG_ERR, "malloc: %m");
530 for (n = 0, res = res0; res != NULL; res = res->ai_next) {
531 socks[n] = socket(res->ai_family, res->ai_socktype,
535 (void)setsockopt(socks[n], SOL_SOCKET, SO_REUSEADDR,
537 if (bind(socks[n], res->ai_addr, res->ai_addrlen)
539 (void)close(socks[n]);
542 if (listen(socks[n], 12) == -1) {
543 (void)close(socks[n]);
547 fds[n].fd = socks[n];
548 fds[n].events = POLLIN;
552 syslog(LOG_ERR, "%m");
557 if (pidfile(NULL) == -1)
558 syslog(LOG_ERR, "failed to write a pid file: %m");
561 if (poll(fds, n, INFTIM) == -1) {
564 syslog(LOG_ERR, "poll: %m");
567 for (i = 0; i < n; i++) {
568 if (fds[i].revents & POLLIN) {
569 fd = accept(fds[i].fd, NULL, NULL);
571 syslog(LOG_ERR, "accept: %m");
576 syslog(LOG_ERR, "fork: %m");
587 (void)dup2(fd, STDIN_FILENO);
588 (void)dup2(fd, STDOUT_FILENO);
589 (void)dup2(fd, STDERR_FILENO);
590 for (i = 0; i < n; i++)
591 (void)close(socks[i]);
594 memset((char *)&his_addr, 0, sizeof(his_addr));
595 addrlen = sizeof(his_addr.si_su);
596 if (getpeername(0, (struct sockaddr *)&his_addr.si_su, &addrlen) < 0) {
597 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
600 his_addr.su_len = addrlen;
601 memset((char *)&ctrl_addr, 0, sizeof(ctrl_addr));
602 addrlen = sizeof(ctrl_addr.si_su);
603 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
604 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
607 ctrl_addr.su_len = addrlen;
609 if (his_addr.su_family == AF_INET6
610 && IN6_IS_ADDR_V4MAPPED(&his_addr.su_6addr)) {
613 * IPv4 control connection arrived to AF_INET6 socket.
614 * I hate to do this, but this is the easiest solution.
616 * The assumption is untrue on SIIT environment.
618 struct sockinet tmp_addr;
619 const int off = sizeof(struct in6_addr) - sizeof(struct in_addr);
622 memset(&his_addr, 0, sizeof(his_addr));
623 his_addr.su_family = AF_INET;
624 his_addr.su_len = sizeof(his_addr.si_su.su_sin);
625 memcpy(&his_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off],
626 sizeof(his_addr.su_addr));
627 his_addr.su_port = tmp_addr.su_port;
629 tmp_addr = ctrl_addr;
630 memset(&ctrl_addr, 0, sizeof(ctrl_addr));
631 ctrl_addr.su_family = AF_INET;
632 ctrl_addr.su_len = sizeof(ctrl_addr.si_su.su_sin);
633 memcpy(&ctrl_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off],
634 sizeof(ctrl_addr.su_addr));
635 ctrl_addr.su_port = tmp_addr.su_port;
637 while (fgets(line, sizeof(line), fd) != NULL) {
638 if ((cp = strchr(line, '\n')) != NULL)
640 reply(-530, "%s", line);
642 (void) fflush(stdout);
645 "Connection from IPv4 mapped address is not supported.");
654 if (!mapped && his_addr.su_family == AF_INET) {
655 tos = IPTOS_LOWDELAY;
656 if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos,
658 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
661 /* if the hostname hasn't been given, attempt to determine it */
662 if (hostname[0] == '\0') {
663 if (getnameinfo((struct sockaddr *)&ctrl_addr.si_su,
664 ctrl_addr.su_len, hostname, sizeof(hostname), NULL, 0, 0)
666 (void)gethostname(hostname, sizeof(hostname));
667 hostname[sizeof(hostname) - 1] = '\0';
670 /* set this here so klogin can use it... */
671 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
673 (void) freopen(_PATH_DEVNULL, "w", stderr);
675 memset(&sa, 0, sizeof(sa));
676 sa.sa_handler = SIG_DFL;
677 sa.sa_flags = SA_RESTART;
678 sigemptyset(&sa.sa_mask);
679 (void) sigaction(SIGCHLD, &sa, NULL);
681 sa.sa_handler = sigquit;
682 sa.sa_flags = SA_RESTART;
683 sigfillset(&sa.sa_mask); /* block all sigs in these handlers */
684 (void) sigaction(SIGHUP, &sa, NULL);
685 (void) sigaction(SIGINT, &sa, NULL);
686 (void) sigaction(SIGQUIT, &sa, NULL);
687 (void) sigaction(SIGTERM, &sa, NULL);
688 sa.sa_handler = lostconn;
689 (void) sigaction(SIGPIPE, &sa, NULL);
690 sa.sa_handler = toolong;
691 (void) sigaction(SIGALRM, &sa, NULL);
692 sa.sa_handler = sigurg;
693 (void) sigaction(SIGURG, &sa, NULL);
695 /* Try to handle urgent data inline */
697 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
698 syslog(LOG_WARNING, "setsockopt: %m");
700 /* Set keepalives on the socket to detect dropped connections. */
703 if (setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepalive,
705 syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
709 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
710 syslog(LOG_WARNING, "fcntl F_SETOWN: %m");
712 logremotehost(&his_addr);
714 * Set up default state
725 kerror = krb5_init_context(&kcontext);
727 syslog(LOG_ERR, "%s when initializing Kerberos context",
728 error_message(kerror));
731 #endif /* KERBEROS5 */
734 curclass.timeout = 300; /* 5 minutes, as per login(1) */
735 curclass.type = CLASS_REAL;
737 /* If logins are disabled, print out the message. */
738 if (display_file(_PATH_NOLOGIN, 530)) {
739 reply(530, "System not available.");
742 (void)display_file(conffilename(_NAME_FTPWELCOME), 220);
743 /* reply(220,) must follow */
744 if (EMPTYSTR(version))
745 reply(220, "%s FTP server ready.", hostname);
747 reply(220, "%s FTP server (%s) ready.", hostname, version);
749 if (xferlogname != NULL) {
750 xferlogfd = open(xferlogname, O_WRONLY | O_APPEND | O_CREAT,
753 syslog(LOG_WARNING, "open xferlog `%s': %m",
768 syslog(LOG_DEBUG, "lost connection");
778 "Timeout (" LLF " seconds): closing control connection.",
779 (LLT)curclass.timeout);
781 syslog(LOG_INFO, "User %s timed out after " LLF " seconds",
782 (pw ? pw->pw_name : "unknown"), (LLT)curclass.timeout);
791 syslog(LOG_DEBUG, "got signal %d", signo);
804 * Save the result of a getpwnam. Used for USER command, since
805 * the data returned must not be clobbered by any other command
808 static struct passwd *
809 sgetpwnam(const char *name)
811 static struct passwd save;
814 if ((p = getpwnam(name)) == NULL)
817 free((char *)save.pw_name);
818 memset(save.pw_passwd, 0, strlen(save.pw_passwd));
819 free((char *)save.pw_passwd);
820 free((char *)save.pw_gecos);
821 free((char *)save.pw_dir);
822 free((char *)save.pw_shell);
825 save.pw_name = ftpd_strdup(p->pw_name);
826 save.pw_passwd = ftpd_strdup(p->pw_passwd);
827 save.pw_gecos = ftpd_strdup(p->pw_gecos);
828 save.pw_dir = ftpd_strdup(p->pw_dir);
829 save.pw_shell = ftpd_strdup(p->pw_shell);
833 static int login_attempts; /* number of failed login attempts */
834 static int askpasswd; /* had USER command, ask for PASSwd */
835 static int permitted; /* USER permitted */
839 * Sets global passwd pointer pw if named account exists and is acceptable;
840 * sets askpasswd if a PASS command is expected. If logged in previously,
841 * need to reset state. If name is "ftp" or "anonymous", the name is not in
842 * _NAME_FTPUSERS, and ftp account exists, set guest and pw, then just return.
843 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
844 * requesting login privileges. Disallow anyone who does not have a standard
845 * shell as returned by getusershell(). Disallow anyone mentioned in the file
846 * _NAME_FTPUSERS to allow people such as root and uucp to be avoided.
849 user(const char *name)
853 login_cap_t *lc = NULL;
858 switch (curclass.type) {
860 reply(530, "Can't change user from guest login.");
863 reply(530, "Can't change user from chroot user.");
867 reply(530, "Can't change user.");
877 #if defined(KERBEROS)
880 #if defined(KERBEROS5)
884 curclass.type = CLASS_REAL;
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);
895 curclass.type = CLASS_GUEST;
898 "Guest login ok, type your name as password.");
903 "ANONYMOUS FTP LOGIN REFUSED FROM %s",
910 pw = sgetpwnam(name);
912 strlcpy(curname, name, curname_len);
914 /* check user in /etc/ftpusers, and setup class */
915 permitted = checkuser(_NAME_FTPUSERS, curname, 1, 0, &class);
917 /* check user in /etc/ftpchroot */
918 lc = login_getpwclass(pw);
919 if (checkuser(_NAME_FTPCHROOT, curname, 0, 0, NULL)
920 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
921 || login_getcapbool(lc, "ftp-chroot", 0)
924 if (curclass.type == CLASS_GUEST) {
926 "Can't change guest user to chroot class; remove entry in %s",
930 curclass.type = CLASS_CHROOT;
932 /* determine default class */
934 switch (curclass.type) {
936 class = ftpd_strdup("guest");
939 class = ftpd_strdup("chroot");
942 class = ftpd_strdup("real");
945 syslog(LOG_ERR, "unknown curclass.type %d; aborting",
950 /* parse ftpd.conf, setting up various parameters */
952 /* if not guest user, check for valid shell */
956 const char *cp, *shell;
958 if ((shell = pw->pw_shell) == NULL || *shell == 0)
959 shell = _PATH_BSHELL;
960 while ((cp = getusershell()) != NULL)
961 if (strcmp(cp, shell) == 0)
964 if (cp == NULL && curclass.type != CLASS_GUEST)
968 /* deny quickly (after USER not PASS) if requested */
969 if (CURCLASS_FLAGS_ISSET(denyquick) && !permitted) {
970 reply(530, "User %s may not use FTP.", curname);
972 syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
973 remotehost, curname);
978 /* if haven't asked yet (i.e, not anon), ask now */
982 if (skey_haskey(curname) == 0) {
985 myskey = skey_keyinfo(curname);
986 reply(331, "Password [ %s ] required for %s.",
987 myskey ? myskey : "error getting challenge",
992 if (opiechallenge(&opiedata, (char *)curname, opieprompt) ==
994 pwok = (pw != NULL) &&
995 opieaccessfile(remotehost) &&
996 opiealways(pw->pw_dir);
997 reply(331, "Response to %s %s for %s.",
998 opieprompt, pwok ? "requested" : "required",
1002 reply(331, "Password required for %s.", curname);
1010 * Delay before reading passwd after first failed
1011 * attempt to slow down passwd-guessing programs.
1014 sleep((unsigned) login_attempts);
1021 * Determine whether something is to happen (allow access, chroot)
1022 * for a user. Each line is a shell-style glob followed by
1025 * For backward compatibility, `allow' and `deny' are synonymns
1026 * for `yes' and `no', respectively.
1028 * Each glob is matched against the username in turn, and the first
1029 * match found is used. If no match is found, the result is the
1030 * argument `def'. If a match is found but without and explicit
1031 * `yes'/`no', the result is the opposite of def.
1033 * If the file doesn't exist at all, the result is the argument
1036 * Any line starting with `#' is considered a comment and ignored.
1038 * Returns 0 if the user is denied, or 1 if they are allowed.
1040 * NOTE: needs struct passwd *pw setup before use.
1043 checkuser(const char *fname, const char *name, int def, int nofile,
1048 char *word, *perm, *class, *buf, *p;
1052 if (retclass != NULL)
1054 if ((fd = fopen(conffilename(fname), "r")) == NULL)
1059 (buf = fparseln(fd, &len, &line, NULL, FPARSELN_UNESCCOMM |
1060 FPARSELN_UNESCCONT | FPARSELN_UNESCESC)) != NULL;
1061 free(buf), buf = NULL) {
1062 word = perm = class = NULL;
1066 if (p[len - 1] == '\n')
1076 if (!EMPTYSTR(class)) {
1077 if (strcasecmp(class, "all") == 0 ||
1078 strcasecmp(class, "none") == 0) {
1080 "%s line %d: illegal user-defined class `%s' - skipping entry",
1081 fname, (int)line, class);
1086 /* have a host specifier */
1087 if ((p = strchr(word, '@')) != NULL) {
1088 unsigned long net, mask, addr;
1092 /* check against network or CIDR */
1093 if (isdigit((unsigned char)*p) &&
1094 (bits = inet_net_pton(AF_INET, p,
1095 &net, sizeof(net))) != -1) {
1097 mask = 0xffffffffU << (32 - bits);
1098 addr = ntohl(his_addr.su_addr.s_addr);
1099 if ((addr & mask) != net)
1102 /* check against hostname glob */
1103 } else if (fnmatch(p, remotehost, FNM_CASEFOLD) != 0)
1107 /* have a group specifier */
1108 if ((p = strchr(word, ':')) != NULL) {
1110 int gsize, i, found;
1113 continue; /* no match for unknown user */
1118 ng = realloc(groups, gsize * sizeof(gid_t));
1121 "Local resource failure: realloc");
1123 } while (getgrouplist(pw->pw_name, pw->pw_gid,
1124 groups, &gsize) == -1);
1126 for (i = 0; i < gsize; i++) {
1129 if ((g = getgrgid(groups[i])) == NULL)
1131 if (fnmatch(p, g->gr_name, 0) == 0) {
1141 /* check against username glob */
1142 if (fnmatch(word, name, 0) != 0)
1146 ((strcasecmp(perm, "allow") == 0) ||
1147 (strcasecmp(perm, "yes") == 0)))
1149 else if (perm != NULL &&
1150 ((strcasecmp(perm, "deny") == 0) ||
1151 (strcasecmp(perm, "no") == 0)))
1155 if (!EMPTYSTR(class) && retclass != NULL)
1156 *retclass = ftpd_strdup(class);
1165 * Check if user is allowed by /etc/ftpusers
1166 * returns 1 for yes, 0 for no
1168 * NOTE: needs struct passwd *pw setup (for checkuser())
1171 checkaccess(const char *name)
1174 return (checkuser(_NAME_FTPUSERS, name, 1, 0, NULL));
1178 login_utmp(const char *line, const char *name, const char *host,
1179 struct sockinet *haddr)
1181 #if defined(SUPPORT_UTMPX) || defined(SUPPORT_UTMP)
1183 (void)gettimeofday(&tv, NULL);
1185 #ifdef SUPPORT_UTMPX
1187 (void)memset(&utmpx, 0, sizeof(utmpx));
1189 utmpx.ut_pid = getpid();
1190 utmpx.ut_id[0] = 'f';
1191 utmpx.ut_id[1] = 't';
1192 utmpx.ut_id[2] = 'p';
1193 utmpx.ut_id[3] = '*';
1194 utmpx.ut_type = USER_PROCESS;
1195 (void)strncpy(utmpx.ut_name, name, sizeof(utmpx.ut_name));
1196 (void)strncpy(utmpx.ut_line, line, sizeof(utmpx.ut_line));
1197 (void)strncpy(utmpx.ut_host, host, sizeof(utmpx.ut_host));
1198 (void)memcpy(&utmpx.ut_ss, &haddr->si_su, haddr->su_len);
1199 ftpd_loginx(&utmpx);
1202 ftpd_logwtmpx(line, name, host, haddr, 0, USER_PROCESS);
1206 (void)memset(&utmp, 0, sizeof(utmp));
1207 (void)time(&utmp.ut_time);
1208 (void)strncpy(utmp.ut_name, name, sizeof(utmp.ut_name));
1209 (void)strncpy(utmp.ut_line, line, sizeof(utmp.ut_line));
1210 (void)strncpy(utmp.ut_host, host, sizeof(utmp.ut_host));
1214 ftpd_logwtmp(line, name, host);
1221 #ifdef SUPPORT_UTMPX
1222 int okwtmpx = dowtmp;
1225 int okwtmp = dowtmp;
1228 #ifdef SUPPORT_UTMPX
1230 okwtmpx &= ftpd_logoutx(ttyline, 0, DEAD_PROCESS);
1232 ftpd_logwtmpx(ttyline, "", "", NULL, 0, DEAD_PROCESS);
1236 okwtmp &= ftpd_logout(ttyline);
1238 ftpd_logwtmp(ttyline, "", "");
1244 * Terminate login as previous user (if any), resetting state;
1245 * used when USER command is given or login fails.
1254 show_chdir_messages(-1); /* flush chdir cache */
1255 if (pw != NULL && pw->pw_passwd != NULL)
1256 memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
1263 curclass.type = CLASS_REAL;
1264 (void) seteuid((uid_t)0);
1266 setusercontext(NULL, getpwuid(0), 0, LOGIN_SETALL & ~(LOGIN_SETLOGIN |
1267 LOGIN_SETUSER | LOGIN_SETGROUP | LOGIN_SETPATH |
1272 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1273 syslog(LOG_ERR, "pam_setcred: %s",
1274 pam_strerror(pamh, e));
1275 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1276 syslog(LOG_ERR, "pam_close_session: %s",
1277 pam_strerror(pamh, e));
1278 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1279 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1286 pass(const char *passwd)
1289 char root[MAXPATHLEN];
1291 login_cap_t *lc = NULL;
1296 if (logged_in || askpasswd == 0) {
1297 reply(503, "Login with USER first.");
1301 if (curclass.type != CLASS_GUEST) {
1302 /* "ftp" is the only account allowed with no password */
1304 rval = 1; /* failure below */
1308 rval = auth_pam(&pw, passwd);
1310 /* If PAM fails, we proceed with other authentications */
1318 /* If PAM fails, that's it */
1322 #if defined(KERBEROS)
1323 if (klogin(pw, "", hostname, (char *)passwd) == 0) {
1328 #if defined(KERBEROS5)
1329 if (k5login(pw, "", hostname, (char *)passwd) == 0) {
1335 if (skey_haskey(pw->pw_name) == 0) {
1339 p = ftpd_strdup(passwd);
1340 r = skey_passcheck(pw->pw_name, p);
1349 if (opieverify(&opiedata, (char *)passwd) == 0) {
1350 /* OPIE says ok, check expire time */
1351 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1359 rval = checkpassword(pw, passwd);
1366 * If rval > 0, the user failed the authentication check
1367 * above. If rval == 0, either Kerberos or local
1368 * authentication succeeded.
1371 reply(530, "%s", rval == 2 ? "Password expired." :
1372 "Login incorrect.");
1375 "FTP LOGIN FAILED FROM %s", remotehost);
1376 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1377 "FTP LOGIN FAILED FROM %s, %s",
1378 remotehost, curname);
1381 if (login_attempts++ >= 5) {
1383 "repeated login failures from %s",
1391 /* password ok; check if anything else prevents login */
1393 reply(530, "User %s may not use FTP.", pw->pw_name);
1395 syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
1396 remotehost, pw->pw_name);
1400 login_attempts = 0; /* this time successful */
1401 if (setegid((gid_t)pw->pw_gid) < 0) {
1402 reply(550, "Can't set gid.");
1406 if ((lc = login_getpwclass(pw)) != NULL) {
1408 char remote_ip[NI_MAXHOST];
1410 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1411 remote_ip, sizeof(remote_ip) - 1, NULL, 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.",
1419 reply(530, "Permission denied.");
1423 if (!auth_timeok(lc, time(NULL))) {
1424 reply(530, "Login not available right now.");
1431 setusercontext(lc, pw, 0, LOGIN_SETALL &
1432 ~(LOGIN_SETUSER | LOGIN_SETPATH | LOGIN_SETENV));
1434 (void) initgroups(pw->pw_name, pw->pw_gid);
1435 /* cache groups for cmds.c::matchgroup() */
1439 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1440 syslog(LOG_ERR, "pam_open_session: %s",
1441 pam_strerror(pamh, e));
1442 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED))
1444 syslog(LOG_ERR, "pam_setcred: %s",
1445 pam_strerror(pamh, e));
1449 gidcount = getgroups(0, NULL);
1452 gidlist = malloc(gidcount * sizeof *gidlist);
1453 gidcount = getgroups(gidcount, gidlist);
1455 /* open utmp/wtmp before chroot */
1456 login_utmp(ttyline, pw->pw_name, remotehost, &his_addr);
1463 if (curclass.limit != -1 && connections > curclass.limit) {
1464 if (! EMPTYSTR(curclass.limitfile))
1465 (void)display_file(conffilename(curclass.limitfile),
1468 "User %s access denied, connection limit of " LLF
1470 pw->pw_name, (LLT)curclass.limit);
1472 "Maximum connection limit of " LLF
1473 " for class %s reached, login refused for %s",
1474 (LLT)curclass.limit, curclass.classname, pw->pw_name);
1479 switch (curclass.type) {
1482 * We MUST do a chdir() after the chroot. Otherwise
1483 * the old current directory will be accessible as "."
1484 * outside the new root!
1487 curclass.chroot ? curclass.chroot :
1490 format_path(homedir,
1491 curclass.homedir ? curclass.homedir :
1493 if (EMPTYSTR(homedir))
1495 if (EMPTYSTR(root) || chroot(root) < 0) {
1497 "GUEST user %s: can't chroot to %s: %m",
1501 if (chdir(homedir) < 0) {
1503 "GUEST user %s: can't chdir to %s: %m",
1504 pw->pw_name, homedir);
1506 reply(550, "Can't set guest privileges.");
1512 curclass.chroot ? curclass.chroot :
1514 format_path(homedir,
1515 curclass.homedir ? curclass.homedir :
1517 if (EMPTYSTR(homedir))
1519 if (EMPTYSTR(root) || chroot(root) < 0) {
1521 "CHROOT user %s: can't chroot to %s: %m",
1525 if (chdir(homedir) < 0) {
1527 "CHROOT user %s: can't chdir to %s: %m",
1528 pw->pw_name, homedir);
1530 reply(550, "Can't change root.");
1535 /* only chroot REAL if explicitly requested */
1536 if (! EMPTYSTR(curclass.chroot)) {
1537 format_path(root, curclass.chroot);
1538 if (EMPTYSTR(root) || chroot(root) < 0) {
1540 "REAL user %s: can't chroot to %s: %m",
1545 format_path(homedir,
1546 curclass.homedir ? curclass.homedir :
1548 if (EMPTYSTR(homedir) || chdir(homedir) < 0) {
1549 if (chdir("/") < 0) {
1551 "REAL user %s: can't chdir to %s: %m",
1553 !EMPTYSTR(homedir) ? homedir : "/");
1555 "User %s: can't change directory to %s.",
1557 !EMPTYSTR(homedir) ? homedir : "/");
1561 "No directory! Logging in with home=/");
1569 setlogin(pw->pw_name);
1572 (curclass.type != CLASS_REAL &&
1573 ntohs(ctrl_addr.su_port) > IPPORT_RESERVED + 1)) {
1575 if (setgid((gid_t)pw->pw_gid) < 0) {
1576 reply(550, "Can't set gid.");
1579 if (setuid((uid_t)pw->pw_uid) < 0) {
1580 reply(550, "Can't set uid.");
1584 if (seteuid((uid_t)pw->pw_uid) < 0) {
1585 reply(550, "Can't set uid.");
1589 setenv("HOME", homedir, 1);
1591 if (curclass.type == CLASS_GUEST && passwd[0] == '-')
1595 * Display a login message, if it exists.
1596 * N.B. reply(230,) must follow the message.
1598 if (! EMPTYSTR(curclass.motd))
1599 (void)display_file(conffilename(curclass.motd), 230);
1600 show_chdir_messages(230);
1601 if (curclass.type == CLASS_GUEST) {
1604 reply(230, "Guest login ok, access restrictions apply.");
1605 #if HAVE_SETPROCTITLE
1606 snprintf(proctitle, sizeof(proctitle),
1607 "%s: anonymous/%s", remotehost, passwd);
1608 setproctitle("%s", proctitle);
1609 #endif /* HAVE_SETPROCTITLE */
1612 "ANONYMOUS FTP LOGIN FROM %s, %s (class: %s, type: %s)",
1614 curclass.classname, CURCLASSTYPE);
1615 /* store guest password reply into pw_passwd */
1616 REASSIGN(pw->pw_passwd, ftpd_strdup(passwd));
1617 for (p = pw->pw_passwd; *p; p++)
1618 if (!isgraph((unsigned char)*p))
1621 reply(230, "User %s logged in.", pw->pw_name);
1622 #if HAVE_SETPROCTITLE
1623 snprintf(proctitle, sizeof(proctitle),
1624 "%s: %s", remotehost, pw->pw_name);
1625 setproctitle("%s", proctitle);
1626 #endif /* HAVE_SETPROCTITLE */
1629 "FTP LOGIN FROM %s as %s (class: %s, type: %s)",
1630 remotehost, pw->pw_name,
1631 curclass.classname, CURCLASSTYPE);
1633 (void) umask(curclass.umask);
1643 /* Forget all about it... */
1648 retrieve(char *argv[], const char *name)
1652 int (*closefunc)(FILE *) = NULL;
1653 int dolog, sendrv, closerv, stderrfd, isconversion, isdata, isls;
1654 struct timeval start, finish, td, *tdp;
1655 struct rusage rusage_before, rusage_after;
1656 const char *dispname;
1659 sendrv = closerv = stderrfd = -1;
1660 isconversion = isdata = isls = dolog = 0;
1665 if (argv == NULL) { /* if not running a command ... */
1668 fin = fopen(name, "r");
1670 if (fin == NULL) /* doesn't exist?; try a conversion */
1671 argv = do_conversion(name);
1674 syslog(LOG_DEBUG, "get command: '%s' on '%s'",
1679 char temp[MAXPATHLEN];
1681 if (strcmp(argv[0], INTERNAL_LS) == 0) {
1685 (void)snprintf(temp, sizeof(temp), "%s", TMPFILE);
1686 stderrfd = mkstemp(temp);
1691 fin = ftpd_popen(argv, "r", stderrfd);
1692 closefunc = ftpd_pclose;
1694 st.st_blksize = BUFSIZ;
1698 perror_reply(550, dispname);
1700 logxfer("get", -1, name, NULL, NULL,
1703 goto cleanupretrieve;
1707 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
1708 error = "Not a plain file";
1709 reply(550, "%s: %s.", dispname, error);
1712 if (restart_point) {
1713 if (type == TYPE_A) {
1717 for (i = 0; i < restart_point; i++) {
1718 if ((c=getc(fin)) == EOF) {
1719 error = strerror(errno);
1720 perror_reply(550, dispname);
1726 } else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
1727 error = strerror(errno);
1728 perror_reply(550, dispname);
1732 dout = dataconn(dispname, st.st_size, "w");
1736 (void)getrusage(RUSAGE_SELF, &rusage_before);
1737 (void)gettimeofday(&start, NULL);
1738 sendrv = send_data(fin, dout, &st, isdata);
1739 (void)gettimeofday(&finish, NULL);
1740 (void)getrusage(RUSAGE_SELF, &rusage_after);
1741 closedataconn(dout); /* close now to affect timing stats */
1742 timersub(&finish, &start, &td);
1746 logxfer("get", byte_count, name, NULL, tdp, error);
1748 logrusage(&rusage_before, &rusage_after);
1750 closerv = (*closefunc)(fin);
1755 if (!isls && argv != NULL && closerv != 0) {
1757 "Command returned an exit status of %d",
1761 "retrieve command: '%s' returned %d",
1764 if (!isls && argv != NULL && stderrfd != -1 &&
1765 (fstat(stderrfd, &sb) == 0) && sb.st_size > 0 &&
1766 ((errf = fdopen(stderrfd, "r")) != NULL)) {
1767 char *cp, line[LINE_MAX];
1769 reply(-226, "Command error messages:");
1771 while (fgets(line, sizeof(line), errf) != NULL) {
1772 if ((cp = strchr(line, '\n')) != NULL)
1774 reply(0, " %s", line);
1776 (void) fflush(stdout);
1777 (void) fclose(errf);
1778 /* a reply(226,) must follow */
1780 reply(226, "Transfer complete.");
1784 (void)close(stderrfd);
1790 store(const char *name, const char *fmode, int unique)
1794 int (*closefunc)(FILE *);
1795 struct timeval start, finish, td, *tdp;
1799 desc = (*fmode == 'w') ? "put" : "append";
1801 if (unique && stat(name, &st) == 0 &&
1802 (name = gunique(name)) == NULL) {
1803 logxfer(desc, -1, name, NULL, NULL,
1804 "cannot create unique file");
1810 fout = fopen(name, fmode);
1814 perror_reply(553, name);
1815 logxfer(desc, -1, name, NULL, NULL, strerror(errno));
1819 if (restart_point) {
1820 if (type == TYPE_A) {
1824 for (i = 0; i < restart_point; i++) {
1825 if ((c=getc(fout)) == EOF) {
1826 error = strerror(errno);
1827 perror_reply(550, name);
1834 * We must do this seek to "current" position
1835 * because we are changing from reading to
1838 if (fseek(fout, 0L, SEEK_CUR) < 0) {
1839 error = strerror(errno);
1840 perror_reply(550, name);
1843 } else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1844 error = strerror(errno);
1845 perror_reply(550, name);
1849 din = dataconn(name, (off_t)-1, "r");
1852 (void)gettimeofday(&start, NULL);
1853 if (receive_data(din, fout) == 0) {
1855 reply(226, "Transfer complete (unique file name:%s).",
1858 reply(226, "Transfer complete.");
1860 (void)gettimeofday(&finish, NULL);
1861 closedataconn(din); /* close now to affect timing stats */
1862 timersub(&finish, &start, &td);
1865 logxfer(desc, byte_count, name, NULL, tdp, error);
1872 getdatasock(const char *fmode)
1874 int on, s, t, tries;
1879 return (fdopen(data, fmode));
1881 (void) seteuid((uid_t)0);
1882 s = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
1885 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
1886 (char *) &on, sizeof(on)) < 0)
1888 if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
1889 (char *) &on, sizeof(on)) < 0)
1891 /* anchor socket to avoid multi-homing problems */
1892 data_source = ctrl_addr;
1894 * By default source port for PORT connctions is
1895 * ctrlport-1 (see RFC959 section 5.2).
1896 * However, if privs have been dropped and that
1897 * would be < IPPORT_RESERVED, use a random port
1903 port = ntohs(ctrl_addr.su_port) - 1;
1904 if (dropprivs && port < IPPORT_RESERVED)
1905 port = 0; /* use random port */
1906 data_source.su_port = htons(port);
1908 for (tries = 1; ; tries++) {
1909 if (bind(s, (struct sockaddr *)&data_source.si_su,
1910 data_source.su_len) >= 0)
1912 if (errno != EADDRINUSE || tries > 10)
1917 (void) seteuid((uid_t)pw->pw_uid);
1919 if (!mapped && ctrl_addr.su_family == AF_INET) {
1920 on = IPTOS_THROUGHPUT;
1921 if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on,
1923 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
1926 return (fdopen(s, fmode));
1928 /* Return the real value of errno (close may change it) */
1931 (void) seteuid((uid_t)pw->pw_uid);
1938 dataconn(const char *name, off_t size, const char *fmode)
1942 int retry, tos, keepalive, conerrno;
1946 if (size != (off_t) -1)
1947 (void)snprintf(sizebuf, sizeof(sizebuf), " (" LLF " byte%s)",
1948 (LLT)size, PLURAL(size));
1952 struct sockinet from;
1954 socklen_t fromlen = sizeof(from.su_len);
1956 (void) alarm(curclass.timeout);
1957 s = accept(pdata, (struct sockaddr *)&from.si_su, &fromlen);
1960 reply(425, "Can't open data connection.");
1961 (void) close(pdata);
1965 (void) close(pdata);
1967 switch (from.su_family) {
1971 tos = IPTOS_THROUGHPUT;
1972 (void) setsockopt(s, IPPROTO_IP, IP_TOS,
1973 (char *)&tos, sizeof(int));
1978 /* Set keepalives on the socket to detect dropped conns. */
1981 (void) setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
1982 (char *)&keepalive, sizeof(int));
1984 reply(150, "Opening %s mode data connection for '%s'%s.",
1985 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1986 return (fdopen(pdata, fmode));
1989 reply(125, "Using existing data connection for '%s'%s.",
1992 return (fdopen(data, fmode));
1995 data_dest = his_addr;
1997 retry = conerrno = 0;
1999 file = getdatasock(fmode);
2001 char hbuf[NI_MAXHOST];
2002 char pbuf[NI_MAXSERV];
2004 if (getnameinfo((struct sockaddr *)&data_source.si_su,
2005 data_source.su_len, hbuf, sizeof(hbuf), pbuf,
2006 sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV))
2007 strlcpy(hbuf, "?", sizeof(hbuf));
2008 reply(425, "Can't create data socket (%s,%s): %s.",
2009 hbuf, pbuf, strerror(errno));
2012 data = fileno(file);
2014 if (connect(data, (struct sockaddr *)&data_dest.si_su,
2015 data_dest.su_len) == 0)
2018 (void) fclose(file);
2021 if (conerrno == EADDRINUSE) {
2022 sleep((unsigned) swaitint);
2027 } while (retry <= swaitmax);
2028 if (conerrno != 0) {
2029 perror_reply(425, "Can't build data connection");
2032 reply(150, "Opening %s mode data connection for '%s'%s.",
2033 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2038 closedataconn(FILE *fd)
2051 write_data(int fd, char *buf, size_t size, off_t *bufrem,
2052 struct timeval *then, int isdata)
2054 struct timeval now, td;
2059 if (curclass.writesize) {
2060 if (curclass.writesize < c)
2061 c = curclass.writesize;
2063 if (curclass.rateget) {
2067 (void) alarm(curclass.timeout);
2068 c = write(fd, buf, c);
2075 total_data_out += c;
2078 total_bytes_out += c;
2080 if (curclass.rateget) {
2083 (void)gettimeofday(&now, NULL);
2084 timersub(&now, then, &td);
2085 if (td.tv_sec == 0) {
2086 usleep(1000000 - td.tv_usec);
2087 (void)gettimeofday(then, NULL);
2090 *bufrem = curclass.rateget;
2097 static enum send_status
2098 send_data_with_read(int filefd, int netfd, const struct stat *st, int isdata)
2100 struct timeval then;
2106 if (curclass.readsize)
2107 readsize = curclass.readsize;
2109 readsize = (size_t)st->st_blksize;
2110 if ((buf = malloc(readsize)) == NULL) {
2111 perror_reply(451, "Local resource failure: malloc");
2112 return (SS_NO_TRANSFER);
2115 if (curclass.rateget) {
2116 bufrem = curclass.rateget;
2117 (void)gettimeofday(&then, NULL);
2120 (void) alarm(curclass.timeout);
2121 c = read(filefd, buf, readsize);
2125 error = SS_FILE_ERROR;
2126 else if (write_data(netfd, buf, c, &bufrem, &then, isdata))
2127 error = SS_DATA_ERROR;
2128 else if (urgflag && handleoobcmd())
2138 static enum send_status
2139 send_data_with_mmap(int filefd, int netfd, const struct stat *st, int isdata)
2141 struct timeval then;
2142 off_t bufrem, filesize, off, origoff;
2143 size_t mapsize, winsize;
2144 int error, sendbufsize, sendlowat;
2147 if (curclass.sendbufsize) {
2148 sendbufsize = curclass.sendbufsize;
2149 if (setsockopt(netfd, SOL_SOCKET, SO_SNDBUF,
2150 &sendbufsize, sizeof(int)) == -1)
2151 syslog(LOG_WARNING, "setsockopt(SO_SNDBUF, %d): %m",
2155 if (curclass.sendlowat) {
2156 sendlowat = curclass.sendlowat;
2157 if (setsockopt(netfd, SOL_SOCKET, SO_SNDLOWAT,
2158 &sendlowat, sizeof(int)) == -1)
2159 syslog(LOG_WARNING, "setsockopt(SO_SNDLOWAT, %d): %m",
2163 winsize = curclass.mmapsize;
2164 filesize = st->st_size;
2166 syslog(LOG_INFO, "mmapsize = %ld, writesize = %ld",
2167 (long)winsize, (long)curclass.writesize);
2171 off = lseek(filefd, (off_t)0, SEEK_CUR);
2176 if (curclass.rateget) {
2177 bufrem = curclass.rateget;
2178 (void)gettimeofday(&then, NULL);
2181 mapsize = MIN(filesize - off, winsize);
2184 win = mmap(NULL, mapsize, PROT_READ,
2185 MAP_FILE|MAP_SHARED, filefd, off);
2186 if (win == MAP_FAILED) {
2189 return (SS_FILE_ERROR);
2191 (void) madvise(win, mapsize, MADV_SEQUENTIAL);
2192 error = write_data(netfd, win, mapsize, &bufrem, &then,
2194 (void) madvise(win, mapsize, MADV_DONTNEED);
2195 munmap(win, mapsize);
2196 if (urgflag && handleoobcmd())
2197 return (SS_ABORTED);
2199 return (SS_DATA_ERROR);
2202 return (SS_SUCCESS);
2205 return (send_data_with_read(filefd, netfd, st, isdata));
2209 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
2210 * encapsulation of the data subject to Mode, Structure, and Type.
2212 * NB: Form isn't handled.
2215 send_data(FILE *instr, FILE *outstr, const struct stat *st, int isdata)
2217 int c, filefd, netfd, rval;
2226 /* XXXLUKEM: rate limit ascii send (get) */
2227 (void) alarm(curclass.timeout);
2228 while ((c = getc(instr)) != EOF) {
2229 if (urgflag && handleoobcmd())
2230 goto cleanup_send_data;
2235 (void) putc('\r', outstr);
2243 (void) putc(c, outstr);
2250 if ((byte_count % 4096) == 0)
2251 (void) alarm(curclass.timeout);
2260 goto cleanup_send_data;
2264 filefd = fileno(instr);
2265 netfd = fileno(outstr);
2266 switch (send_data_with_mmap(filefd, netfd, st, isdata)) {
2272 case SS_NO_TRANSFER:
2273 goto cleanup_send_data;
2282 goto cleanup_send_data;
2285 reply(550, "Unimplemented TYPE %d in send_data", type);
2286 goto cleanup_send_data;
2291 perror_reply(426, "Data connection");
2292 goto cleanup_send_data;
2296 perror_reply(551, "Error on input file");
2297 goto cleanup_send_data;
2313 * Transfer data from peer to "outstr" using the appropriate encapulation of
2314 * the data subject to Mode, Structure, and Type.
2316 * N.B.: Form isn't handled.
2319 receive_data(FILE *instr, FILE *outstr)
2321 int c, bare_lfs, netfd, filefd, rval;
2325 struct sigaction sa, sa_saved;
2331 memset(&sa, 0, sizeof(sa));
2332 sigfillset(&sa.sa_mask);
2333 sa.sa_flags = SA_RESTART;
2334 sa.sa_handler = lostconn;
2335 (void) sigaction(SIGALRM, &sa, &sa_saved);
2344 #define FILESIZECHECK(x) \
2346 if (curclass.maxfilesize != -1 && \
2347 (x) > curclass.maxfilesize) { \
2357 netfd = fileno(instr);
2358 filefd = fileno(outstr);
2359 (void) alarm(curclass.timeout);
2360 if (curclass.readsize)
2361 readsize = curclass.readsize;
2362 else if (fstat(filefd, &st))
2363 readsize = (size_t)st.st_blksize;
2366 if ((buf = malloc(readsize)) == NULL) {
2367 perror_reply(451, "Local resource failure: malloc");
2368 goto cleanup_recv_data;
2370 if (curclass.rateput) {
2373 struct timeval then, now, td;
2376 (void)gettimeofday(&then, NULL);
2378 for (bufrem = curclass.rateput; bufrem > 0; ) {
2379 if ((c = read(netfd, buf,
2380 MIN(readsize, bufrem))) <= 0)
2382 if (urgflag && handleoobcmd())
2383 goto cleanup_recv_data;
2384 FILESIZECHECK(byte_count + c);
2385 if ((d = write(filefd, buf, c)) != c)
2387 (void) alarm(curclass.timeout);
2392 total_bytes_in += c;
2395 (void)gettimeofday(&now, NULL);
2396 timersub(&now, &then, &td);
2398 usleep(1000000 - td.tv_usec);
2401 while ((c = read(netfd, buf, readsize)) > 0) {
2402 if (urgflag && handleoobcmd())
2403 goto cleanup_recv_data;
2404 FILESIZECHECK(byte_count + c);
2405 if (write(filefd, buf, c) != c)
2407 (void) alarm(curclass.timeout);
2411 total_bytes_in += c;
2419 goto cleanup_recv_data;
2422 reply(553, "TYPE E not implemented.");
2423 goto cleanup_recv_data;
2426 (void) alarm(curclass.timeout);
2427 /* XXXLUKEM: rate limit ascii receive (put) */
2428 while ((c = getc(instr)) != EOF) {
2429 if (urgflag && handleoobcmd())
2430 goto cleanup_recv_data;
2436 if ((byte_count % 4096) == 0)
2437 (void) alarm(curclass.timeout);
2443 if ((c = getc(instr)) != '\n') {
2449 if ((byte_count % 4096) == 0)
2450 (void) alarm(curclass.timeout);
2452 FILESIZECHECK(byteswritten);
2453 (void) putc ('\r', outstr);
2454 if (c == '\0' || c == EOF)
2459 FILESIZECHECK(byteswritten);
2460 (void) putc(c, outstr);
2471 "WARNING! %d bare linefeeds received in ASCII mode",
2473 reply(0, "File may not have transferred correctly.");
2476 goto cleanup_recv_data;
2479 reply(550, "Unimplemented TYPE %d in receive_data", type);
2480 goto cleanup_recv_data;
2482 #undef FILESIZECHECK
2486 perror_reply(426, "Data Connection");
2487 goto cleanup_recv_data;
2491 perror_reply(452, "Error writing file");
2492 goto cleanup_recv_data;
2496 (void) sigaction(SIGALRM, &sa_saved, NULL);
2511 struct sockinet *su = NULL;
2512 static char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
2515 off_t otbi, otbo, otb;
2517 a = p = (u_char *)NULL;
2519 reply(-211, "%s FTP server status:", hostname);
2520 reply(0, "Version: %s", EMPTYSTR(version) ? "<suppressed>" : version);
2522 if (!getnameinfo((struct sockaddr *)&his_addr.si_su, his_addr.su_len,
2523 hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST)
2524 && strcmp(remotehost, hbuf) != 0)
2525 reply(0, "Connected to %s (%s)", remotehost, hbuf);
2527 reply(0, "Connected to %s", remotehost);
2530 if (curclass.type == CLASS_GUEST)
2531 reply(0, "Logged in anonymously");
2533 reply(0, "Logged in as %s%s", pw->pw_name,
2534 curclass.type == CLASS_CHROOT ? " (chroot)" : "");
2535 } else if (askpasswd)
2536 reply(0, "Waiting for password");
2538 reply(0, "Waiting for user name");
2539 cprintf(stdout, " TYPE: %s", typenames[type]);
2540 if (type == TYPE_A || type == TYPE_E)
2541 cprintf(stdout, ", FORM: %s", formnames[form]);
2542 if (type == TYPE_L) {
2544 cprintf(stdout, " %d", NBBY);
2546 /* XXX: `bytesize' needs to be defined in this case */
2547 cprintf(stdout, " %d", bytesize);
2550 cprintf(stdout, "; STRUcture: %s; transfer MODE: %s\r\n",
2551 strunames[stru], modenames[mode]);
2554 reply(0, "Data connection open");
2556 } else if (pdata != -1) {
2557 reply(0, "in Passive mode");
2558 if (curclass.advertise.su_len != 0)
2559 su = &curclass.advertise;
2564 } else if (usedefault == 0) {
2565 su = (struct sockinet *)&data_dest;
2568 reply(0, "EPSV only mode (EPSV ALL)");
2573 if (su->su_family == AF_INET) {
2574 a = (u_char *) &su->su_addr;
2575 p = (u_char *) &su->su_port;
2576 #define UC(b) (((int) b) & 0xff)
2577 reply(0, "%s (%d,%d,%d,%d,%d,%d)",
2578 ispassive ? "PASV" : "PORT" ,
2579 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2580 UC(p[0]), UC(p[1]));
2588 switch (su->su_family) {
2590 a = (u_char *) &su->su_addr;
2591 p = (u_char *) &su->su_port;
2592 alen = sizeof(su->su_addr);
2597 a = (u_char *) &su->su_6addr;
2598 p = (u_char *) &su->su_port;
2599 alen = sizeof(su->su_6addr);
2608 cprintf(stdout, " %s (%d,%d",
2609 ispassive ? "LPSV" : "LPRT", af, alen);
2610 for (i = 0; i < alen; i++)
2611 cprintf(stdout, ",%d", UC(a[i]));
2612 cprintf(stdout, ",%d,%d,%d)\r\n",
2613 2, UC(p[0]), UC(p[1]));
2620 af = af2epsvproto(su->su_family);
2623 struct sockinet tmp;
2627 if (tmp.su_family == AF_INET6)
2628 tmp.su_scope_id = 0;
2630 if (getnameinfo((struct sockaddr *)&tmp.si_su,
2631 tmp.su_len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
2632 NI_NUMERICHOST | NI_NUMERICSERV) == 0)
2633 reply(0, "%s (|%d|%s|%s|)",
2634 ispassive ? "EPSV" : "EPRT",
2638 reply(0, "No data connection");
2642 "Data sent: " LLF " byte%s in " LLF " file%s",
2643 (LLT)total_data_out, PLURAL(total_data_out),
2644 (LLT)total_files_out, PLURAL(total_files_out));
2646 "Data received: " LLF " byte%s in " LLF " file%s",
2647 (LLT)total_data_in, PLURAL(total_data_in),
2648 (LLT)total_files_in, PLURAL(total_files_in));
2650 "Total data: " LLF " byte%s in " LLF " file%s",
2651 (LLT)total_data, PLURAL(total_data),
2652 (LLT)total_files, PLURAL(total_files));
2654 otbi = total_bytes_in;
2655 otbo = total_bytes_out;
2657 reply(0, "Traffic sent: " LLF " byte%s in " LLF " transfer%s",
2658 (LLT)otbo, PLURAL(otbo),
2659 (LLT)total_xfers_out, PLURAL(total_xfers_out));
2660 reply(0, "Traffic received: " LLF " byte%s in " LLF " transfer%s",
2661 (LLT)otbi, PLURAL(otbi),
2662 (LLT)total_xfers_in, PLURAL(total_xfers_in));
2663 reply(0, "Total traffic: " LLF " byte%s in " LLF " transfer%s",
2664 (LLT)otb, PLURAL(otb),
2665 (LLT)total_xfers, PLURAL(total_xfers));
2667 if (logged_in && !CURCLASS_FLAGS_ISSET(private)) {
2671 reply(0, "Class: %s, type: %s",
2672 curclass.classname, CURCLASSTYPE);
2673 reply(0, "Check PORT/LPRT commands: %sabled",
2674 CURCLASS_FLAGS_ISSET(checkportcmd) ? "en" : "dis");
2675 if (! EMPTYSTR(curclass.display))
2676 reply(0, "Display file: %s", curclass.display);
2677 if (! EMPTYSTR(curclass.notify))
2678 reply(0, "Notify fileglob: %s", curclass.notify);
2679 reply(0, "Idle timeout: " LLF ", maximum timeout: " LLF,
2680 (LLT)curclass.timeout, (LLT)curclass.maxtimeout);
2681 reply(0, "Current connections: %d", connections);
2682 if (curclass.limit == -1)
2683 reply(0, "Maximum connections: unlimited");
2685 reply(0, "Maximum connections: " LLF,
2686 (LLT)curclass.limit);
2687 if (curclass.limitfile)
2688 reply(0, "Connection limit exceeded message file: %s",
2689 conffilename(curclass.limitfile));
2690 if (! EMPTYSTR(curclass.chroot))
2691 reply(0, "Chroot format: %s", curclass.chroot);
2692 reply(0, "Deny bad ftpusers(5) quickly: %sabled",
2693 CURCLASS_FLAGS_ISSET(denyquick) ? "en" : "dis");
2694 if (! EMPTYSTR(curclass.homedir))
2695 reply(0, "Homedir format: %s", curclass.homedir);
2696 if (curclass.maxfilesize == -1)
2697 reply(0, "Maximum file size: unlimited");
2699 reply(0, "Maximum file size: " LLF,
2700 (LLT)curclass.maxfilesize);
2701 if (! EMPTYSTR(curclass.motd))
2702 reply(0, "MotD file: %s", conffilename(curclass.motd));
2704 "Modify commands (CHMOD, DELE, MKD, RMD, RNFR, UMASK): %sabled",
2705 CURCLASS_FLAGS_ISSET(modify) ? "en" : "dis");
2706 reply(0, "Upload commands (APPE, STOR, STOU): %sabled",
2707 CURCLASS_FLAGS_ISSET(upload) ? "en" : "dis");
2708 reply(0, "Sanitize file names: %sabled",
2709 CURCLASS_FLAGS_ISSET(sanenames) ? "en" : "dis");
2710 reply(0, "PASV/LPSV/EPSV connections: %sabled",
2711 CURCLASS_FLAGS_ISSET(passive) ? "en" : "dis");
2712 if (curclass.advertise.su_len != 0) {
2713 char buf[50]; /* big enough for IPv6 address */
2716 bp = inet_ntop(curclass.advertise.su_family,
2717 (void *)&curclass.advertise.su_addr,
2720 reply(0, "PASV advertise address: %s", bp);
2722 if (curclass.portmin && curclass.portmax)
2723 reply(0, "PASV port range: " LLF " - " LLF,
2724 (LLT)curclass.portmin, (LLT)curclass.portmax);
2725 if (curclass.rateget)
2726 reply(0, "Rate get limit: " LLF " bytes/sec",
2727 (LLT)curclass.rateget);
2729 reply(0, "Rate get limit: disabled");
2730 if (curclass.rateput)
2731 reply(0, "Rate put limit: " LLF " bytes/sec",
2732 (LLT)curclass.rateput);
2734 reply(0, "Rate put limit: disabled");
2735 if (curclass.mmapsize)
2736 reply(0, "Mmap size: " LLF, (LLT)curclass.mmapsize);
2738 reply(0, "Mmap size: disabled");
2739 if (curclass.readsize)
2740 reply(0, "Read size: " LLF, (LLT)curclass.readsize);
2742 reply(0, "Read size: default");
2743 if (curclass.writesize)
2744 reply(0, "Write size: " LLF, (LLT)curclass.writesize);
2746 reply(0, "Write size: default");
2747 if (curclass.recvbufsize)
2748 reply(0, "Receive buffer size: " LLF,
2749 (LLT)curclass.recvbufsize);
2751 reply(0, "Receive buffer size: default");
2752 if (curclass.sendbufsize)
2753 reply(0, "Send buffer size: " LLF,
2754 (LLT)curclass.sendbufsize);
2756 reply(0, "Send buffer size: default");
2757 if (curclass.sendlowat)
2758 reply(0, "Send low water mark: " LLF,
2759 (LLT)curclass.sendlowat);
2761 reply(0, "Send low water mark: default");
2762 reply(0, "Umask: %.04o", curclass.umask);
2763 for (cp = curclass.conversions; cp != NULL; cp=cp->next) {
2764 if (cp->suffix == NULL || cp->types == NULL ||
2765 cp->command == NULL)
2767 reply(0, "Conversion: %s [%s] disable: %s, command: %s",
2768 cp->suffix, cp->types, cp->disable, cp->command);
2772 reply(211, "End of status");
2776 fatal(const char *s)
2779 reply(451, "Error in server: %s\n", s);
2780 reply(221, "Closing connection due to server error.");
2787 * depending on the value of n, display fmt with a trailing CRLF and
2789 * n < -1 prefix the message with abs(n) + "-" (initial line)
2790 * n == 0 prefix the message with 4 spaces (middle lines)
2791 * n > 0 prefix the message with n + " " (final line)
2794 reply(int n, const char *fmt, ...)
2796 char msg[MAXPATHLEN * 2 + 100];
2802 b = snprintf(msg, sizeof(msg), " ");
2804 b = snprintf(msg, sizeof(msg), "%d-", -n);
2806 b = snprintf(msg, sizeof(msg), "%d ", n);
2808 vsnprintf(msg + b, sizeof(msg) - b, fmt, ap);
2810 cprintf(stdout, "%s\r\n", msg);
2811 (void)fflush(stdout);
2813 syslog(LOG_DEBUG, "<--- %s", msg);
2817 logremotehost(struct sockinet *who)
2820 if (getnameinfo((struct sockaddr *)&who->si_su,
2821 who->su_len, remotehost, sizeof(remotehost), NULL, 0, 0))
2822 strlcpy(remotehost, "?", sizeof(remotehost));
2824 #if HAVE_SETPROCTITLE
2825 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
2826 setproctitle("%s", proctitle);
2827 #endif /* HAVE_SETPROCTITLE */
2829 syslog(LOG_INFO, "connection from %s to %s",
2830 remotehost, hostname);
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).
2839 dologout(int status)
2842 * Prevent reception of SIGURG from resulting in a resumption
2843 * back to the main program loop.
2849 if (!notickets && krbtkfile_env)
2850 unlink(krbtkfile_env);
2853 /* beware of flushing buffers after a SIGPIPE */
2854 if (xferlogfd != -1)
2867 reply(426, "Transfer aborted. Data connection closed.");
2868 reply(226, "Abort successful");
2869 transflag = 0; /* flag that the transfer has aborted */
2880 if (file_size != (off_t) -1)
2882 "Status: " LLF " of " LLF " byte%s transferred",
2883 (LLT)byte_count, (LLT)file_size,
2884 PLURAL(byte_count));
2886 reply(213, "Status: " LLF " byte%s transferred",
2887 (LLT)byte_count, PLURAL(byte_count));
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").
2904 /* only process if transfer occurring */
2908 ret = getline(cp, sizeof(tmpline)-1, stdin);
2910 reply(221, "You could at least say goodbye.");
2912 } else if (ret == -2) {
2913 /* Ignore truncated command */
2914 /* XXX: abort xfer with "500 command too long", & return 1 ? */
2918 * Manually parse OOB commands, because we can't
2919 * recursively call the yacc parser...
2921 if (strcasecmp(cp, "ABOR\r\n") == 0) {
2923 } else if (strcasecmp(cp, "STAT\r\n") == 0) {
2926 /* XXX: error with "500 unknown command" ? */
2928 return (transflag == 0);
2932 bind_pasv_addr(void)
2934 static int passiveport;
2937 len = pasv_addr.su_len;
2938 if (curclass.portmin == 0 && curclass.portmax == 0) {
2939 pasv_addr.su_port = 0;
2940 return (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len));
2943 if (passiveport == 0) {
2945 passiveport = rand() % (curclass.portmax - curclass.portmin)
2952 if (port > curclass.portmax)
2953 port = curclass.portmin;
2954 else if (port == passiveport) {
2958 pasv_addr.su_port = htons(port);
2959 if (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len) == 0)
2961 if (errno != EADDRINUSE)
2969 * Note: a response of 425 is not mentioned as a possible response to
2970 * the PASV command in RFC959. However, it has been blessed as
2971 * a legitimate response by Jon Postel in a telephone conversation
2972 * with Rick Adams on 25 Jan 89.
2977 socklen_t len, recvbufsize;
2982 pdata = socket(AF_INET, SOCK_STREAM, 0);
2983 if (pdata < 0 || !logged_in) {
2984 perror_reply(425, "Can't open passive connection");
2987 pasv_addr = ctrl_addr;
2989 if (bind_pasv_addr() < 0)
2991 len = pasv_addr.su_len;
2992 if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
2994 pasv_addr.su_len = len;
2995 if (curclass.recvbufsize) {
2996 recvbufsize = curclass.recvbufsize;
2997 if (setsockopt(pdata, SOL_SOCKET, SO_RCVBUF, &recvbufsize,
2999 syslog(LOG_WARNING, "setsockopt(SO_RCVBUF, %d): %m",
3002 if (listen(pdata, 1) < 0)
3004 if (curclass.advertise.su_len != 0)
3005 a = (char *) &curclass.advertise.su_addr;
3007 a = (char *) &pasv_addr.su_addr;
3008 p = (char *) &pasv_addr.su_port;
3010 #define UC(b) (((int) b) & 0xff)
3012 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
3013 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
3017 (void) close(pdata);
3019 perror_reply(425, "Can't open passive connection");
3024 * convert protocol identifier to/from AF
3027 lpsvproto2af(int proto)
3043 af2lpsvproto(int af)
3059 epsvproto2af(int proto)
3075 af2epsvproto(int af)
3091 * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)
3092 * 229 Entering Extended Passive Mode (|||port|)
3095 long_passive(char *cmd, int pf)
3101 syslog(LOG_NOTICE, "long passive but not logged in");
3102 reply(503, "Login with USER first.");
3106 if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) {
3108 * XXX: only EPRT/EPSV ready clients will understand this
3110 if (strcmp(cmd, "EPSV") != 0)
3111 reply(501, "Network protocol mismatch"); /*XXX*/
3113 epsv_protounsupp("Network protocol mismatch");
3120 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
3122 perror_reply(425, "Can't open passive connection");
3125 pasv_addr = ctrl_addr;
3126 if (bind_pasv_addr() < 0)
3128 len = pasv_addr.su_len;
3129 if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
3131 pasv_addr.su_len = len;
3132 if (listen(pdata, 1) < 0)
3134 p = (char *) &pasv_addr.su_port;
3136 #define UC(b) (((int) b) & 0xff)
3138 if (strcmp(cmd, "LPSV") == 0) {
3139 struct sockinet *advert;
3141 if (curclass.advertise.su_len != 0)
3142 advert = &curclass.advertise;
3144 advert = &pasv_addr;
3145 switch (advert->su_family) {
3147 a = (char *) &advert->su_addr;
3149 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3150 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3151 2, UC(p[0]), UC(p[1]));
3155 a = (char *) &advert->su_6addr;
3157 "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)",
3159 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3160 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3161 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3162 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3163 2, UC(p[0]), UC(p[1]));
3168 } else if (strcmp(cmd, "EPSV") == 0) {
3169 switch (pasv_addr.su_family) {
3174 reply(229, "Entering Extended Passive Mode (|||%d|)",
3175 ntohs(pasv_addr.su_port));
3179 /* more proper error code? */
3183 (void) close(pdata);
3185 perror_reply(425, "Can't open passive connection");
3190 extended_port(const char *arg)
3196 struct addrinfo hints;
3197 struct addrinfo *res = NULL;
3199 unsigned long proto;
3201 tmp = ftpd_strdup(arg);
3205 memset(result, 0, sizeof(result));
3206 for (i = 0; i < 3; i++) {
3207 q = strchr(p, delim);
3208 if (!q || *q != delim)
3215 /* some more sanity checks */
3218 (void)strtoul(result[2], &p, 10);
3219 if (errno || !*result[2] || *p)
3223 proto = strtoul(result[0], &p, 10);
3224 if (errno || !*result[0] || *p)
3227 memset(&hints, 0, sizeof(hints));
3228 hints.ai_family = epsvproto2af((int)proto);
3229 if (hints.ai_family < 0)
3231 hints.ai_socktype = SOCK_STREAM;
3232 hints.ai_flags = AI_NUMERICHOST;
3233 if (getaddrinfo(result[1], result[2], &hints, &res))
3237 if (sizeof(data_dest) < res->ai_addrlen)
3239 memcpy(&data_dest.si_su, res->ai_addr, res->ai_addrlen);
3240 data_dest.su_len = res->ai_addrlen;
3242 if (his_addr.su_family == AF_INET6 &&
3243 data_dest.su_family == AF_INET6) {
3244 /* XXX: more sanity checks! */
3245 data_dest.su_scope_id = his_addr.su_scope_id;
3256 reply(500, "Invalid argument, rejected.");
3265 epsv_protounsupp("Protocol not supported");
3273 * 522 Protocol not supported (proto,...)
3274 * as we assume address family for control and data connections are the same,
3275 * we do not return the list of address families we support - instead, we
3276 * return the address family of the control connection.
3279 epsv_protounsupp(const char *message)
3283 proto = af2epsvproto(ctrl_addr.su_family);
3285 reply(501, "%s", message); /* XXX */
3287 reply(522, "%s, use (%d)", message, proto);
3291 * Generate unique name for file with basename "local".
3292 * The file named "local" is already known to exist.
3293 * Generates failure reply on error.
3295 * XXX: this function should under go changes similar to
3296 * the mktemp(3)/mkstemp(3) changes.
3299 gunique(const char *local)
3301 static char new[MAXPATHLEN];
3306 cp = strrchr(local, '/');
3309 if (stat(cp ? local : ".", &st) < 0) {
3310 perror_reply(553, cp ? local : ".");
3315 for (count = 1; count < 100; count++) {
3316 (void)snprintf(new, sizeof(new) - 1, "%s.%d", local, count);
3317 if (stat(new, &st) < 0)
3320 reply(452, "Unique file name cannot be created.");
3325 * Format and send reply containing system error number.
3328 perror_reply(int code, const char *string)
3333 reply(code, "%s: %s.", string, strerror(errno));
3337 static char *onefile[] = {
3343 send_file_list(const char *whichf)
3349 char **dirlist, *dirname, *p;
3350 char *notglob = NULL;
3364 if (strpbrk(whichf, "~{[*?") != NULL) {
3365 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE|GLOB_LIMIT;
3367 memset(&gl, 0, sizeof(gl));
3369 if (glob(whichf, flags, 0, &gl)) {
3370 reply(450, "Not found");
3371 goto cleanup_send_file_list;
3372 } else if (gl.gl_pathc == 0) {
3374 perror_reply(450, whichf);
3375 goto cleanup_send_file_list;
3377 dirlist = gl.gl_pathv;
3379 notglob = ftpd_strdup(whichf);
3380 onefile[0] = notglob;
3384 /* XXX: } for vi sm */
3386 while ((dirname = *dirlist++) != NULL) {
3387 int trailingslash = 0;
3389 if (stat(dirname, &st) < 0) {
3391 * If user typed "ls -l", etc, and the client
3392 * used NLST, do what the user meant.
3394 /* XXX: nuke this support? */
3395 if (dirname[0] == '-' && *dirlist == NULL &&
3397 char *argv[] = { INTERNAL_LS, "", NULL };
3400 retrieve(argv, dirname);
3401 goto cleanup_send_file_list;
3403 perror_reply(450, whichf);
3404 goto cleanup_send_file_list;
3407 if (S_ISREG(st.st_mode)) {
3410 * should we follow RFC959 and not work
3411 * for non directories?
3414 dout = dataconn("file list", (off_t)-1, "w");
3416 goto cleanup_send_file_list;
3419 cprintf(dout, "%s%s\n", dirname,
3420 type == TYPE_A ? "\r" : "");
3422 } else if (!S_ISDIR(st.st_mode))
3425 if (dirname[strlen(dirname) - 1] == '/')
3428 if ((dirp = opendir(dirname)) == NULL)
3431 while ((dir = readdir(dirp)) != NULL) {
3432 char nbuf[MAXPATHLEN];
3434 if (urgflag && handleoobcmd())
3435 goto cleanup_send_file_list;
3437 if (ISDOTDIR(dir->d_name) || ISDOTDOTDIR(dir->d_name))
3440 (void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
3441 trailingslash ? "" : "/", dir->d_name);
3444 * We have to do a stat to ensure it's
3445 * not a directory or special file.
3449 * should we follow RFC959 and filter out
3450 * non files ? lukem - NO!, or not until
3451 * our ftp client uses MLS{T,D} for completion.
3453 if (simple || (stat(nbuf, &st) == 0 &&
3454 S_ISREG(st.st_mode))) {
3456 dout = dataconn("file list", (off_t)-1,
3459 goto cleanup_send_file_list;
3463 if (nbuf[0] == '.' && nbuf[1] == '/')
3465 cprintf(dout, "%s%s\n", p,
3466 type == TYPE_A ? "\r" : "");
3469 (void) closedir(dirp);
3473 reply(450, "No files found.");
3474 else if (ferror(dout) != 0)
3475 perror_reply(451, "Data connection");
3477 reply(226, "Transfer complete.");
3479 cleanup_send_file_list:
3480 closedataconn(dout);
3492 conffilename(const char *s)
3494 static char filename[MAXPATHLEN];
3497 strlcpy(filename, s, sizeof(filename));
3499 (void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
3505 * if logging > 1, then based on the arguments, syslog a message:
3506 * if bytes != -1 "<command> <file1> = <bytes> bytes"
3507 * else if file2 != NULL "<command> <file1> <file2>"
3508 * else "<command> <file1>"
3509 * if elapsed != NULL, append "in xxx.yyy seconds"
3510 * if error != NULL, append ": " + error
3512 * if doxferlog != 0, bytes != -1, and command is "get", "put",
3513 * or "append", syslog and/or write a wu-ftpd style xferlog entry
3516 logxfer(const char *command, off_t bytes, const char *file1, const char *file2,
3517 const struct timeval *elapsed, const char *error)
3519 char buf[MAXPATHLEN * 2 + 100];
3520 char realfile1[MAXPATHLEN], realfile2[MAXPATHLEN];
3521 const char *r1, *r2;
3526 if (logging <=1 && !doxferlog)
3530 if ((r1 = realpath(file1, realfile1)) == NULL)
3533 if ((r2 = realpath(file2, realfile2)) == NULL)
3540 len = snprintf(buf, sizeof(buf), "%s %s", command, r1);
3541 if (bytes != (off_t)-1)
3542 len += snprintf(buf + len, sizeof(buf) - len,
3543 " = " LLF " byte%s", (LLT) bytes, PLURAL(bytes));
3544 else if (r2 != NULL)
3545 len += snprintf(buf + len, sizeof(buf) - len,
3547 if (elapsed != NULL)
3548 len += snprintf(buf + len, sizeof(buf) - len,
3549 " in %ld.%.03d seconds", elapsed->tv_sec,
3550 (int)(elapsed->tv_usec / 1000));
3552 len += snprintf(buf + len, sizeof(buf) - len,
3554 syslog(LOG_INFO, "%s", buf);
3558 * syslog wu-ftpd style log entry, prefixed with "xferlog: "
3560 if (!doxferlog || bytes == -1)
3563 if (strcmp(command, "get") == 0)
3565 else if (strcmp(command, "put") == 0 || strcmp(command, "append") == 0)
3571 len = snprintf(buf, sizeof(buf),
3572 "%.24s %ld %s " LLF " %s %c %s %c %c %s FTP 0 * %c\n",
3575 * XXX: wu-ftpd puts ' (send)' or ' (recv)' in the syslog message, and removes
3576 * the full date. This may be problematic for accurate log parsing,
3577 * given that syslog messages don't contain the full date.
3580 elapsed == NULL ? 0 : elapsed->tv_sec + (elapsed->tv_usec > 0),
3584 type == TYPE_A ? 'a' : 'b',
3585 "_", /* XXX: take conversions into account? */
3588 curclass.type == CLASS_GUEST ? 'a' :
3589 curclass.type == CLASS_CHROOT ? 'g' :
3590 curclass.type == CLASS_REAL ? 'r' : '?',
3592 curclass.type == CLASS_GUEST ? pw->pw_passwd : pw->pw_name,
3593 error != NULL ? 'i' : 'c'
3596 if ((doxferlog & 2) && xferlogfd != -1)
3597 write(xferlogfd, buf, len);
3598 if ((doxferlog & 1)) {
3599 buf[len-1] = '\n'; /* strip \n from syslog message */
3600 syslog(LOG_INFO, "xferlog: %s", buf);
3605 * Log the resource usage.
3607 * XXX: more resource usage to logging?
3610 logrusage(const struct rusage *rusage_before,
3611 const struct rusage *rusage_after)
3613 struct timeval usrtime, systime;
3618 timersub(&rusage_after->ru_utime, &rusage_before->ru_utime, &usrtime);
3619 timersub(&rusage_after->ru_stime, &rusage_before->ru_stime, &systime);
3620 syslog(LOG_INFO, "%ld.%.03du %ld.%.03ds %ld+%ldio %ldpf+%ldw",
3621 usrtime.tv_sec, (int)(usrtime.tv_usec / 1000),
3622 systime.tv_sec, (int)(systime.tv_usec / 1000),
3623 rusage_after->ru_inblock - rusage_before->ru_inblock,
3624 rusage_after->ru_oublock - rusage_before->ru_oublock,
3625 rusage_after->ru_majflt - rusage_before->ru_majflt,
3626 rusage_after->ru_nswap - rusage_before->ru_nswap);
3630 * Determine if `password' is valid for user given in `pw'.
3631 * Returns 2 if password expired, 1 if otherwise failed, 0 if ok
3634 checkpassword(const struct passwd *pwent, const char *password)
3637 time_t change, expire, now;
3639 change = expire = 0;
3644 orig = pwent->pw_passwd; /* save existing password */
3645 expire = pwent->pw_expire;
3646 change = (pwent->pw_change == _PASSWORD_CHGNOW)? now : pwent->pw_change;
3648 if (orig[0] == '\0') /* don't allow empty passwords */
3651 new = crypt(password, orig); /* encrypt given password */
3652 if (strcmp(new, orig) != 0) /* compare */
3655 if ((expire && now >= expire) || (change && now >= change))
3656 return 2; /* check if expired */
3662 ftpd_strdup(const char *s)
3664 char *new = strdup(s);
3667 fatal("Local resource failure: malloc");
3673 * As per fprintf(), but increment total_bytes and total_bytes_out,
3674 * by the appropriate amount.
3677 cprintf(FILE *fd, const char *fmt, ...)
3683 b = vfprintf(fd, fmt, ap);
3686 total_bytes_out += b;
3691 * the following code is stolen from imap-uw PAM authentication module and
3694 #define COPY_STRING(s) (s ? strdup(s) : NULL)
3697 const char *uname; /* user name */
3698 const char *pass; /* password */
3700 typedef struct cred_t cred_t;
3703 auth_conv(int num_msg, const struct pam_message **msg,
3704 struct pam_response **resp, void *appdata)
3707 cred_t *cred = (cred_t *) appdata;
3708 struct pam_response *myreply;
3710 myreply = calloc(num_msg, sizeof *myreply);
3711 if (myreply == NULL)
3714 for (i = 0; i < num_msg; i++) {
3715 switch (msg[i]->msg_style) {
3716 case PAM_PROMPT_ECHO_ON: /* assume want user name */
3717 myreply[i].resp_retcode = PAM_SUCCESS;
3718 myreply[i].resp = COPY_STRING(cred->uname);
3719 /* PAM frees resp. */
3721 case PAM_PROMPT_ECHO_OFF: /* assume want password */
3722 myreply[i].resp_retcode = PAM_SUCCESS;
3723 myreply[i].resp = COPY_STRING(cred->pass);
3724 /* PAM frees resp. */
3728 myreply[i].resp_retcode = PAM_SUCCESS;
3729 myreply[i].resp = NULL;
3731 default: /* unknown message style */
3733 return PAM_CONV_ERR;
3742 * Attempt to authenticate the user using PAM. Returns 0 if the user is
3743 * authenticated, or 1 if not authenticated. If some sort of PAM system
3744 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
3745 * function returns -1. This can be used as an indication that we should
3746 * fall back to a different authentication mechanism.
3749 auth_pam(struct passwd **ppw, const char *pwstr)
3751 const char *tmpl_user;
3755 cred_t auth_cred = { (*ppw)->pw_name, pwstr };
3756 struct pam_conv conv = { &auth_conv, &auth_cred };
3758 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
3759 if (e != PAM_SUCCESS) {
3761 * In OpenPAM, it's OK to pass NULL to pam_strerror()
3762 * if context creation has failed in the first place.
3764 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
3768 e = pam_set_item(pamh, PAM_RHOST, remotehost);
3769 if (e != PAM_SUCCESS) {
3770 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
3771 pam_strerror(pamh, e));
3772 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
3773 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
3779 e = pam_authenticate(pamh, 0);
3783 * With PAM we support the concept of a "template"
3784 * user. The user enters a login name which is
3785 * authenticated by PAM, usually via a remote service
3786 * such as RADIUS or TACACS+. If authentication
3787 * succeeds, a different but related "template" name
3788 * is used for setting the credentials, shell, and
3789 * home directory. The name the user enters need only
3790 * exist on the remote authentication server, but the
3791 * template name must be present in the local password
3794 * This is supported by two various mechanisms in the
3795 * individual modules. However, from the application's
3796 * point of view, the template user is always passed
3797 * back as a changed value of the PAM_USER item.
3799 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
3801 tmpl_user = (const char *) item;
3802 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
3803 *ppw = sgetpwnam(tmpl_user);
3805 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
3806 pam_strerror(pamh, e));
3811 case PAM_USER_UNKNOWN:
3817 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
3823 e = pam_acct_mgmt(pamh, 0);
3824 if (e != PAM_SUCCESS) {
3825 syslog(LOG_ERR, "pam_acct_mgmt: %s",
3826 pam_strerror(pamh, e));
3832 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
3833 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
3840 #endif /* USE_PAM */