1 /* $NetBSD: ftpd.c,v 1.138 2002/02/11 11:45:07 lukem Exp $ */
4 * Copyright (c) 1997-2001 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. 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.
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
73 * Copyright (C) 1997 and 1998 WIDE Project.
74 * All rights reserved.
76 * Redistribution and use in source and binary forms, with or without
77 * modification, are permitted provided that the following conditions
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.
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
107 #include "lukemftpd.h"
113 #include <arpa/telnet.h>
120 #include <krb5/krb5.h>
125 #include "pathnames.h"
131 int stru; /* avoid C keyword */
133 int dataport; /* use specific data port */
134 int dopidfile; /* maintain pid file */
135 int doutmp; /* update utmp file */
136 int dowtmp; /* update wtmp file */
137 int doxferlog; /* syslog wu-ftpd style xferlog entries */
138 int dropprivs; /* if privileges should or have been dropped */
139 int mapped; /* IPv4 connection on AF_INET6 socket */
142 static char ttyline[20];
143 static struct utmp utmp; /* for utmp */
145 static const char *anondir = NULL;
146 static const char *confdir = _DEFAULT_CONFDIR;
148 #if defined(KERBEROS) || defined(KERBEROS5)
151 char *krbtkfile_env = NULL;
153 int login_krb5_forwardable_tgt = 0;
159 * Timeout intervals for retrying connections
160 * to hosts that don't accept PORT cmds. This
161 * is a kludge, but given the problems with TCP...
163 #define SWAITMAX 90 /* wait at most 90 seconds */
164 #define SWAITINT 5 /* interval between retries */
166 int swaitmax = SWAITMAX;
167 int swaitint = SWAITINT;
169 static int bind_pasv_addr(void);
170 static int checkuser(const char *, const char *, int, int, char **);
171 static int checkaccess(const char *);
172 static int checkpassword(const struct passwd *, const char *);
173 static void end_login(void);
174 static FILE *getdatasock(const char *);
175 static char *gunique(const char *);
176 static void logremotehost(struct sockinet *);
177 static void lostconn(int);
178 static void myoob(int);
179 static int receive_data(FILE *, FILE *);
180 static int send_data(FILE *, FILE *, off_t, int);
181 static struct passwd *sgetpwnam(const char *);
183 int main(int, char *[]);
185 #if defined(KERBEROS)
186 int klogin(struct passwd *, char *, char *, char *);
189 #if defined(KERBEROS5)
190 int k5login(struct passwd *, char *, char *, char *);
191 void k5destroy(void);
197 main(int argc, char *argv[])
199 int addrlen, ch, on = 1, tos, keepalive;
201 krb5_error_code kerror;
205 __progname = strrchr(argv[0], '/');
206 if (__progname == NULL)
207 __progname = argv[0];
217 dopidfile = 1; /* default: DO use a pid file to count users */
218 doutmp = 0; /* default: Do NOT log to utmp */
219 dowtmp = 1; /* default: DO log to wtmp */
220 doxferlog = 0; /* default: Do NOT syslog xferlog */
229 version = FTPD_VERSION;
232 * LOG_NDELAY sets up the logging connection immediately,
233 * necessary for anonymous ftp's that chroot and can't do it later.
235 openlog("ftpd", LOG_PID | LOG_NDELAY, FTPD_LOGTYPE);
237 while ((ch = getopt(argc, argv, "a:c:C:de:h:HlP:qQrst:T:uUvV:wWX"))
249 pw = sgetpwnam(optarg);
250 exit(checkaccess(optarg) ? 0 : 1);
254 case 'v': /* deprecated */
263 strlcpy(hostname, optarg, sizeof(hostname));
267 if (gethostname(hostname, sizeof(hostname)) == -1)
269 hostname[sizeof(hostname) - 1] = '\0';
273 logging++; /* > 1 == extra logging */
277 dataport = (int)strtol(optarg, &p, 10);
278 if (*p != '\0' || dataport < IPPORT_RESERVED ||
279 dataport > IPPORT_ANONMAX) {
280 syslog(LOG_WARNING, "Invalid dataport %s",
305 "-%c has been deprecated in favour of ftpd.conf",
318 if (EMPTYSTR(optarg) || strcmp(optarg, "-") == 0)
321 version = xstrdup(optarg);
337 if (optopt == 'a' || optopt == 'C')
339 syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
343 if (EMPTYSTR(confdir))
344 confdir = _DEFAULT_CONFDIR;
346 memset((char *)&his_addr, 0, sizeof(his_addr));
347 addrlen = sizeof(his_addr.si_su);
348 if (getpeername(0, (struct sockaddr *)&his_addr.si_su, &addrlen) < 0) {
349 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
352 his_addr.su_len = addrlen;
353 memset((char *)&ctrl_addr, 0, sizeof(ctrl_addr));
354 addrlen = sizeof(ctrl_addr.si_su);
355 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
356 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
359 ctrl_addr.su_len = addrlen;
361 if (his_addr.su_family == AF_INET6
362 && IN6_IS_ADDR_V4MAPPED(&his_addr.su_6addr)) {
365 * IPv4 control connection arrived to AF_INET6 socket.
366 * I hate to do this, but this is the easiest solution.
368 * The assumption is untrue on SIIT environment.
370 struct sockinet tmp_addr;
371 const int off = sizeof(struct in6_addr) - sizeof(struct in_addr);
374 memset(&his_addr, 0, sizeof(his_addr));
375 his_addr.su_family = AF_INET;
376 his_addr.su_len = sizeof(his_addr.si_su.su_sin);
377 memcpy(&his_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off],
378 sizeof(his_addr.su_addr));
379 his_addr.su_port = tmp_addr.su_port;
381 tmp_addr = ctrl_addr;
382 memset(&ctrl_addr, 0, sizeof(ctrl_addr));
383 ctrl_addr.su_family = AF_INET;
384 ctrl_addr.su_len = sizeof(ctrl_addr.si_su.su_sin);
385 memcpy(&ctrl_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off],
386 sizeof(ctrl_addr.su_addr));
387 ctrl_addr.su_port = tmp_addr.su_port;
389 while (fgets(line, sizeof(line), fd) != NULL) {
390 if ((cp = strchr(line, '\n')) != NULL)
392 reply(-530, "%s", line);
394 (void) fflush(stdout);
397 "Connection from IPv4 mapped address is not supported.");
406 if (!mapped && his_addr.su_family == AF_INET) {
407 tos = IPTOS_LOWDELAY;
408 if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos,
410 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
413 /* if the hostname hasn't been given, attempt to determine it */
414 if (hostname[0] == '\0') {
415 if (getnameinfo((struct sockaddr *)&ctrl_addr.si_su,
416 ctrl_addr.su_len, hostname, sizeof(hostname), NULL, 0, 0)
418 (void)gethostname(hostname, sizeof(hostname));
419 hostname[sizeof(hostname) - 1] = '\0';
422 /* set this here so klogin can use it... */
423 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
425 (void) freopen(_PATH_DEVNULL, "w", stderr);
426 (void) signal(SIGPIPE, lostconn);
427 (void) signal(SIGCHLD, SIG_IGN);
428 if (signal(SIGURG, myoob) == SIG_ERR)
429 syslog(LOG_WARNING, "signal: %m");
431 /* Try to handle urgent data inline */
433 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
434 syslog(LOG_WARNING, "setsockopt: %m");
436 /* Set keepalives on the socket to detect dropped connections. */
439 if (setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepalive,
441 syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
445 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
446 syslog(LOG_WARNING, "fcntl F_SETOWN: %m");
448 logremotehost(&his_addr);
450 * Set up default state
461 kerror = krb5_init_context(&kcontext);
463 syslog(LOG_ERR, "%s when initializing Kerberos context",
464 error_message(kerror));
467 #endif /* KERBEROS5 */
470 curclass.timeout = 300; /* 5 minutes, as per login(1) */
471 curclass.type = CLASS_REAL;
473 /* If logins are disabled, print out the message. */
474 if (display_file(_PATH_NOLOGIN, 530)) {
475 reply(530, "System not available.");
478 (void)display_file(conffilename(_PATH_FTPWELCOME), 220);
479 /* reply(220,) must follow */
480 if (EMPTYSTR(version))
481 reply(220, "%s FTP server ready.", hostname);
483 reply(220, "%s FTP server (%s) ready.", hostname, version);
485 (void) setjmp(errcatch);
495 syslog(LOG_DEBUG, "lost connection");
500 * Save the result of a getpwnam. Used for USER command, since
501 * the data returned must not be clobbered by any other command
504 static struct passwd *
505 sgetpwnam(const char *name)
507 static struct passwd save;
510 if ((p = getpwnam(name)) == NULL)
513 free((char *)save.pw_name);
514 memset(save.pw_passwd, 0, strlen(save.pw_passwd));
515 free((char *)save.pw_passwd);
516 free((char *)save.pw_gecos);
517 free((char *)save.pw_dir);
518 free((char *)save.pw_shell);
521 save.pw_name = xstrdup(p->pw_name);
522 save.pw_passwd = xstrdup(p->pw_passwd);
523 save.pw_gecos = xstrdup(p->pw_gecos);
524 save.pw_dir = xstrdup(p->pw_dir);
525 save.pw_shell = xstrdup(p->pw_shell);
529 static int login_attempts; /* number of failed login attempts */
530 static int askpasswd; /* had USER command, ask for PASSwd */
531 static int permitted; /* USER permitted */
532 static char curname[10]; /* current USER name */
536 * Sets global passwd pointer pw if named account exists and is acceptable;
537 * sets askpasswd if a PASS command is expected. If logged in previously,
538 * need to reset state. If name is "ftp" or "anonymous", the name is not in
539 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
540 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
541 * requesting login privileges. Disallow anyone who does not have a standard
542 * shell as returned by getusershell(). Disallow anyone mentioned in the file
543 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
546 user(const char *name)
552 switch (curclass.type) {
554 reply(530, "Can't change user from guest login.");
557 reply(530, "Can't change user from chroot user.");
561 reply(530, "Can't change user.");
571 #if defined(KERBEROS)
574 #if defined(KERBEROS5)
578 curclass.type = CLASS_REAL;
582 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
583 /* need `pw' setup for checkaccess() and checkuser () */
584 if ((pw = sgetpwnam("ftp")) == NULL)
585 reply(530, "User %s unknown.", name);
586 else if (! checkaccess("ftp") || ! checkaccess("anonymous"))
587 reply(530, "User %s access denied.", name);
589 curclass.type = CLASS_GUEST;
592 "Guest login ok, type your name as password.");
597 "ANONYMOUS FTP LOGIN REFUSED FROM %s",
604 pw = sgetpwnam(name);
607 strlcpy(curname, name, sizeof(curname));
609 /* check user in /etc/ftpusers, and setup class */
610 permitted = checkuser(_PATH_FTPUSERS, curname, 1, 0, &class);
612 /* check user in /etc/ftpchroot */
613 if (checkuser(_PATH_FTPCHROOT, curname, 0, 0, NULL)) {
614 if (curclass.type == CLASS_GUEST) {
616 "Can't change guest user to chroot class; remove entry in %s",
620 curclass.type = CLASS_CHROOT;
622 /* determine default class */
624 switch (curclass.type) {
626 class = xstrdup("guest");
629 class = xstrdup("chroot");
632 class = xstrdup("real");
635 syslog(LOG_ERR, "unknown curclass.type %d; aborting",
640 /* parse ftpd.conf, setting up various parameters */
642 /* if not guest user, check for valid shell */
646 const char *cp, *shell;
648 if ((shell = pw->pw_shell) == NULL || *shell == 0)
649 shell = _PATH_BSHELL;
650 while ((cp = getusershell()) != NULL)
651 if (strcmp(cp, shell) == 0)
654 if (cp == NULL && curclass.type != CLASS_GUEST)
658 /* deny quickly (after USER not PASS) if requested */
659 if (CURCLASS_FLAGS_ISSET(denyquick) && !permitted) {
660 reply(530, "User %s may not use FTP.", curname);
662 syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
663 remotehost, curname);
668 /* if haven't asked yet (i.e, not anon), ask now */
672 if (skey_haskey(curname) == 0) {
675 myskey = skey_keyinfo(curname);
676 reply(331, "Password [ %s ] required for %s.",
677 myskey ? myskey : "error getting challenge",
681 reply(331, "Password required for %s.", curname);
686 * Delay before reading passwd after first failed
687 * attempt to slow down passwd-guessing programs.
690 sleep((unsigned) login_attempts);
697 * Determine whether something is to happen (allow access, chroot)
698 * for a user. Each line is a shell-style glob followed by
701 * For backward compatibility, `allow' and `deny' are synonymns
702 * for `yes' and `no', respectively.
704 * Each glob is matched against the username in turn, and the first
705 * match found is used. If no match is found, the result is the
706 * argument `def'. If a match is found but without and explicit
707 * `yes'/`no', the result is the opposite of def.
709 * If the file doesn't exist at all, the result is the argument
712 * Any line starting with `#' is considered a comment and ignored.
714 * Returns 0 if the user is denied, or 1 if they are allowed.
716 * NOTE: needs struct passwd *pw setup before use.
719 checkuser(const char *fname, const char *name, int def, int nofile,
724 char *word, *perm, *class, *buf, *p;
728 if (retclass != NULL)
730 if ((fd = fopen(conffilename(fname), "r")) == NULL)
735 (buf = fparseln(fd, &len, &line, NULL, FPARSELN_UNESCCOMM |
736 FPARSELN_UNESCCONT | FPARSELN_UNESCESC)) != NULL;
737 free(buf), buf = NULL) {
738 word = perm = class = NULL;
742 if (p[len - 1] == '\n')
752 if (!EMPTYSTR(class)) {
753 if (strcasecmp(class, "all") == 0 ||
754 strcasecmp(class, "none") == 0) {
756 "%s line %d: illegal user-defined class `%s' - skipping entry",
757 fname, (int)line, class);
762 /* have a host specifier */
763 if ((p = strchr(word, '@')) != NULL) {
764 unsigned long net, mask, addr;
768 /* check against network or CIDR */
770 (bits = inet_net_pton(AF_INET, p,
771 &net, sizeof(net))) != -1) {
773 mask = 0xffffffffU << (32 - bits);
774 addr = ntohl(his_addr.su_addr.s_addr);
775 if ((addr & mask) != net)
778 /* check against hostname glob */
779 } else if (fnmatch(p, remotehost, FNM_CASEFOLD) != 0)
783 /* have a group specifier */
784 if ((p = strchr(word, ':')) != NULL) {
789 continue; /* no match for unknown user */
794 ng = realloc(groups, gsize * sizeof(gid_t));
797 "Local resource failure: realloc");
799 } while (getgrouplist(pw->pw_name, pw->pw_gid,
800 groups, &gsize) == -1);
802 for (i = 0; i < gsize; i++) {
805 if ((g = getgrgid(groups[i])) == NULL)
807 if (fnmatch(p, g->gr_name, 0) == 0) {
817 /* check against username glob */
818 if (fnmatch(word, name, 0) != 0)
822 ((strcasecmp(perm, "allow") == 0) ||
823 (strcasecmp(perm, "yes") == 0)))
825 else if (perm != NULL &&
826 ((strcasecmp(perm, "deny") == 0) ||
827 (strcasecmp(perm, "no") == 0)))
831 if (!EMPTYSTR(class) && retclass != NULL)
832 *retclass = xstrdup(class);
841 * Check if user is allowed by /etc/ftpusers
842 * returns 1 for yes, 0 for no
844 * NOTE: needs struct passwd *pw setup (for checkuser())
847 checkaccess(const char *name)
850 return (checkuser(_PATH_FTPUSERS, name, 1, 0, NULL));
854 * Terminate login as previous user (if any), resetting state;
855 * used when USER command is given or login fails.
864 logwtmp(ttyline, "", "");
866 logout(utmp.ut_line);
869 /* reset login state */
870 show_chdir_messages(-1); /* flush chdir cache */
871 if (pw != NULL && pw->pw_passwd != NULL)
872 memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
879 curclass.type = CLASS_REAL;
880 (void) seteuid((uid_t)0);
884 pass(const char *passwd)
887 char root[MAXPATHLEN];
891 if (logged_in || askpasswd == 0) {
892 reply(503, "Login with USER first.");
896 if (curclass.type != CLASS_GUEST) {
897 /* "ftp" is the only account allowed with no password */
899 rval = 1; /* failure below */
902 #if defined(KERBEROS)
903 if (klogin(pw, "", hostname, (char *)passwd) == 0) {
908 #if defined(KERBEROS5)
909 if (k5login(pw, "", hostname, (char *)passwd) == 0) {
915 if (skey_haskey(pw->pw_name) == 0) {
920 r = skey_passcheck(pw->pw_name, p);
929 rval = checkpassword(pw, passwd);
936 * If rval > 0, the user failed the authentication check
937 * above. If rval == 0, either Kerberos or local
938 * authentication succeeded.
941 reply(530, "%s", rval == 2 ? "Password expired." :
945 "FTP LOGIN FAILED FROM %s", remotehost);
946 syslog(LOG_AUTHPRIV | LOG_NOTICE,
947 "FTP LOGIN FAILED FROM %s, %s",
948 remotehost, curname);
951 if (login_attempts++ >= 5) {
953 "repeated login failures from %s",
961 /* password ok; check if anything else prevents login */
963 reply(530, "User %s may not use FTP.", pw->pw_name);
965 syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
966 remotehost, pw->pw_name);
970 login_attempts = 0; /* this time successful */
971 if (setegid((gid_t)pw->pw_gid) < 0) {
972 reply(550, "Can't set gid.");
975 (void) initgroups(pw->pw_name, pw->pw_gid);
976 /* cache groups for cmds.c::matchgroup() */
977 gidcount = getgroups(sizeof(gidlist), gidlist);
979 /* open wtmp before chroot */
982 logwtmp(ttyline, pw->pw_name, remotehost);
984 /* open utmp before chroot */
986 memset((void *)&utmp, 0, sizeof(utmp));
987 (void)time(&utmp.ut_time);
988 (void)strncpy(utmp.ut_name, pw->pw_name, sizeof(utmp.ut_name));
989 (void)strncpy(utmp.ut_host, remotehost, sizeof(utmp.ut_host));
990 (void)strncpy(utmp.ut_line, ttyline, sizeof(utmp.ut_line));
1000 if (curclass.limit != -1 && connections > curclass.limit) {
1001 if (! EMPTYSTR(curclass.limitfile))
1002 (void)display_file(conffilename(curclass.limitfile),
1005 "User %s access denied, connection limit of %d reached.",
1006 pw->pw_name, curclass.limit);
1008 "Maximum connection limit of %d for class %s reached, login refused for %s",
1009 curclass.limit, curclass.classname, pw->pw_name);
1014 switch (curclass.type) {
1017 * We MUST do a chdir() after the chroot. Otherwise
1018 * the old current directory will be accessible as "."
1019 * outside the new root!
1022 curclass.chroot ? curclass.chroot :
1025 format_path(homedir,
1026 curclass.homedir ? curclass.homedir :
1028 if (EMPTYSTR(homedir))
1030 if (EMPTYSTR(root) || chroot(root) < 0) {
1032 "GUEST user %s: can't chroot to %s: %m",
1036 if (chdir(homedir) < 0) {
1038 "GUEST user %s: can't chdir to %s: %m",
1039 pw->pw_name, homedir);
1041 reply(550, "Can't set guest privileges.");
1047 curclass.chroot ? curclass.chroot :
1049 format_path(homedir,
1050 curclass.homedir ? curclass.homedir :
1052 if (EMPTYSTR(homedir))
1054 if (EMPTYSTR(root) || chroot(root) < 0) {
1056 "CHROOT user %s: can't chroot to %s: %m",
1060 if (chdir(homedir) < 0) {
1062 "CHROOT user %s: can't chdir to %s: %m",
1063 pw->pw_name, homedir);
1065 reply(550, "Can't change root.");
1070 /* only chroot REAL if explictly requested */
1071 if (! EMPTYSTR(curclass.chroot)) {
1072 format_path(root, curclass.chroot);
1073 if (EMPTYSTR(root) || chroot(root) < 0) {
1075 "REAL user %s: can't chroot to %s: %m",
1080 format_path(homedir,
1081 curclass.homedir ? curclass.homedir :
1083 if (EMPTYSTR(homedir) || chdir(homedir) < 0) {
1084 if (chdir("/") < 0) {
1086 "REAL user %s: can't chdir to %s: %m",
1088 !EMPTYSTR(homedir) ? homedir : "/");
1090 "User %s: can't change directory to %s.",
1092 !EMPTYSTR(homedir) ? homedir : "/");
1096 "No directory! Logging in with home=/");
1103 setlogin(pw->pw_name);
1106 (curclass.type != CLASS_REAL &&
1107 ntohs(ctrl_addr.su_port) > IPPORT_RESERVED + 1)) {
1109 if (setgid((gid_t)pw->pw_gid) < 0) {
1110 reply(550, "Can't set gid.");
1113 if (setuid((uid_t)pw->pw_uid) < 0) {
1114 reply(550, "Can't set uid.");
1118 if (seteuid((uid_t)pw->pw_uid) < 0) {
1119 reply(550, "Can't set uid.");
1123 len = sizeof("HOME=") + strlen(homedir) + 1;;
1126 reply(550, "Local resource failure: malloc");
1129 snprintf(p, len, "HOME=%s", homedir);
1133 if (curclass.type == CLASS_GUEST && passwd[0] == '-')
1137 * Display a login message, if it exists.
1138 * N.B. reply(230,) must follow the message.
1140 if (! EMPTYSTR(curclass.motd))
1141 (void)display_file(conffilename(curclass.motd), 230);
1142 show_chdir_messages(230);
1143 if (curclass.type == CLASS_GUEST) {
1146 reply(230, "Guest login ok, access restrictions apply.");
1147 #if HAVE_SETPROCTITLE
1148 snprintf(proctitle, sizeof(proctitle),
1149 "%s: anonymous/%s", remotehost, passwd);
1150 setproctitle("%s", proctitle);
1151 #endif /* HAVE_SETPROCTITLE */
1154 "ANONYMOUS FTP LOGIN FROM %s, %s (class: %s, type: %s)",
1156 curclass.classname, CURCLASSTYPE);
1157 /* store guest password reply into pw_passwd */
1158 REASSIGN(pw->pw_passwd, xstrdup(passwd));
1159 for (p = pw->pw_passwd; *p; p++)
1163 reply(230, "User %s logged in.", pw->pw_name);
1164 #if HAVE_SETPROCTITLE
1165 snprintf(proctitle, sizeof(proctitle),
1166 "%s: %s", remotehost, pw->pw_name);
1167 setproctitle("%s", proctitle);
1168 #endif /* HAVE_SETPROCTITLE */
1171 "FTP LOGIN FROM %s as %s (class: %s, type: %s)",
1172 remotehost, pw->pw_name,
1173 curclass.classname, CURCLASSTYPE);
1175 (void) umask(curclass.umask);
1179 /* Forget all about it... */
1184 retrieve(char *argv[], const char *name)
1188 int (*closefunc)(FILE *) = NULL;
1189 int log, sendrv, closerv, stderrfd, isconversion, isdata, isls;
1190 struct timeval start, finish, td, *tdp;
1191 const char *dispname;
1194 sendrv = closerv = stderrfd = -1;
1195 isconversion = isdata = isls = log = 0;
1200 if (argv == NULL) { /* if not running a command ... */
1203 fin = fopen(name, "r");
1205 if (fin == NULL) /* doesn't exist?; try a conversion */
1206 argv = do_conversion(name);
1209 syslog(LOG_DEBUG, "get command: '%s' on '%s'",
1214 char temp[MAXPATHLEN];
1216 if (strcmp(argv[0], INTERNAL_LS) == 0) {
1220 (void)snprintf(temp, sizeof(temp), "%s", TMPFILE);
1221 stderrfd = mkstemp(temp);
1226 fin = ftpd_popen(argv, "r", stderrfd);
1227 closefunc = ftpd_pclose;
1229 st.st_blksize = BUFSIZ;
1233 perror_reply(550, dispname);
1235 logxfer("get", -1, name, NULL, NULL,
1238 goto cleanupretrieve;
1242 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
1243 error = "Not a plain file";
1244 reply(550, "%s: %s.", dispname, error);
1247 if (restart_point) {
1248 if (type == TYPE_A) {
1252 for (i = 0; i < restart_point; i++) {
1253 if ((c=getc(fin)) == EOF) {
1254 error = strerror(errno);
1255 perror_reply(550, dispname);
1261 } else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
1262 error = strerror(errno);
1263 perror_reply(550, dispname);
1267 dout = dataconn(dispname, st.st_size, "w");
1271 (void)gettimeofday(&start, NULL);
1272 sendrv = send_data(fin, dout, st.st_blksize, isdata);
1273 (void)gettimeofday(&finish, NULL);
1274 closedataconn(dout); /* close now to affect timing stats */
1275 timersub(&finish, &start, &td);
1279 logxfer("get", byte_count, name, NULL, tdp, error);
1280 closerv = (*closefunc)(fin);
1285 if (!isls && argv != NULL && closerv != 0) {
1287 "Command returned an exit status of %d",
1291 "retrieve command: '%s' returned %d",
1294 if (!isls && argv != NULL && stderrfd != -1 &&
1295 (fstat(stderrfd, &sb) == 0) && sb.st_size > 0 &&
1296 ((errf = fdopen(stderrfd, "r")) != NULL)) {
1297 char *cp, line[LINE_MAX];
1299 reply(-226, "Command error messages:");
1301 while (fgets(line, sizeof(line), errf) != NULL) {
1302 if ((cp = strchr(line, '\n')) != NULL)
1304 reply(0, " %s", line);
1306 (void) fflush(stdout);
1307 (void) fclose(errf);
1308 /* a reply(226,) must follow */
1310 reply(226, "Transfer complete.");
1314 (void)close(stderrfd);
1320 store(const char *name, const char *fmode, int unique)
1324 int (*closefunc)(FILE *);
1325 struct timeval start, finish, td, *tdp;
1329 desc = (*fmode == 'w') ? "put" : "append";
1331 if (unique && stat(name, &st) == 0 &&
1332 (name = gunique(name)) == NULL) {
1333 logxfer(desc, -1, name, NULL, NULL,
1334 "cannot create unique file");
1340 fout = fopen(name, fmode);
1344 perror_reply(553, name);
1345 logxfer(desc, -1, name, NULL, NULL, strerror(errno));
1349 if (restart_point) {
1350 if (type == TYPE_A) {
1354 for (i = 0; i < restart_point; i++) {
1355 if ((c=getc(fout)) == EOF) {
1356 error = strerror(errno);
1357 perror_reply(550, name);
1364 * We must do this seek to "current" position
1365 * because we are changing from reading to
1368 if (fseek(fout, 0L, SEEK_CUR) < 0) {
1369 error = strerror(errno);
1370 perror_reply(550, name);
1373 } else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1374 error = strerror(errno);
1375 perror_reply(550, name);
1379 din = dataconn(name, (off_t)-1, "r");
1382 (void)gettimeofday(&start, NULL);
1383 if (receive_data(din, fout) == 0) {
1385 reply(226, "Transfer complete (unique file name:%s).",
1388 reply(226, "Transfer complete.");
1390 (void)gettimeofday(&finish, NULL);
1391 closedataconn(din); /* close now to affect timing stats */
1392 timersub(&finish, &start, &td);
1395 logxfer(desc, byte_count, name, NULL, tdp, error);
1402 getdatasock(const char *fmode)
1404 int on, s, t, tries;
1409 return (fdopen(data, fmode));
1411 (void) seteuid((uid_t)0);
1412 s = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
1415 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
1416 (char *) &on, sizeof(on)) < 0)
1418 if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
1419 (char *) &on, sizeof(on)) < 0)
1421 /* anchor socket to avoid multi-homing problems */
1422 data_source = ctrl_addr;
1424 * By default source port for PORT connctions is
1425 * ctrlport-1 (see RFC959 section 5.2).
1426 * However, if privs have been dropped and that
1427 * would be < IPPORT_RESERVED, use a random port
1433 port = ntohs(ctrl_addr.su_port) - 1;
1434 if (dropprivs && port < IPPORT_RESERVED)
1435 port = 0; /* use random port */
1436 data_source.su_port = htons(port);
1438 for (tries = 1; ; tries++) {
1439 if (bind(s, (struct sockaddr *)&data_source.si_su,
1440 data_source.su_len) >= 0)
1442 if (errno != EADDRINUSE || tries > 10)
1447 (void) seteuid((uid_t)pw->pw_uid);
1449 if (!mapped && ctrl_addr.su_family == AF_INET) {
1450 on = IPTOS_THROUGHPUT;
1451 if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on,
1453 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
1456 return (fdopen(s, fmode));
1458 /* Return the real value of errno (close may change it) */
1461 (void) seteuid((uid_t)pw->pw_uid);
1468 dataconn(const char *name, off_t size, const char *fmode)
1472 int retry = 0, tos, keepalive;
1476 if (size != (off_t) -1)
1477 (void)snprintf(sizebuf, sizeof(sizebuf), " (" LLF " byte%s)",
1478 (LLT)size, PLURAL(size));
1482 struct sockinet from;
1483 int s, fromlen = sizeof(from.su_len);
1485 (void) alarm(curclass.timeout);
1486 s = accept(pdata, (struct sockaddr *)&from.si_su, &fromlen);
1489 reply(425, "Can't open data connection.");
1490 (void) close(pdata);
1494 (void) close(pdata);
1496 switch (from.su_family) {
1500 tos = IPTOS_THROUGHPUT;
1501 (void) setsockopt(s, IPPROTO_IP, IP_TOS,
1502 (char *)&tos, sizeof(int));
1507 /* Set keepalives on the socket to detect dropped conns. */
1510 (void) setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
1511 (char *)&keepalive, sizeof(int));
1513 reply(150, "Opening %s mode data connection for '%s'%s.",
1514 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1515 return (fdopen(pdata, fmode));
1518 reply(125, "Using existing data connection for '%s'%s.",
1521 return (fdopen(data, fmode));
1524 data_dest = his_addr;
1526 file = getdatasock(fmode);
1528 char hbuf[NI_MAXHOST];
1529 char pbuf[NI_MAXSERV];
1531 if (getnameinfo((struct sockaddr *)&data_source.si_su,
1532 data_source.su_len, hbuf, sizeof(hbuf), pbuf, sizeof(pbuf),
1533 NI_NUMERICHOST | NI_NUMERICSERV))
1534 strlcpy(hbuf, "?", sizeof(hbuf));
1535 reply(425, "Can't create data socket (%s,%s): %s.",
1536 hbuf, pbuf, strerror(errno));
1539 data = fileno(file);
1540 while (connect(data, (struct sockaddr *)&data_dest.si_su,
1541 data_dest.su_len) < 0) {
1542 if (errno == EADDRINUSE && retry < swaitmax) {
1543 sleep((unsigned) swaitint);
1547 perror_reply(425, "Can't build data connection");
1548 (void) fclose(file);
1552 reply(150, "Opening %s mode data connection for '%s'%s.",
1553 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1558 closedataconn(FILE *fd)
1571 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1572 * encapsulation of the data subject * to Mode, Structure, and Type.
1574 * NB: Form isn't handled.
1577 send_data(FILE *instr, FILE *outstr, off_t blksize, int isdata)
1579 int c, filefd, netfd, rval;
1585 if (setjmp(urgcatch))
1586 goto cleanup_send_data;
1591 /* XXXLUKEM: rate limit ascii send (get) */
1592 (void) alarm(curclass.timeout);
1593 while ((c = getc(instr)) != EOF) {
1598 (void) putc('\r', outstr);
1606 (void) putc(c, outstr);
1613 if ((byte_count % 4096) == 0)
1614 (void) alarm(curclass.timeout);
1623 goto cleanup_send_data;
1627 if ((buf = malloc((size_t)blksize)) == NULL) {
1628 perror_reply(451, "Local resource failure: malloc");
1629 goto cleanup_send_data;
1631 filefd = fileno(instr);
1632 netfd = fileno(outstr);
1633 (void) alarm(curclass.timeout);
1634 if (curclass.rateget) {
1637 struct timeval then, now, td;
1641 (void)gettimeofday(&then, NULL);
1643 bufrem = curclass.rateget;
1644 while (bufrem > 0) {
1645 if ((c = read(filefd, buf,
1646 MIN(blksize, bufrem))) <= 0)
1648 (void) alarm(curclass.timeout);
1652 total_data_out += c;
1655 total_bytes_out += c;
1657 for (bufp = buf; c > 0;
1660 write(netfd, bufp, c)) <= 0)
1665 (void)gettimeofday(&now, NULL);
1666 timersub(&now, &then, &td);
1668 usleep(1000000 - td.tv_usec);
1671 while ((c = read(filefd, buf, (size_t)blksize)) > 0) {
1672 if (write(netfd, buf, c) != c)
1674 (void) alarm(curclass.timeout);
1677 total_data_out += c;
1680 total_bytes_out += c;
1688 goto cleanup_send_data;
1691 reply(550, "Unimplemented TYPE %d in send_data", type);
1692 goto cleanup_send_data;
1697 perror_reply(426, "Data connection");
1698 goto cleanup_send_data;
1702 perror_reply(551, "Error on input file");
1720 * Transfer data from peer to "outstr" using the appropriate encapulation of
1721 * the data subject to Mode, Structure, and Type.
1723 * N.B.: Form isn't handled.
1726 receive_data(FILE *instr, FILE *outstr)
1728 int c, bare_lfs, netfd, filefd, rval;
1739 if (setjmp(urgcatch))
1740 goto cleanup_recv_data;
1742 #define FILESIZECHECK(x) \
1744 if (curclass.maxfilesize != -1 && \
1745 (x) > curclass.maxfilesize) { \
1755 netfd = fileno(instr);
1756 filefd = fileno(outstr);
1757 (void) alarm(curclass.timeout);
1758 if (curclass.rateput) {
1761 struct timeval then, now, td;
1764 (void)gettimeofday(&then, NULL);
1766 for (bufrem = curclass.rateput; bufrem > 0; ) {
1767 if ((c = read(netfd, buf,
1768 MIN(sizeof(buf), bufrem))) <= 0)
1770 FILESIZECHECK(byte_count + c);
1771 if ((d = write(filefd, buf, c)) != c)
1773 (void) alarm(curclass.timeout);
1778 total_bytes_in += c;
1781 (void)gettimeofday(&now, NULL);
1782 timersub(&now, &then, &td);
1784 usleep(1000000 - td.tv_usec);
1787 while ((c = read(netfd, buf, sizeof(buf))) > 0) {
1788 FILESIZECHECK(byte_count + c);
1789 if (write(filefd, buf, c) != c)
1791 (void) alarm(curclass.timeout);
1795 total_bytes_in += c;
1803 goto cleanup_recv_data;
1806 reply(553, "TYPE E not implemented.");
1807 goto cleanup_recv_data;
1810 (void) alarm(curclass.timeout);
1811 /* XXXLUKEM: rate limit ascii receive (put) */
1812 while ((c = getc(instr)) != EOF) {
1818 if ((byte_count % 4096) == 0)
1819 (void) alarm(curclass.timeout);
1825 if ((c = getc(instr)) != '\n') {
1831 if ((byte_count % 4096) == 0)
1832 (void) alarm(curclass.timeout);
1834 FILESIZECHECK(byteswritten);
1835 (void) putc ('\r', outstr);
1836 if (c == '\0' || c == EOF)
1841 FILESIZECHECK(byteswritten);
1842 (void) putc(c, outstr);
1853 "WARNING! %d bare linefeeds received in ASCII mode",
1855 reply(0, "File may not have transferred correctly.");
1858 goto cleanup_recv_data;
1861 reply(550, "Unimplemented TYPE %d in receive_data", type);
1862 goto cleanup_recv_data;
1864 #undef FILESIZECHECK
1868 perror_reply(426, "Data Connection");
1869 goto cleanup_recv_data;
1873 perror_reply(452, "Error writing file");
1874 goto cleanup_recv_data;
1889 struct sockinet *su = NULL;
1890 static char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
1893 off_t otbi, otbo, otb;
1895 a = p = (u_char *)NULL;
1897 reply(-211, "%s FTP server status:", hostname);
1898 reply(0, "Version: %s", EMPTYSTR(version) ? "<suppressed>" : version);
1900 if (!getnameinfo((struct sockaddr *)&his_addr.si_su, his_addr.su_len,
1901 hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST)
1902 && strcmp(remotehost, hbuf) != 0)
1903 reply(0, "Connected to %s (%s)", remotehost, hbuf);
1905 reply(0, "Connected to %s", remotehost);
1908 if (curclass.type == CLASS_GUEST)
1909 reply(0, "Logged in anonymously");
1911 reply(0, "Logged in as %s%s", pw->pw_name,
1912 curclass.type == CLASS_CHROOT ? " (chroot)" : "");
1913 } else if (askpasswd)
1914 reply(0, "Waiting for password");
1916 reply(0, "Waiting for user name");
1917 cprintf(stdout, " TYPE: %s", typenames[type]);
1918 if (type == TYPE_A || type == TYPE_E)
1919 cprintf(stdout, ", FORM: %s", formnames[form]);
1920 if (type == TYPE_L) {
1922 cprintf(stdout, " %d", NBBY);
1924 /* XXX: `bytesize' needs to be defined in this case */
1925 cprintf(stdout, " %d", bytesize);
1928 cprintf(stdout, "; STRUcture: %s; transfer MODE: %s\r\n",
1929 strunames[stru], modenames[mode]);
1932 reply(0, "Data connection open");
1934 } else if (pdata != -1) {
1935 reply(0, "in Passive mode");
1936 if (curclass.advertise.su_len != 0)
1937 su = &curclass.advertise;
1942 } else if (usedefault == 0) {
1944 reply(0, "EPSV only mode (EPSV ALL)");
1947 su = (struct sockinet *)&data_dest;
1950 if (su->su_family == AF_INET) {
1951 a = (u_char *) &su->su_addr;
1952 p = (u_char *) &su->su_port;
1953 #define UC(b) (((int) b) & 0xff)
1954 reply(0, "%s (%d,%d,%d,%d,%d,%d)",
1955 ispassive ? "PASV" : "PORT" ,
1956 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
1957 UC(p[0]), UC(p[1]));
1965 switch (su->su_family) {
1967 a = (u_char *) &su->su_addr;
1968 p = (u_char *) &su->su_port;
1969 alen = sizeof(su->su_addr);
1974 a = (u_char *) &su->su_6addr;
1975 p = (u_char *) &su->su_port;
1976 alen = sizeof(su->su_6addr);
1985 cprintf(stdout, " %s (%d,%d",
1986 ispassive ? "LPSV" : "LPRT", af, alen);
1987 for (i = 0; i < alen; i++)
1988 cprintf(stdout, ",%d", UC(a[i]));
1989 cprintf(stdout, ",%d,%d,%d)\r\n",
1990 2, UC(p[0]), UC(p[1]));
1997 af = af2epsvproto(su->su_family);
2000 struct sockinet tmp;
2004 if (tmp.su_family == AF_INET6)
2005 tmp.su_scope_id = 0;
2007 if (getnameinfo((struct sockaddr *)&tmp.si_su,
2008 tmp.su_len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
2009 NI_NUMERICHOST | NI_NUMERICSERV) == 0)
2010 reply(0, "%s (|%d|%s|%s|)",
2011 ispassive ? "EPSV" : "EPRT",
2015 reply(0, "No data connection");
2019 "Data sent: " LLF " byte%s in " LLF " file%s",
2020 (LLT)total_data_out, PLURAL(total_data_out),
2021 (LLT)total_files_out, PLURAL(total_files_out));
2023 "Data received: " LLF " byte%s in " LLF " file%s",
2024 (LLT)total_data_in, PLURAL(total_data_in),
2025 (LLT)total_files_in, PLURAL(total_files_in));
2027 "Total data: " LLF " byte%s in " LLF " file%s",
2028 (LLT)total_data, PLURAL(total_data),
2029 (LLT)total_files, PLURAL(total_files));
2031 otbi = total_bytes_in;
2032 otbo = total_bytes_out;
2034 reply(0, "Traffic sent: " LLF " byte%s in " LLF " transfer%s",
2035 (LLT)otbo, PLURAL(otbo),
2036 (LLT)total_xfers_out, PLURAL(total_xfers_out));
2037 reply(0, "Traffic received: " LLF " byte%s in " LLF " transfer%s",
2038 (LLT)otbi, PLURAL(otbi),
2039 (LLT)total_xfers_in, PLURAL(total_xfers_in));
2040 reply(0, "Total traffic: " LLF " byte%s in " LLF " transfer%s",
2041 (LLT)otb, PLURAL(otb),
2042 (LLT)total_xfers, PLURAL(total_xfers));
2044 if (logged_in && !CURCLASS_FLAGS_ISSET(private)) {
2048 reply(0, "Class: %s, type: %s",
2049 curclass.classname, CURCLASSTYPE);
2050 reply(0, "Check PORT/LPRT commands: %sabled",
2051 CURCLASS_FLAGS_ISSET(checkportcmd) ? "en" : "dis");
2052 if (! EMPTYSTR(curclass.display))
2053 reply(0, "Display file: %s", curclass.display);
2054 if (! EMPTYSTR(curclass.notify))
2055 reply(0, "Notify fileglob: %s", curclass.notify);
2056 reply(0, "Idle timeout: %d, maximum timeout: %d",
2057 curclass.timeout, curclass.maxtimeout);
2058 reply(0, "Current connections: %d", connections);
2059 if (curclass.limit == -1)
2060 reply(0, "Maximum connections: unlimited");
2062 reply(0, "Maximum connections: %d", curclass.limit);
2063 if (curclass.limitfile)
2064 reply(0, "Connection limit exceeded message file: %s",
2065 conffilename(curclass.limitfile));
2066 if (! EMPTYSTR(curclass.chroot))
2067 reply(0, "Chroot format: %s", curclass.chroot);
2068 reply(0, "Deny bad ftpusers(5) quickly: %sabled",
2069 CURCLASS_FLAGS_ISSET(denyquick) ? "en" : "dis");
2070 if (! EMPTYSTR(curclass.homedir))
2071 reply(0, "Homedir format: %s", curclass.homedir);
2072 if (curclass.maxfilesize == -1)
2073 reply(0, "Maximum file size: unlimited");
2075 reply(0, "Maximum file size: " LLF,
2076 (LLT)curclass.maxfilesize);
2077 if (! EMPTYSTR(curclass.motd))
2078 reply(0, "MotD file: %s", conffilename(curclass.motd));
2080 "Modify commands (CHMOD, DELE, MKD, RMD, RNFR, UMASK): %sabled",
2081 CURCLASS_FLAGS_ISSET(modify) ? "en" : "dis");
2082 reply(0, "Upload commands (APPE, STOR, STOU): %sabled",
2083 CURCLASS_FLAGS_ISSET(upload) ? "en" : "dis");
2084 reply(0, "Sanitize file names: %sabled",
2085 CURCLASS_FLAGS_ISSET(sanenames) ? "en" : "dis");
2086 reply(0, "PASV/LPSV/EPSV connections: %sabled",
2087 CURCLASS_FLAGS_ISSET(passive) ? "en" : "dis");
2088 if (curclass.advertise.su_len != 0) {
2089 char buf[50]; /* big enough for IPv6 address */
2092 bp = inet_ntop(curclass.advertise.su_family,
2093 (void *)&curclass.advertise.su_addr,
2096 reply(0, "PASV advertise address: %s", bp);
2098 if (curclass.portmin && curclass.portmax)
2099 reply(0, "PASV port range: %d - %d",
2100 curclass.portmin, curclass.portmax);
2101 if (curclass.rateget)
2102 reply(0, "Rate get limit: " LLF " bytes/sec",
2103 (LLT)curclass.rateget);
2105 reply(0, "Rate get limit: disabled");
2106 if (curclass.rateput)
2107 reply(0, "Rate put limit: " LLF " bytes/sec",
2108 (LLT)curclass.rateput);
2110 reply(0, "Rate put limit: disabled");
2111 reply(0, "Umask: %.04o", curclass.umask);
2112 for (cp = curclass.conversions; cp != NULL; cp=cp->next) {
2113 if (cp->suffix == NULL || cp->types == NULL ||
2114 cp->command == NULL)
2116 reply(0, "Conversion: %s [%s] disable: %s, command: %s",
2117 cp->suffix, cp->types, cp->disable, cp->command);
2121 reply(211, "End of status");
2125 fatal(const char *s)
2128 reply(451, "Error in server: %s\n", s);
2129 reply(221, "Closing connection due to server error.");
2136 * depending on the value of n, display fmt with a trailing CRLF and
2138 * n < -1 prefix the message with abs(n) + "-" (initial line)
2139 * n == 0 prefix the message with 4 spaces (middle lines)
2140 * n > 0 prefix the message with n + " " (final line)
2143 reply(int n, const char *fmt, ...)
2151 cprintf(stdout, " ");
2153 cprintf(stdout, "%d-", -n);
2155 cprintf(stdout, "%d ", n);
2156 b = vprintf(fmt, ap);
2159 total_bytes_out += b;
2160 cprintf(stdout, "\r\n");
2161 (void)fflush(stdout);
2163 syslog(LOG_DEBUG, "<--- %d%c", abs(n), (n < 0) ? '-' : ' ');
2165 vsyslog(LOG_DEBUG, fmt, ap);
2171 logremotehost(struct sockinet *who)
2174 if (getnameinfo((struct sockaddr *)&who->si_su,
2175 who->su_len, remotehost, sizeof(remotehost), NULL, 0, 0))
2176 strlcpy(remotehost, "?", sizeof(remotehost));
2178 #if HAVE_SETPROCTITLE
2179 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
2180 setproctitle("%s", proctitle);
2181 #endif /* HAVE_SETPROCTITLE */
2183 syslog(LOG_INFO, "connection from %s to %s",
2184 remotehost, hostname);
2188 * Record logout in wtmp file and exit with supplied status.
2191 dologout(int status)
2194 * Prevent reception of SIGURG from resulting in a resumption
2195 * back to the main program loop.
2202 logwtmp(ttyline, "", "");
2204 logout(utmp.ut_line);
2205 #endif /* NO_UTMP */
2207 if (!notickets && krbtkfile_env)
2208 unlink(krbtkfile_env);
2211 /* beware of flushing buffers after a SIGPIPE */
2221 reply(426, "Transfer aborted. Data connection closed.");
2222 reply(226, "Abort successful");
2223 longjmp(urgcatch, 1);
2232 if (file_size != (off_t) -1)
2234 "Status: " LLF " of " LLF " byte%s transferred",
2235 (LLT)byte_count, (LLT)file_size,
2236 PLURAL(byte_count));
2238 reply(213, "Status: " LLF " byte%s transferred",
2239 (LLT)byte_count, PLURAL(byte_count));
2247 /* only process if transfer occurring */
2251 if (getline(cp, sizeof(tmpline), stdin) == NULL) {
2252 reply(221, "You could at least say goodbye.");
2256 ftp_handle_line(cp);
2261 bind_pasv_addr(void)
2263 static int passiveport;
2266 len = pasv_addr.su_len;
2267 if (curclass.portmin == 0 && curclass.portmax == 0) {
2268 pasv_addr.su_port = 0;
2269 return (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len));
2272 if (passiveport == 0) {
2274 passiveport = rand() % (curclass.portmax - curclass.portmin)
2281 if (port > curclass.portmax)
2282 port = curclass.portmin;
2283 else if (port == passiveport) {
2287 pasv_addr.su_port = htons(port);
2288 if (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len) == 0)
2290 if (errno != EADDRINUSE)
2298 * Note: a response of 425 is not mentioned as a possible response to
2299 * the PASV command in RFC959. However, it has been blessed as
2300 * a legitimate response by Jon Postel in a telephone conversation
2301 * with Rick Adams on 25 Jan 89.
2311 pdata = socket(AF_INET, SOCK_STREAM, 0);
2312 if (pdata < 0 || !logged_in) {
2313 perror_reply(425, "Can't open passive connection");
2316 pasv_addr = ctrl_addr;
2318 if (bind_pasv_addr() < 0)
2320 len = pasv_addr.su_len;
2321 if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
2323 pasv_addr.su_len = len;
2324 if (listen(pdata, 1) < 0)
2326 if (curclass.advertise.su_len != 0)
2327 a = (char *) &curclass.advertise.su_addr;
2329 a = (char *) &pasv_addr.su_addr;
2330 p = (char *) &pasv_addr.su_port;
2332 #define UC(b) (((int) b) & 0xff)
2334 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2335 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2339 (void) close(pdata);
2341 perror_reply(425, "Can't open passive connection");
2346 * convert protocol identifier to/from AF
2349 lpsvproto2af(int proto)
2365 af2lpsvproto(int af)
2381 epsvproto2af(int proto)
2397 af2epsvproto(int af)
2413 * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)
2414 * 229 Entering Extended Passive Mode (|||port|)
2417 long_passive(char *cmd, int pf)
2423 syslog(LOG_NOTICE, "long passive but not logged in");
2424 reply(503, "Login with USER first.");
2428 if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) {
2430 * XXX: only EPRT/EPSV ready clients will understand this
2432 if (strcmp(cmd, "EPSV") != 0)
2433 reply(501, "Network protocol mismatch"); /*XXX*/
2435 epsv_protounsupp("Network protocol mismatch");
2442 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2444 perror_reply(425, "Can't open passive connection");
2447 pasv_addr = ctrl_addr;
2448 if (bind_pasv_addr() < 0)
2450 len = pasv_addr.su_len;
2451 if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
2453 pasv_addr.su_len = len;
2454 if (listen(pdata, 1) < 0)
2456 p = (char *) &pasv_addr.su_port;
2458 #define UC(b) (((int) b) & 0xff)
2460 if (strcmp(cmd, "LPSV") == 0) {
2461 struct sockinet *advert;
2463 if (curclass.advertise.su_len != 0)
2464 advert = &curclass.advertise;
2466 advert = &pasv_addr;
2467 switch (advert->su_family) {
2469 a = (char *) &advert->su_addr;
2471 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2472 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2473 2, UC(p[0]), UC(p[1]));
2477 a = (char *) &advert->su_6addr;
2479 "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)",
2481 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2482 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2483 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2484 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2485 2, UC(p[0]), UC(p[1]));
2490 } else if (strcmp(cmd, "EPSV") == 0) {
2491 switch (pasv_addr.su_family) {
2496 reply(229, "Entering Extended Passive Mode (|||%d|)",
2497 ntohs(pasv_addr.su_port));
2501 /* more proper error code? */
2505 (void) close(pdata);
2507 perror_reply(425, "Can't open passive connection");
2512 extended_port(const char *arg)
2518 struct addrinfo hints;
2519 struct addrinfo *res = NULL;
2521 unsigned long proto;
2527 memset(result, 0, sizeof(result));
2528 for (i = 0; i < 3; i++) {
2529 q = strchr(p, delim);
2530 if (!q || *q != delim)
2537 /* some more sanity checks */
2539 (void)strtoul(result[2], &p, 10);
2540 if (!*result[2] || *p)
2543 proto = strtoul(result[0], &p, 10);
2544 if (!*result[0] || *p)
2547 memset(&hints, 0, sizeof(hints));
2548 hints.ai_family = epsvproto2af((int)proto);
2549 if (hints.ai_family < 0)
2551 hints.ai_socktype = SOCK_STREAM;
2552 hints.ai_flags = AI_NUMERICHOST;
2553 if (getaddrinfo(result[1], result[2], &hints, &res))
2557 if (sizeof(data_dest) < res->ai_addrlen)
2559 memcpy(&data_dest.si_su, res->ai_addr, res->ai_addrlen);
2560 data_dest.su_len = res->ai_addrlen;
2562 if (his_addr.su_family == AF_INET6 &&
2563 data_dest.su_family == AF_INET6) {
2564 /* XXX: more sanity checks! */
2565 data_dest.su_scope_id = his_addr.su_scope_id;
2576 reply(500, "Invalid argument, rejected.");
2585 epsv_protounsupp("Protocol not supported");
2595 * 522 Protocol not supported (proto,...)
2596 * as we assume address family for control and data connections are the same,
2597 * we do not return the list of address families we support - instead, we
2598 * return the address family of the control connection.
2601 epsv_protounsupp(const char *message)
2605 proto = af2epsvproto(ctrl_addr.su_family);
2607 reply(501, "%s", message); /* XXX */
2609 reply(522, "%s, use (%d)", message, proto);
2613 * Generate unique name for file with basename "local".
2614 * The file named "local" is already known to exist.
2615 * Generates failure reply on error.
2617 * XXX: this function should under go changes similar to
2618 * the mktemp(3)/mkstemp(3) changes.
2621 gunique(const char *local)
2623 static char new[MAXPATHLEN];
2628 cp = strrchr(local, '/');
2631 if (stat(cp ? local : ".", &st) < 0) {
2632 perror_reply(553, cp ? local : ".");
2637 for (count = 1; count < 100; count++) {
2638 (void)snprintf(new, sizeof(new) - 1, "%s.%d", local, count);
2639 if (stat(new, &st) < 0)
2642 reply(452, "Unique file name cannot be created.");
2647 * Format and send reply containing system error number.
2650 perror_reply(int code, const char *string)
2655 reply(code, "%s: %s.", string, strerror(errno));
2659 static char *onefile[] = {
2665 send_file_list(const char *whichf)
2671 char **dirlist, *dirname, *notglob, *p;
2684 if (strpbrk(whichf, "~{[*?") != NULL) {
2685 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE|GLOB_LIMIT;
2687 memset(&gl, 0, sizeof(gl));
2689 if (glob(whichf, flags, 0, &gl)) {
2690 reply(550, "not found");
2692 } else if (gl.gl_pathc == 0) {
2694 perror_reply(550, whichf);
2697 dirlist = gl.gl_pathv;
2699 notglob = xstrdup(whichf);
2700 onefile[0] = notglob;
2704 /* XXX: } for vi sm */
2706 if (setjmp(urgcatch)) {
2710 while ((dirname = *dirlist++) != NULL) {
2711 int trailingslash = 0;
2713 if (stat(dirname, &st) < 0) {
2715 * If user typed "ls -l", etc, and the client
2716 * used NLST, do what the user meant.
2718 /* XXX: nuke this support? */
2719 if (dirname[0] == '-' && *dirlist == NULL &&
2721 char *argv[] = { INTERNAL_LS, "", NULL };
2724 retrieve(argv, dirname);
2727 perror_reply(550, whichf);
2728 goto cleanup_send_file_list;
2731 if (S_ISREG(st.st_mode)) {
2734 * should we follow RFC959 and not work
2735 * for non directories?
2738 dout = dataconn("file list", (off_t)-1, "w");
2743 cprintf(dout, "%s%s\n", dirname,
2744 type == TYPE_A ? "\r" : "");
2746 } else if (!S_ISDIR(st.st_mode))
2749 if (dirname[strlen(dirname) - 1] == '/')
2752 if ((dirp = opendir(dirname)) == NULL)
2755 while ((dir = readdir(dirp)) != NULL) {
2756 char nbuf[MAXPATHLEN];
2758 if (ISDOTDIR(dir->d_name) || ISDOTDOTDIR(dir->d_name))
2761 (void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
2762 trailingslash ? "" : "/", dir->d_name);
2765 * We have to do a stat to ensure it's
2766 * not a directory or special file.
2770 * should we follow RFC959 and filter out
2771 * non files ? lukem - NO!, or not until
2772 * our ftp client uses MLS{T,D} for completion.
2774 if (simple || (stat(nbuf, &st) == 0 &&
2775 S_ISREG(st.st_mode))) {
2777 dout = dataconn("file list", (off_t)-1,
2784 if (nbuf[0] == '.' && nbuf[1] == '/')
2786 cprintf(dout, "%s%s\n", p,
2787 type == TYPE_A ? "\r" : "");
2790 (void) closedir(dirp);
2794 reply(550, "No files found.");
2795 else if (ferror(dout) != 0)
2796 perror_reply(550, "Data connection");
2798 reply(226, "Transfer complete.");
2800 cleanup_send_file_list:
2802 closedataconn(dout);
2813 conffilename(const char *s)
2815 static char filename[MAXPATHLEN];
2818 strlcpy(filename, s, sizeof(filename));
2820 (void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
2826 * if logging > 1, then based on the arguments, syslog a message:
2827 * if bytes != -1 "<command> <file1> = <bytes> bytes"
2828 * else if file2 != NULL "<command> <file1> <file2>"
2829 * else "<command> <file1>"
2830 * if elapsed != NULL, append "in xxx.yyy seconds"
2831 * if error != NULL, append ": " + error
2833 * if doxferlog != 0, bytes != -1, and command is "get", "put",
2834 * or "append", syslog a wu-ftpd style xferlog entry
2837 logxfer(const char *command, off_t bytes, const char *file1, const char *file2,
2838 const struct timeval *elapsed, const char *error)
2840 char buf[MAXPATHLEN * 2 + 100], realfile[MAXPATHLEN];
2841 const char *r1, *r2;
2846 if (logging <=1 && !doxferlog)
2850 if ((r1 = realpath(file1, realfile)) == NULL)
2853 if ((r2 = realpath(file2, realfile)) == NULL)
2860 len = snprintf(buf, sizeof(buf), "%s %s", command, r1);
2861 if (bytes != (off_t)-1)
2862 len += snprintf(buf + len, sizeof(buf) - len,
2863 " = " LLF " byte%s", (LLT) bytes, PLURAL(bytes));
2864 else if (r2 != NULL)
2865 len += snprintf(buf + len, sizeof(buf) - len,
2867 if (elapsed != NULL)
2868 len += snprintf(buf + len, sizeof(buf) - len,
2869 " in %ld.%.03d seconds", elapsed->tv_sec,
2870 (int)(elapsed->tv_usec / 1000));
2872 len += snprintf(buf + len, sizeof(buf) - len,
2874 syslog(LOG_INFO, "%s", buf);
2879 * syslog wu-ftpd style log entry, prefixed with "xferlog: "
2881 if (!doxferlog || bytes == -1)
2884 if (strcmp(command, "get") == 0)
2886 else if (strcmp(command, "put") == 0 || strcmp(command, "append") == 0)
2893 "xferlog%s: %.24s %ld %s " LLF " %s %c %s %c %c %s FTP 0 * %c",
2896 * XXX: wu-ftpd puts (send) or (recv) in the syslog message, and removes
2897 * the full date. This may be problematic for accurate log parsing,
2898 * given that syslog messages don't contain the full date.
2900 #if 1 /* lukem's method; easier to convert to actual xferlog file */
2903 #else /* wu-ftpd's syslog method, with an extra unneeded space */
2904 (direction == 'i') ? " (recv)" : " (send)",
2907 elapsed == NULL ? 0 : elapsed->tv_sec + (elapsed->tv_usec > 0),
2911 type == TYPE_A ? 'a' : 'b',
2912 "_", /* XXX: take conversions into account? */
2915 curclass.type == CLASS_GUEST ? 'a' :
2916 curclass.type == CLASS_CHROOT ? 'g' :
2917 curclass.type == CLASS_REAL ? 'r' : '?',
2919 curclass.type == CLASS_GUEST ? pw->pw_passwd : pw->pw_name,
2920 error != NULL ? 'i' : 'c'
2925 * Determine if `password' is valid for user given in `pw'.
2926 * Returns 2 if password expired, 1 if otherwise failed, 0 if ok
2929 checkpassword(const struct passwd *pwent, const char *password)
2942 if ((spw = getspnam(pwent->pw_name)) == NULL)
2944 orig = spw->sp_pwdp;
2946 orig = pwent->pw_passwd; /* save existing password */
2948 expire = pwent->pw_expire;
2950 #endif /* HAVE_GETSPNAM */
2952 if (orig[0] == '\0') /* don't allow empty passwords */
2955 new = crypt(password, orig); /* encrypt given password */
2956 if (strcmp(new, orig) != 0) /* compare */
2959 if (expire && time(NULL) >= expire)
2960 return 2; /* check if expired */
2966 xstrdup(const char *s)
2968 char *new = strdup(s);
2971 fatal("Local resource failure: malloc");
2977 * As per fprintf(), but increment total_bytes and total_bytes_out,
2978 * by the appropriate amount.
2981 cprintf(FILE *fd, const char *fmt, ...)
2987 b = vfprintf(fd, fmt, ap);
2990 total_bytes_out += b;