2 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 static char copyright[] =
37 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
38 The Regents of the University of California. All rights reserved.\n";
44 static char sccsid[] = "@(#)ftpd.c 8.4 (Berkeley) 4/16/94";
46 static const char rcsid[] =
53 #include <sys/param.h>
54 #include <sys/ioctl.h>
56 #include <sys/socket.h>
61 #include <netinet/in.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/ip.h>
64 #include <netinet/tcp.h>
68 #include <arpa/inet.h>
69 #include <arpa/telnet.h>
91 #include <login_cap.h>
95 #include <security/pam_appl.h>
98 #include "pathnames.h"
103 static char version[] = "Version 6.00LS";
106 extern off_t restart_point;
109 union sockunion server_addr;
110 union sockunion ctrl_addr;
111 union sockunion data_source;
112 union sockunion data_dest;
113 union sockunion his_addr;
114 union sockunion pasv_addr;
121 int timeout = 900; /* timeout after 15 minutes of inactivity */
122 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
124 int restricted_data_ports = 1;
125 int paranoid = 1; /* be extra careful about security */
126 int anon_only = 0; /* Only anonymous ftp allowed */
134 int stru; /* avoid C keyword */
136 int usedefault = 1; /* for data transfers */
137 int pdata = -1; /* for passive mode */
138 int readonly=0; /* Server is in readonly mode. */
139 int noepsv=0; /* EPSV command is disabled. */
140 int noretr=0; /* RETR command is disabled. */
141 int noguestretr=0; /* RETR command is disabled for anon users. */
142 int noguestmkd=0; /* MKD command is disabled for anon users. */
143 int noguestmod=1; /* anon users may not modify existing files. */
145 static volatile sig_atomic_t recvurg;
146 sig_atomic_t transflag;
149 #if !defined(CMASK) || CMASK == 0
153 int defumask = CMASK; /* default umask value */
158 #ifdef VIRTUAL_HOSTING
161 static struct ftphost {
162 struct ftphost *next;
163 struct addrinfo *hostinfo;
169 } *thishost, *firsthost;
172 char remotehost[MAXHOSTNAMELEN];
175 static char ttyline[20];
176 char *tty = ttyline; /* for klogin */
179 static int auth_pam(struct passwd**, const char*);
180 pam_handle_t *pamh = NULL;
183 static struct opie opiedata;
184 static char opieprompt[OPIE_CHALLENGE_MAX+1];
187 char *pid_file = NULL;
190 * Limit number of pathnames that glob can return.
191 * A limit of 0 indicates the number of pathnames is unlimited.
193 #define MAXGLOBARGS 16384
197 * Timeout intervals for retrying connections
198 * to hosts that don't accept PORT cmds. This
199 * is a kludge, but given the problems with TCP...
201 #define SWAITMAX 90 /* wait at most 90 seconds */
202 #define SWAITINT 5 /* interval between retries */
204 int swaitmax = SWAITMAX;
205 int swaitint = SWAITINT;
208 #ifdef OLD_SETPROCTITLE
209 char **Argv = NULL; /* pointer to argument vector */
210 char *LastArgv = NULL; /* end of argv */
211 #endif /* OLD_SETPROCTITLE */
212 char proctitle[LINE_MAX]; /* initial part of title */
213 #endif /* SETPROCTITLE */
215 #define LOGCMD(cmd, file) \
217 syslog(LOG_INFO,"%s %s%s", cmd, \
218 *(file) == '/' ? "" : curdir(), file);
219 #define LOGCMD2(cmd, file1, file2) \
221 syslog(LOG_INFO,"%s %s%s %s%s", cmd, \
222 *(file1) == '/' ? "" : curdir(), file1, \
223 *(file2) == '/' ? "" : curdir(), file2);
224 #define LOGBYTES(cmd, file, cnt) \
226 if (cnt == (off_t)-1) \
227 syslog(LOG_INFO,"%s %s%s", cmd, \
228 *(file) == '/' ? "" : curdir(), file); \
230 syslog(LOG_INFO, "%s %s%s = %qd bytes", \
231 cmd, (*(file) == '/') ? "" : curdir(), file, cnt); \
234 #ifdef VIRTUAL_HOSTING
235 static void inithosts(void);
236 static void selecthost(union sockunion *);
238 static void ack(char *);
239 static void sigurg(int);
240 static void myoob(void);
241 static int checkuser(char *, char *, int);
242 static FILE *dataconn(char *, off_t, char *);
243 static void dolog(struct sockaddr *);
244 static char *curdir(void);
245 static void end_login(void);
246 static FILE *getdatasock(char *);
247 static int guniquefd(char *, char **);
248 static void lostconn(int);
249 static void sigquit(int);
250 static int receive_data(FILE *, FILE *);
251 static int send_data(FILE *, FILE *, off_t, off_t, int);
252 static struct passwd *
254 static char *sgetsave(char *);
255 static void reapchild(int);
256 static void logxfer(char *, off_t, time_t);
257 static char *doublequote(char *);
262 static char path[MAXPATHLEN+1+1]; /* path + '/' + '\0' */
264 if (getcwd(path, sizeof(path)-2) == NULL)
266 if (path[1] != '\0') /* special case for root dir. */
268 /* For guest account, skip / since it's chrooted */
269 return (guest ? path+1 : path);
273 main(int argc, char *argv[], char **envp)
275 int addrlen, ch, on = 1, tos;
276 char *cp, line[LINE_MAX];
279 char *bindname = NULL;
280 int family = AF_UNSPEC;
284 tzset(); /* in case no timezone database in ~ftp */
285 sigemptyset(&sa.sa_mask);
286 sa.sa_flags = SA_RESTART;
288 #ifdef OLD_SETPROCTITLE
290 * Save start and extent of argv for setproctitle.
295 LastArgv = envp[-1] + strlen(envp[-1]);
296 #endif /* OLD_SETPROCTITLE */
299 while ((ch = getopt(argc, argv, "46a:AdDElmMoOp:rRSt:T:u:UvW")) != -1) {
303 if (family == AF_UNSPEC)
332 logging++; /* > 1 == extra logging */
368 timeout = atoi(optarg);
369 if (maxtimeout < timeout)
370 maxtimeout = timeout;
374 maxtimeout = atoi(optarg);
375 if (timeout > maxtimeout)
376 timeout = maxtimeout;
383 val = strtol(optarg, &optarg, 8);
384 if (*optarg != '\0' || val < 0)
385 warnx("bad value for -u");
391 restricted_data_ports = 0;
403 warnx("unknown flag -%c ignored", optopt);
408 #ifdef VIRTUAL_HOSTING
411 (void) freopen(_PATH_DEVNULL, "w", stderr);
414 * LOG_NDELAY sets up the logging connection immediately,
415 * necessary for anonymous ftp's that chroot and can't do it later.
417 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
421 struct addrinfo hints, *res;
424 * Detach from parent.
426 if (daemon(1, 1) < 0) {
427 syslog(LOG_ERR, "failed to become a daemon");
430 sa.sa_handler = reapchild;
431 (void)sigaction(SIGCHLD, &sa, NULL);
433 memset(&hints, 0, sizeof(hints));
435 hints.ai_family = family == AF_UNSPEC ? AF_INET : family;
436 hints.ai_socktype = SOCK_STREAM;
437 hints.ai_protocol = 0;
438 hints.ai_flags = AI_PASSIVE;
439 error = getaddrinfo(bindname, "ftp", &hints, &res);
441 if (family == AF_UNSPEC) {
442 hints.ai_family = AF_UNSPEC;
443 error = getaddrinfo(bindname, "ftp", &hints,
448 syslog(LOG_ERR, "%s", gai_strerror(error));
449 if (error == EAI_SYSTEM)
450 syslog(LOG_ERR, "%s", strerror(errno));
453 if (res->ai_addr == NULL) {
454 syslog(LOG_ERR, "-a %s: getaddrinfo failed", hostname);
457 family = res->ai_addr->sa_family;
459 * Open a socket, bind it to the FTP port, and start
462 ctl_sock = socket(family, SOCK_STREAM, 0);
464 syslog(LOG_ERR, "control socket: %m");
467 if (setsockopt(ctl_sock, SOL_SOCKET, SO_REUSEADDR,
468 &on, sizeof(on)) < 0)
470 "control setsockopt (SO_REUSEADDR): %m");
471 if (family == AF_INET6 && enable_v4 == 0) {
472 if (setsockopt(ctl_sock, IPPROTO_IPV6, IPV6_V6ONLY,
473 &on, sizeof (on)) < 0)
475 "control setsockopt (IPV6_V6ONLY): %m");
477 memcpy(&server_addr, res->ai_addr, res->ai_addr->sa_len);
478 if (bind(ctl_sock, (struct sockaddr *)&server_addr,
479 server_addr.su_len) < 0) {
480 syslog(LOG_ERR, "control bind: %m");
483 if (listen(ctl_sock, 32) < 0) {
484 syslog(LOG_ERR, "control listen: %m");
488 * Atomically write process ID
495 fd = open(pid_file, O_CREAT | O_WRONLY | O_TRUNC
496 | O_NONBLOCK | O_EXLOCK, 0644);
499 errx(1, "%s: file locked", pid_file);
501 err(1, "%s", pid_file);
503 snprintf(buf, sizeof(buf),
504 "%lu\n", (unsigned long) getpid());
505 if (write(fd, buf, strlen(buf)) < 0)
506 err(1, "%s: write", pid_file);
507 /* Leave the pid file open and locked */
510 * Loop forever accepting connection requests and forking off
511 * children to handle them.
514 addrlen = server_addr.su_len;
515 fd = accept(ctl_sock, (struct sockaddr *)&his_addr, &addrlen);
526 addrlen = sizeof(his_addr);
527 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
528 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
533 sa.sa_handler = SIG_DFL;
534 (void)sigaction(SIGCHLD, &sa, NULL);
536 sa.sa_handler = sigurg;
537 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
538 (void)sigaction(SIGURG, &sa, NULL);
540 sigfillset(&sa.sa_mask); /* block all signals in handler */
541 sa.sa_flags = SA_RESTART;
542 sa.sa_handler = sigquit;
543 (void)sigaction(SIGHUP, &sa, NULL);
544 (void)sigaction(SIGINT, &sa, NULL);
545 (void)sigaction(SIGQUIT, &sa, NULL);
546 (void)sigaction(SIGTERM, &sa, NULL);
548 sa.sa_handler = lostconn;
549 (void)sigaction(SIGPIPE, &sa, NULL);
551 addrlen = sizeof(ctrl_addr);
552 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
553 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
556 #ifdef VIRTUAL_HOSTING
557 /* select our identity from virtual host table */
558 selecthost(&ctrl_addr);
561 if (ctrl_addr.su_family == AF_INET)
563 tos = IPTOS_LOWDELAY;
564 if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
565 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
569 * Disable Nagle on the control channel so that we don't have to wait
570 * for peer's ACK before issuing our next reply.
572 if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
573 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
575 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
577 /* set this here so klogin can use it... */
578 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
580 /* Try to handle urgent data inline */
582 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
583 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
587 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
588 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
590 dolog((struct sockaddr *)&his_addr);
592 * Set up default state
601 /* If logins are disabled, print out the message. */
602 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
603 while (fgets(line, sizeof(line), fd) != NULL) {
604 if ((cp = strchr(line, '\n')) != NULL)
606 lreply(530, "%s", line);
608 (void) fflush(stdout);
610 reply(530, "System not available.");
613 #ifdef VIRTUAL_HOSTING
614 if ((fd = fopen(thishost->welcome, "r")) != NULL) {
616 if ((fd = fopen(_PATH_FTPWELCOME, "r")) != NULL) {
618 while (fgets(line, sizeof(line), fd) != NULL) {
619 if ((cp = strchr(line, '\n')) != NULL)
621 lreply(220, "%s", line);
623 (void) fflush(stdout);
625 /* reply(220,) must follow */
627 #ifndef VIRTUAL_HOSTING
628 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
629 fatalerror("Ran out of memory.");
630 (void) gethostname(hostname, MAXHOSTNAMELEN - 1);
631 hostname[MAXHOSTNAMELEN - 1] = '\0';
633 reply(220, "%s FTP server (%s) ready.", hostname, version);
644 syslog(LOG_DEBUG, "lost connection");
652 syslog(LOG_ERR, "got signal %d", signo);
656 #ifdef VIRTUAL_HOSTING
658 * read in virtual host tables (if they exist)
667 char *cp, *mp, *line;
669 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
670 struct ftphost *hrp, *lhrp;
671 struct addrinfo hints, *res, *ai;
674 * Fill in the default host information
676 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
677 fatalerror("Ran out of memory.");
678 if (gethostname(hostname, MAXHOSTNAMELEN) < 0)
680 hostname[MAXHOSTNAMELEN - 1] = '\0';
681 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
682 fatalerror("Ran out of memory.");
683 hrp->hostname = hostname;
684 hrp->hostinfo = NULL;
686 memset(&hints, 0, sizeof(hints));
687 hints.ai_flags = AI_CANONNAME;
688 hints.ai_family = AF_UNSPEC;
689 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
691 hrp->statfile = _PATH_FTPDSTATFILE;
692 hrp->welcome = _PATH_FTPWELCOME;
693 hrp->loginmsg = _PATH_FTPLOGINMESG;
694 hrp->anonuser = "ftp";
696 thishost = firsthost = lhrp = hrp;
697 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
698 int addrsize, gothost;
702 while ((line = fgetln(fp, &len)) != NULL) {
708 if (line[len - 1] == '\n') {
709 line[len - 1] = '\0';
712 if ((mp = malloc(len + 1)) == NULL)
713 fatalerror("Ran out of memory.");
714 memcpy(mp, line, len);
718 cp = strtok(line, " \t");
719 /* skip empty lines */
726 statfile = _PATH_FTPDSTATFILE;
727 welcome = _PATH_FTPWELCOME;
728 loginmsg = _PATH_FTPLOGINMESG;
731 * Preparse the line so we can use its info
732 * for all the addresses associated with
733 * the virtual host name.
734 * Field 0, the virtual host name, is special:
735 * it's already parsed off and will be strdup'ed
736 * later, after we know its canonical form.
738 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
739 if (*cp != '-' && (cp = strdup(cp)))
741 case 1: /* anon user permissions */
744 case 2: /* statistics file */
747 case 3: /* welcome message */
750 case 4: /* login message */
753 default: /* programming error */
759 hints.ai_family = AF_UNSPEC;
760 hints.ai_flags = AI_PASSIVE;
761 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
763 for (ai = res; ai != NULL && ai->ai_addr != NULL;
767 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
770 for (hi = hrp->hostinfo; hi != NULL;
772 if (hi->ai_addrlen == ai->ai_addrlen &&
775 ai->ai_addr->sa_len) == 0) {
783 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
785 hrp->hostname = NULL;
789 freeaddrinfo(hrp->hostinfo);
790 insert = 0; /* host already in the chain */
795 * determine hostname to use.
796 * force defined name if there is a valid alias
797 * otherwise fallback to primary hostname
799 /* XXX: getaddrinfo() can't do alias check */
800 switch(hrp->hostinfo->ai_family) {
802 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
803 addrsize = sizeof(struct in_addr);
806 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
807 addrsize = sizeof(struct in6_addr);
810 /* should not reach here */
811 freeaddrinfo(hrp->hostinfo);
813 free(hrp); /*not in chain, can free*/
815 hrp->hostinfo = NULL; /*mark as blank*/
819 if ((hp = getipnodebyaddr(addr, addrsize,
820 hrp->hostinfo->ai_family,
821 &hp_error)) != NULL) {
822 if (strcmp(vhost, hp->h_name) != 0) {
823 if (hp->h_aliases == NULL)
827 while (hp->h_aliases[i] &&
828 strcmp(vhost, hp->h_aliases[i]) != 0)
830 if (hp->h_aliases[i] == NULL)
836 strcmp(hrp->hostname, vhost) != 0) {
838 hrp->hostname = NULL;
840 if (hrp->hostname == NULL &&
841 (hrp->hostname = strdup(vhost)) == NULL) {
842 freeaddrinfo(hrp->hostinfo);
843 hrp->hostinfo = NULL; /* mark as blank */
848 hrp->anonuser = anonuser;
849 hrp->statfile = statfile;
850 hrp->welcome = welcome;
851 hrp->loginmsg = loginmsg;
869 selecthost(union sockunion *su)
874 struct in6_addr *mapped_in6 = NULL;
880 * XXX IPv4 mapped IPv6 addr consideraton,
881 * specified in rfc2373.
883 if (su->su_family == AF_INET6 &&
884 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
885 mapped_in6 = &su->su_sin6.sin6_addr;
888 hrp = thishost = firsthost; /* default */
891 while (hrp != NULL) {
892 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
893 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
898 /* XXX IPv4 mapped IPv6 addr consideraton */
899 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
900 (memcmp(&mapped_in6->s6_addr[12],
901 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
902 sizeof(struct in_addr)) == 0)) {
911 /* setup static variables as appropriate */
912 hostname = thishost->hostname;
913 ftpuser = thishost->anonuser;
918 * Helper function for sgetpwnam().
923 char *new = malloc((unsigned) strlen(s) + 1);
926 perror_reply(421, "Local resource failure: malloc");
930 (void) strcpy(new, s);
935 * Save the result of a getpwnam. Used for USER command, since
936 * the data returned must not be clobbered by any other command
939 static struct passwd *
940 sgetpwnam(char *name)
942 static struct passwd save;
945 if ((p = getpwnam(name)) == NULL)
949 free(save.pw_passwd);
955 save.pw_name = sgetsave(p->pw_name);
956 save.pw_passwd = sgetsave(p->pw_passwd);
957 save.pw_gecos = sgetsave(p->pw_gecos);
958 save.pw_dir = sgetsave(p->pw_dir);
959 save.pw_shell = sgetsave(p->pw_shell);
963 static int login_attempts; /* number of failed login attempts */
964 static int askpasswd; /* had user command, ask for passwd */
965 static char curname[MAXLOGNAME]; /* current USER name */
969 * Sets global passwd pointer pw if named account exists and is acceptable;
970 * sets askpasswd if a PASS command is expected. If logged in previously,
971 * need to reset state. If name is "ftp" or "anonymous", the name is not in
972 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
973 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
974 * requesting login privileges. Disallow anyone who does not have a standard
975 * shell as returned by getusershell(). Disallow anyone mentioned in the file
976 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
985 reply(530, "Can't change user from guest login.");
987 } else if (dochroot) {
988 reply(530, "Can't change user from chroot user.");
995 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
996 if (checkuser(_PATH_FTPUSERS, "ftp", 0) ||
997 checkuser(_PATH_FTPUSERS, "anonymous", 0))
998 reply(530, "User %s access denied.", name);
999 #ifdef VIRTUAL_HOSTING
1000 else if ((pw = sgetpwnam(thishost->anonuser)) != NULL) {
1002 else if ((pw = sgetpwnam("ftp")) != NULL) {
1007 "Guest login ok, send your email address as password.");
1009 reply(530, "User %s unknown.", name);
1010 if (!askpasswd && logging)
1012 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1015 if (anon_only != 0) {
1016 reply(530, "Sorry, only anonymous ftp allowed.");
1020 if ((pw = sgetpwnam(name))) {
1021 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1022 shell = _PATH_BSHELL;
1023 while ((cp = getusershell()) != NULL)
1024 if (strcmp(cp, shell) == 0)
1028 if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1)) {
1029 reply(530, "User %s access denied.", name);
1032 "FTP LOGIN REFUSED FROM %s, %s",
1034 pw = (struct passwd *) NULL;
1039 strncpy(curname, name, sizeof(curname)-1);
1043 /* XXX Kluge! The conversation mechanism needs to be fixed. */
1045 if (opiechallenge(&opiedata, name, opieprompt) == 0) {
1046 pwok = (pw != NULL) &&
1047 opieaccessfile(remotehost) &&
1048 opiealways(pw->pw_dir);
1049 reply(331, "Response to %s %s for %s.",
1050 opieprompt, pwok ? "requested" : "required", name);
1053 reply(331, "Password required for %s.", name);
1057 * Delay before reading passwd after first failed
1058 * attempt to slow down passwd-guessing programs.
1061 sleep((unsigned) login_attempts);
1065 * Check if a user is in the file "fname"
1068 checkuser(char *fname, char *name, int pwset)
1073 char *line, *mp, *p;
1075 if ((fd = fopen(fname, "r")) != NULL) {
1076 while (!found && (line = fgetln(fd, &len)) != NULL) {
1080 if (line[len - 1] == '\n') {
1081 line[len - 1] = '\0';
1084 if ((mp = malloc(len + 1)) == NULL)
1085 fatalerror("Ran out of memory.");
1086 memcpy(mp, line, len);
1090 /* avoid possible leading and trailing whitespace */
1091 p = strtok(line, " \t");
1092 /* skip empty lines */
1096 * if first chr is '@', check group membership
1102 if ((grp = getgrnam(p+1)) == NULL)
1105 * Check user's default group
1107 if (pwset && grp->gr_gid == pw->pw_gid)
1110 * Check supplementary groups
1112 while (!found && grp->gr_mem[i])
1113 found = strcmp(name,
1118 * Otherwise, just check for username match
1121 found = strcmp(p, name) == 0;
1132 * Terminate login as previous user, if any, resetting state;
1133 * used when USER command is given or login fails.
1142 (void) seteuid((uid_t)0);
1143 if (logged_in && dowtmp)
1144 ftpd_logwtmp(ttyline, "", NULL);
1147 setusercontext(NULL, getpwuid(0), (uid_t)0,
1148 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1151 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1152 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1153 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1154 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1155 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1156 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1167 * the following code is stolen from imap-uw PAM authentication module and
1170 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1173 const char *uname; /* user name */
1174 const char *pass; /* password */
1176 typedef struct cred_t cred_t;
1179 auth_conv(int num_msg, const struct pam_message **msg,
1180 struct pam_response **resp, void *appdata)
1183 cred_t *cred = (cred_t *) appdata;
1184 struct pam_response *reply;
1186 reply = calloc(num_msg, sizeof *reply);
1190 for (i = 0; i < num_msg; i++) {
1191 switch (msg[i]->msg_style) {
1192 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1193 reply[i].resp_retcode = PAM_SUCCESS;
1194 reply[i].resp = COPY_STRING(cred->uname);
1195 /* PAM frees resp. */
1197 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1198 reply[i].resp_retcode = PAM_SUCCESS;
1199 reply[i].resp = COPY_STRING(cred->pass);
1200 /* PAM frees resp. */
1204 reply[i].resp_retcode = PAM_SUCCESS;
1205 reply[i].resp = NULL;
1207 default: /* unknown message style */
1209 return PAM_CONV_ERR;
1218 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1219 * authenticated, or 1 if not authenticated. If some sort of PAM system
1220 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1221 * function returns -1. This can be used as an indication that we should
1222 * fall back to a different authentication mechanism.
1225 auth_pam(struct passwd **ppw, const char *pass)
1227 pam_handle_t *pamh = NULL;
1228 const char *tmpl_user;
1232 cred_t auth_cred = { (*ppw)->pw_name, pass };
1233 struct pam_conv conv = { &auth_conv, &auth_cred };
1235 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1236 if (e != PAM_SUCCESS) {
1237 syslog(LOG_ERR, "pam_start: %s", pam_strerror(pamh, e));
1241 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1242 if (e != PAM_SUCCESS) {
1243 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1244 pam_strerror(pamh, e));
1248 e = pam_authenticate(pamh, 0);
1252 * With PAM we support the concept of a "template"
1253 * user. The user enters a login name which is
1254 * authenticated by PAM, usually via a remote service
1255 * such as RADIUS or TACACS+. If authentication
1256 * succeeds, a different but related "template" name
1257 * is used for setting the credentials, shell, and
1258 * home directory. The name the user enters need only
1259 * exist on the remote authentication server, but the
1260 * template name must be present in the local password
1263 * This is supported by two various mechanisms in the
1264 * individual modules. However, from the application's
1265 * point of view, the template user is always passed
1266 * back as a changed value of the PAM_USER item.
1268 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1270 tmpl_user = (const char *) item;
1271 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1272 *ppw = getpwnam(tmpl_user);
1274 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1275 pam_strerror(pamh, e));
1280 case PAM_USER_UNKNOWN:
1286 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1292 e = pam_acct_mgmt(pamh, 0);
1293 if (e == PAM_NEW_AUTHTOK_REQD) {
1294 e = pam_chauthtok(pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
1295 if (e != PAM_SUCCESS) {
1296 syslog(LOG_ERR, "pam_chauthtok: %s", pam_strerror(pamh, e));
1299 } else if (e != PAM_SUCCESS) {
1305 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1306 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1313 #endif /* USE_PAM */
1321 login_cap_t *lc = NULL;
1328 if (logged_in || askpasswd == 0) {
1329 reply(503, "Login with USER first.");
1333 if (!guest) { /* "ftp" is only account allowed no password */
1335 rval = 1; /* failure below */
1339 rval = auth_pam(&pw, passwd);
1345 if (opieverify(&opiedata, passwd) == 0)
1346 xpasswd = pw->pw_passwd;
1348 xpasswd = crypt(passwd, pw->pw_passwd);
1349 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1355 rval = strcmp(pw->pw_passwd, xpasswd);
1356 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1357 rval = 1; /* failure */
1360 * If rval == 1, the user failed the authentication check
1361 * above. If rval == 0, either PAM or local authentication
1365 reply(530, "Login incorrect.");
1368 "FTP LOGIN FAILED FROM %s, %s",
1369 remotehost, curname);
1371 if (login_attempts++ >= 5) {
1373 "repeated login failures from %s",
1380 login_attempts = 0; /* this time successful */
1381 if (setegid((gid_t)pw->pw_gid) < 0) {
1382 reply(550, "Can't set gid.");
1385 /* May be overridden by login.conf */
1386 (void) umask(defumask);
1388 if ((lc = login_getpwclass(pw)) != NULL) {
1389 char remote_ip[MAXHOSTNAMELEN];
1391 getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1392 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1394 remote_ip[sizeof(remote_ip) - 1] = 0;
1395 if (!auth_hostok(lc, remotehost, remote_ip)) {
1396 syslog(LOG_INFO|LOG_AUTH,
1397 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1399 reply(530, "Permission denied.\n");
1403 if (!auth_timeok(lc, time(NULL))) {
1404 reply(530, "Login not available right now.\n");
1409 setusercontext(lc, pw, (uid_t)0,
1410 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1411 LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1413 setlogin(pw->pw_name);
1414 (void) initgroups(pw->pw_name, pw->pw_gid);
1419 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1420 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1421 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1422 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1427 /* open wtmp before chroot */
1429 ftpd_logwtmp(ttyline, pw->pw_name,
1430 (struct sockaddr *)&his_addr);
1433 if (guest && stats && statfd < 0)
1434 #ifdef VIRTUAL_HOSTING
1435 if ((statfd = open(thishost->statfile, O_WRONLY|O_APPEND)) < 0)
1437 if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0)
1442 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1443 login_getcapbool(lc, "ftp-chroot", 0) ||
1445 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1);
1448 * We MUST do a chdir() after the chroot. Otherwise
1449 * the old current directory will be accessible as "."
1450 * outside the new root!
1452 if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
1453 reply(550, "Can't set guest privileges.");
1456 } else if (dochroot) {
1457 if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
1458 reply(550, "Can't change root.");
1461 } else if (chdir(pw->pw_dir) < 0) {
1462 if (chdir("/") < 0) {
1463 reply(530, "User %s: can't change directory to %s.",
1464 pw->pw_name, pw->pw_dir);
1467 lreply(230, "No directory! Logging in with home=/");
1469 if (seteuid((uid_t)pw->pw_uid) < 0) {
1470 reply(550, "Can't set uid.");
1475 * Display a login message, if it exists.
1476 * N.B. reply(230,) must follow the message.
1478 #ifdef VIRTUAL_HOSTING
1479 if ((fd = fopen(thishost->loginmsg, "r")) != NULL) {
1481 if ((fd = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) {
1483 char *cp, line[LINE_MAX];
1485 while (fgets(line, sizeof(line), fd) != NULL) {
1486 if ((cp = strchr(line, '\n')) != NULL)
1488 lreply(230, "%s", line);
1490 (void) fflush(stdout);
1496 ident = strdup(passwd);
1498 fatalerror("Ran out of memory.");
1500 reply(230, "Guest login ok, access restrictions apply.");
1502 #ifdef VIRTUAL_HOSTING
1503 if (thishost != firsthost)
1504 snprintf(proctitle, sizeof(proctitle),
1505 "%s: anonymous(%s)/%s", remotehost, hostname,
1509 snprintf(proctitle, sizeof(proctitle),
1510 "%s: anonymous/%s", remotehost, passwd);
1511 setproctitle("%s", proctitle);
1512 #endif /* SETPROCTITLE */
1514 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1515 remotehost, passwd);
1518 reply(230, "User %s logged in, "
1519 "access restrictions apply.", pw->pw_name);
1521 reply(230, "User %s logged in.", pw->pw_name);
1524 snprintf(proctitle, sizeof(proctitle),
1525 "%s: user/%s", remotehost, pw->pw_name);
1526 setproctitle("%s", proctitle);
1527 #endif /* SETPROCTITLE */
1529 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1530 remotehost, pw->pw_name);
1537 /* Forget all about it... */
1545 retrieve(char *cmd, char *name)
1549 int (*closefunc)(FILE *);
1553 fin = fopen(name, "r"), closefunc = fclose;
1558 (void) snprintf(line, sizeof(line), cmd, name), name = line;
1559 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1561 st.st_blksize = BUFSIZ;
1565 perror_reply(550, name);
1567 LOGCMD("get", name);
1573 if (cmd == 0 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
1574 reply(550, "%s: not a plain file.", name);
1577 if (restart_point) {
1578 if (type == TYPE_A) {
1585 if ((c=getc(fin)) == EOF) {
1586 perror_reply(550, name);
1592 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1593 perror_reply(550, name);
1597 dout = dataconn(name, st.st_size, "w");
1601 send_data(fin, dout, st.st_blksize, st.st_size,
1602 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1603 if (cmd == 0 && guest && stats)
1604 logxfer(name, st.st_size, start);
1605 (void) fclose(dout);
1610 LOGBYTES("get", name, byte_count);
1615 store(char *name, char *mode, int unique)
1619 int (*closefunc)(FILE *);
1621 if (*mode == 'a') { /* APPE */
1623 /* Programming error */
1624 syslog(LOG_ERR, "Internal: unique flag to APPE");
1627 if (guest && noguestmod) {
1628 reply(550, "Appending to existing file denied");
1631 restart_point = 0; /* not affected by preceding REST */
1633 if (unique) /* STOU overrides REST */
1635 if (guest && noguestmod) {
1636 if (restart_point) { /* guest STOR w/REST */
1637 reply(550, "Modifying existing file denied");
1639 } else /* treat guest STOR as STOU */
1644 mode = "r+"; /* so ASCII manual seek can work */
1646 if ((fd = guniquefd(name, &name)) < 0)
1648 fout = fdopen(fd, mode);
1650 fout = fopen(name, mode);
1653 perror_reply(553, name);
1657 if (restart_point) {
1658 if (type == TYPE_A) {
1665 if ((c=getc(fout)) == EOF) {
1666 perror_reply(550, name);
1673 * We must do this seek to "current" position
1674 * because we are changing from reading to
1677 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1678 perror_reply(550, name);
1681 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1682 perror_reply(550, name);
1686 din = dataconn(name, (off_t)-1, "r");
1689 if (receive_data(din, fout) == 0) {
1691 reply(226, "Transfer complete (unique file name:%s).",
1694 reply(226, "Transfer complete.");
1700 LOGBYTES(*mode == 'w' ? "put" : "append", name, byte_count);
1704 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1709 getdatasock(char *mode)
1711 int on = 1, s, t, tries;
1714 return (fdopen(data, mode));
1715 (void) seteuid((uid_t)0);
1717 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1720 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1721 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1722 /* anchor socket to avoid multi-homing problems */
1723 data_source = ctrl_addr;
1724 data_source.su_port = htons(20); /* ftp-data port */
1725 for (tries = 1; ; tries++) {
1726 if (bind(s, (struct sockaddr *)&data_source,
1727 data_source.su_len) >= 0)
1729 if (errno != EADDRINUSE || tries > 10)
1733 (void) seteuid((uid_t)pw->pw_uid);
1735 if (data_source.su_family == AF_INET)
1737 on = IPTOS_THROUGHPUT;
1738 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1739 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1744 * Turn off push flag to keep sender TCP from sending short packets
1745 * at the boundaries of each write(). Should probably do a SO_SNDBUF
1746 * to set the send buffer size as well, but that may not be desirable
1747 * in heavy-load situations.
1750 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1751 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1755 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &on, sizeof on) < 0)
1756 syslog(LOG_WARNING, "data setsockopt (SO_SNDBUF): %m");
1759 return (fdopen(s, mode));
1761 /* Return the real value of errno (close may change it) */
1763 (void) seteuid((uid_t)pw->pw_uid);
1770 dataconn(char *name, off_t size, char *mode)
1778 if (size != (off_t) -1)
1779 (void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)", size);
1783 union sockunion from;
1785 int s, fromlen = ctrl_addr.su_len;
1786 struct timeval timeout;
1790 FD_SET(pdata, &set);
1792 timeout.tv_usec = 0;
1793 timeout.tv_sec = 120;
1796 * Granted a socket is in the blocking I/O mode,
1797 * accept() will block after a successful select()
1798 * if the selected connection dies in between.
1799 * Therefore set the non-blocking I/O flag here.
1801 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1802 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1804 if (select(pdata+1, &set, (fd_set *) 0, (fd_set *) 0, &timeout) <= 0 ||
1805 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1807 (void) close(pdata);
1810 * Unset the inherited non-blocking I/O flag
1811 * on the child socket so stdio can work on it.
1813 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1814 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1817 if (from.su_family == AF_INET)
1819 tos = IPTOS_THROUGHPUT;
1820 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1821 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1824 reply(150, "Opening %s mode data connection for '%s'%s.",
1825 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1826 return (fdopen(pdata, mode));
1828 reply(425, "Can't open data connection.");
1829 (void) close(pdata);
1834 reply(125, "Using existing data connection for '%s'%s.",
1837 return (fdopen(data, mode));
1840 data_dest = his_addr;
1842 file = getdatasock(mode);
1844 char hostbuf[BUFSIZ], portbuf[BUFSIZ];
1845 getnameinfo((struct sockaddr *)&data_source,
1846 data_source.su_len, hostbuf, sizeof(hostbuf) - 1,
1847 portbuf, sizeof(portbuf),
1848 NI_NUMERICHOST|NI_NUMERICSERV);
1849 reply(425, "Can't create data socket (%s,%s): %s.",
1850 hostbuf, portbuf, strerror(errno));
1853 data = fileno(file);
1854 while (connect(data, (struct sockaddr *)&data_dest,
1855 data_dest.su_len) < 0) {
1856 if (errno == EADDRINUSE && retry < swaitmax) {
1857 sleep((unsigned) swaitint);
1861 perror_reply(425, "Can't build data connection");
1862 (void) fclose(file);
1866 reply(150, "Opening %s mode data connection for '%s'%s.",
1867 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1872 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1873 * encapsulation of the data subject to Mode, Structure, and Type.
1875 * NB: Form isn't handled.
1878 send_data(FILE *instr, FILE *outstr, off_t blksize, off_t filesize, int isreg)
1880 int c, filefd, netfd;
1888 while ((c = getc(instr)) != EOF) {
1895 (void) putc('\r', outstr);
1897 (void) putc(c, outstr);
1907 reply(226, "Transfer complete.");
1913 * isreg is only set if we are not doing restart and we
1914 * are sending a regular file
1916 netfd = fileno(outstr);
1917 filefd = fileno(instr);
1924 err = cnt = offset = 0;
1926 while (err != -1 && filesize > 0) {
1927 err = sendfile(filefd, netfd, offset, 0,
1928 (struct sf_hdtr *) NULL, &cnt, 0);
1930 * Calculate byte_count before OOB processing.
1931 * It can be used in myoob() later.
1948 reply(226, "Transfer complete.");
1953 if ((buf = malloc((u_int)blksize)) == NULL) {
1955 perror_reply(451, "Local resource failure: malloc");
1959 while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
1960 write(netfd, buf, cnt) == cnt)
1969 reply(226, "Transfer complete.");
1973 reply(550, "Unimplemented TYPE %d in send_data", type);
1979 perror_reply(426, "Data connection");
1984 perror_reply(551, "Error on input file");
1995 * Transfer data from peer to "outstr" using the appropriate encapulation of
1996 * the data subject to Mode, Structure, and Type.
1998 * N.B.: Form isn't handled.
2001 receive_data(FILE *instr, FILE *outstr)
2014 while ((cnt = read(fileno(instr), buf, sizeof(buf))) > 0) {
2017 if (write(fileno(outstr), buf, cnt) != cnt)
2029 reply(553, "TYPE E not implemented.");
2034 while ((c = getc(instr)) != EOF) {
2043 if ((c = getc(instr)) != '\n') {
2044 (void) putc ('\r', outstr);
2045 if (c == '\0' || c == EOF)
2049 (void) putc(c, outstr);
2062 "WARNING! %d bare linefeeds received in ASCII mode",
2064 (void)printf(" File may not have transferred correctly.\r\n");
2068 reply(550, "Unimplemented TYPE %d in receive_data", type);
2075 perror_reply(426, "Data Connection");
2080 perror_reply(452, "Error writing file");
2091 statfilecmd(char *filename)
2095 char line[LINE_MAX];
2097 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2098 fin = ftpd_popen(line, "r");
2099 lreply(211, "status of %s:", filename);
2100 while ((c = getc(fin)) != EOF) {
2102 if (ferror(stdout)){
2103 perror_reply(421, "control connection");
2104 (void) ftpd_pclose(fin);
2109 perror_reply(551, filename);
2110 (void) ftpd_pclose(fin);
2113 (void) putc('\r', stdout);
2115 (void) putc(c, stdout);
2117 (void) ftpd_pclose(fin);
2118 reply(211, "End of Status");
2124 union sockunion *su;
2126 char hname[NI_MAXHOST];
2129 lreply(211, "%s FTP server status:", hostname);
2130 printf(" %s\r\n", version);
2131 printf(" Connected to %s", remotehost);
2132 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2133 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2134 if (strcmp(hname, remotehost) != 0)
2135 printf(" (%s)", hname);
2140 printf(" Logged in anonymously\r\n");
2142 printf(" Logged in as %s\r\n", pw->pw_name);
2143 } else if (askpasswd)
2144 printf(" Waiting for password\r\n");
2146 printf(" Waiting for user name\r\n");
2147 printf(" TYPE: %s", typenames[type]);
2148 if (type == TYPE_A || type == TYPE_E)
2149 printf(", FORM: %s", formnames[form]);
2152 printf(" %d", NBBY);
2154 printf(" %d", bytesize); /* need definition! */
2156 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2157 strunames[stru], modenames[mode]);
2159 printf(" Data connection open\r\n");
2160 else if (pdata != -1) {
2164 } else if (usedefault == 0) {
2168 #define UC(b) (((int) b) & 0xff)
2170 printf(" EPSV only mode (EPSV ALL)\r\n");
2175 if (su->su_family == AF_INET) {
2176 a = (u_char *) &su->su_sin.sin_addr;
2177 p = (u_char *) &su->su_sin.sin_port;
2178 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2179 ispassive ? "PASV" : "PORT",
2180 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2181 UC(p[0]), UC(p[1]));
2188 switch (su->su_family) {
2190 a = (u_char *) &su->su_sin.sin_addr;
2191 p = (u_char *) &su->su_sin.sin_port;
2192 alen = sizeof(su->su_sin.sin_addr);
2196 a = (u_char *) &su->su_sin6.sin6_addr;
2197 p = (u_char *) &su->su_sin6.sin6_port;
2198 alen = sizeof(su->su_sin6.sin6_addr);
2206 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2208 for (i = 0; i < alen; i++)
2209 printf("%d,", UC(a[i]));
2210 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2219 switch (su->su_family) {
2231 union sockunion tmp;
2234 if (tmp.su_family == AF_INET6)
2235 tmp.su_sin6.sin6_scope_id = 0;
2236 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2237 hname, sizeof(hname) - 1, NULL, 0,
2239 printf(" %s |%d|%s|%d|\r\n",
2240 ispassive ? "EPSV" : "EPRT",
2241 af, hname, htons(tmp.su_port));
2247 printf(" No data connection\r\n");
2248 reply(211, "End of status");
2255 reply(451, "Error in server: %s\n", s);
2256 reply(221, "Closing connection due to server error.");
2262 reply(int n, const char *fmt, ...)
2267 (void)printf("%d ", n);
2268 (void)vprintf(fmt, ap);
2269 (void)printf("\r\n");
2270 (void)fflush(stdout);
2272 syslog(LOG_DEBUG, "<--- %d ", n);
2273 vsyslog(LOG_DEBUG, fmt, ap);
2278 lreply(int n, const char *fmt, ...)
2283 (void)printf("%d- ", n);
2284 (void)vprintf(fmt, ap);
2285 (void)printf("\r\n");
2286 (void)fflush(stdout);
2288 syslog(LOG_DEBUG, "<--- %d- ", n);
2289 vsyslog(LOG_DEBUG, fmt, ap);
2297 reply(250, "%s command successful.", s);
2304 reply(502, "%s command not implemented.", s);
2313 if ((cp = strchr(cbuf,'\n')))
2315 reply(500, "'%s': command not understood.", cbuf);
2323 LOGCMD("delete", name);
2324 if (lstat(name, &st) < 0) {
2325 perror_reply(550, name);
2328 if ((st.st_mode&S_IFMT) == S_IFDIR) {
2329 if (rmdir(name) < 0) {
2330 perror_reply(550, name);
2335 if (unlink(name) < 0) {
2336 perror_reply(550, name);
2347 if (chdir(path) < 0)
2348 perror_reply(550, path);
2358 LOGCMD("mkdir", name);
2359 if (guest && noguestmkd)
2360 reply(550, "%s: permission denied", name);
2361 else if (mkdir(name, 0777) < 0)
2362 perror_reply(550, name);
2364 if ((s = doublequote(name)) == NULL)
2365 fatalerror("Ran out of memory.");
2366 reply(257, "\"%s\" directory created.", s);
2372 removedir(char *name)
2375 LOGCMD("rmdir", name);
2376 if (rmdir(name) < 0)
2377 perror_reply(550, name);
2385 char *s, path[MAXPATHLEN + 1];
2387 if (getwd(path) == (char *)NULL)
2388 reply(550, "%s.", path);
2390 if ((s = doublequote(path)) == NULL)
2391 fatalerror("Ran out of memory.");
2392 reply(257, "\"%s\" is current directory.", s);
2398 renamefrom(char *name)
2402 if (lstat(name, &st) < 0) {
2403 perror_reply(550, name);
2406 reply(350, "File exists, ready for destination name");
2411 renamecmd(char *from, char *to)
2415 LOGCMD2("rename", from, to);
2417 if (guest && (stat(to, &st) == 0)) {
2418 reply(550, "%s: permission denied", to);
2422 if (rename(from, to) < 0)
2423 perror_reply(550, "rename");
2429 dolog(struct sockaddr *who)
2433 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2436 #ifdef VIRTUAL_HOSTING
2437 if (thishost != firsthost)
2438 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2439 remotehost, hostname);
2442 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2444 setproctitle("%s", proctitle);
2445 #endif /* SETPROCTITLE */
2448 #ifdef VIRTUAL_HOSTING
2449 if (thishost != firsthost)
2450 syslog(LOG_INFO, "connection from %s (to %s)",
2451 remotehost, hostname);
2455 char who_name[MAXHOSTNAMELEN];
2457 error = getnameinfo(who, who->sa_len,
2458 who_name, sizeof(who_name) - 1,
2459 NULL, 0, NI_NUMERICHOST);
2460 syslog(LOG_INFO, "connection from %s (%s)", remotehost,
2461 error == 0 ? who_name : "");
2467 * Record logout in wtmp file
2468 * and exit with supplied status.
2471 dologout(int status)
2474 * Prevent reception of SIGURG from resulting in a resumption
2475 * back to the main program loop.
2479 if (logged_in && dowtmp) {
2480 (void) seteuid((uid_t)0);
2481 ftpd_logwtmp(ttyline, "", NULL);
2483 /* beware of flushing buffers after a SIGPIPE */
2499 /* only process if transfer occurring */
2503 if (getline(cp, 7, stdin) == NULL) {
2504 reply(221, "You could at least say goodbye.");
2508 if (strcmp(cp, "ABOR\r\n") == 0) {
2510 reply(426, "Transfer aborted. Data connection closed.");
2511 reply(226, "Abort successful");
2513 if (strcmp(cp, "STAT\r\n") == 0) {
2515 if (file_size != (off_t) -1)
2516 reply(213, "Status: %qd of %qd bytes transferred",
2517 byte_count, file_size);
2519 reply(213, "Status: %qd bytes transferred", byte_count);
2524 * Note: a response of 425 is not mentioned as a possible response to
2525 * the PASV command in RFC959. However, it has been blessed as
2526 * a legitimate response by Jon Postel in a telephone conversation
2527 * with Rick Adams on 25 Jan 89.
2535 if (pdata >= 0) /* close old port if one set */
2538 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2540 perror_reply(425, "Can't open passive connection");
2544 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2545 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2547 (void) seteuid((uid_t)0);
2550 if (ctrl_addr.su_family == AF_INET) {
2551 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2552 : IP_PORTRANGE_DEFAULT;
2554 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2555 &on, sizeof(on)) < 0)
2559 #ifdef IPV6_PORTRANGE
2560 if (ctrl_addr.su_family == AF_INET6) {
2561 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2562 : IPV6_PORTRANGE_DEFAULT;
2564 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2565 &on, sizeof(on)) < 0)
2570 pasv_addr = ctrl_addr;
2571 pasv_addr.su_port = 0;
2572 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2575 (void) seteuid((uid_t)pw->pw_uid);
2577 len = sizeof(pasv_addr);
2578 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2580 if (listen(pdata, 1) < 0)
2582 if (pasv_addr.su_family == AF_INET)
2583 a = (char *) &pasv_addr.su_sin.sin_addr;
2584 else if (pasv_addr.su_family == AF_INET6 &&
2585 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2586 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2590 p = (char *) &pasv_addr.su_port;
2592 #define UC(b) (((int) b) & 0xff)
2594 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2595 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2599 (void) seteuid((uid_t)pw->pw_uid);
2600 (void) close(pdata);
2602 perror_reply(425, "Can't open passive connection");
2607 * Long Passive defined in RFC 1639.
2608 * 228 Entering Long Passive Mode
2609 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2613 long_passive(char *cmd, int pf)
2618 if (pdata >= 0) /* close old port if one set */
2621 if (pf != PF_UNSPEC) {
2622 if (ctrl_addr.su_family != pf) {
2623 switch (ctrl_addr.su_family) {
2636 * only EPRT/EPSV ready clients will understand this
2638 if (strcmp(cmd, "EPSV") == 0 && pf) {
2639 reply(522, "Network protocol mismatch, "
2642 reply(501, "Network protocol mismatch"); /*XXX*/
2648 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2650 perror_reply(425, "Can't open passive connection");
2654 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2655 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2657 (void) seteuid((uid_t)0);
2659 pasv_addr = ctrl_addr;
2660 pasv_addr.su_port = 0;
2661 len = pasv_addr.su_len;
2664 if (ctrl_addr.su_family == AF_INET) {
2665 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2666 : IP_PORTRANGE_DEFAULT;
2668 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2669 &on, sizeof(on)) < 0)
2673 #ifdef IPV6_PORTRANGE
2674 if (ctrl_addr.su_family == AF_INET6) {
2675 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2676 : IPV6_PORTRANGE_DEFAULT;
2678 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2679 &on, sizeof(on)) < 0)
2684 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2687 (void) seteuid((uid_t)pw->pw_uid);
2689 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2691 if (listen(pdata, 1) < 0)
2694 #define UC(b) (((int) b) & 0xff)
2696 if (strcmp(cmd, "LPSV") == 0) {
2697 p = (char *)&pasv_addr.su_port;
2698 switch (pasv_addr.su_family) {
2700 a = (char *) &pasv_addr.su_sin.sin_addr;
2703 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2704 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2705 2, UC(p[0]), UC(p[1]));
2708 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
2709 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2712 a = (char *) &pasv_addr.su_sin6.sin6_addr;
2714 "Entering Long Passive Mode "
2715 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2716 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2717 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2718 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2719 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2720 2, UC(p[0]), UC(p[1]));
2723 } else if (strcmp(cmd, "EPSV") == 0) {
2724 switch (pasv_addr.su_family) {
2727 reply(229, "Entering Extended Passive Mode (|||%d|)",
2728 ntohs(pasv_addr.su_port));
2732 /* more proper error code? */
2736 (void) seteuid((uid_t)pw->pw_uid);
2737 (void) close(pdata);
2739 perror_reply(425, "Can't open passive connection");
2744 * Generate unique name for file with basename "local"
2745 * and open the file in order to avoid possible races.
2746 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
2747 * Return descriptor to the file, set "name" to its name.
2749 * Generates failure reply on error.
2752 guniquefd(char *local, char **name)
2754 static char new[MAXPATHLEN];
2760 cp = strrchr(local, '/');
2763 if (stat(cp ? local : ".", &st) < 0) {
2764 perror_reply(553, cp ? local : ".");
2769 * Let not overwrite dirname with counter suffix.
2771 * In this extreme case dot won't be put in front of suffix.
2773 if (strlen(local) > sizeof(new) - 4) {
2774 reply(553, "Pathname too long");
2779 /* -4 is for the .nn<null> we put on the end below */
2780 (void) snprintf(new, sizeof(new) - 4, "%s", local);
2781 cp = new + strlen(new);
2783 * Don't generate dotfile unless requested explicitly.
2784 * This covers the case when basename gets truncated off
2787 if (cp > new && cp[-1] != '/')
2789 for (count = 0; count < 100; count++) {
2790 /* At count 0 try unmodified name */
2792 (void)sprintf(cp, "%d", count);
2793 if ((fd = open(count ? new : local,
2794 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
2795 *name = count ? new : local;
2799 reply(452, "Unique file name cannot be created.");
2804 * Format and send reply containing system error number.
2807 perror_reply(int code, char *string)
2810 reply(code, "%s: %s.", string, strerror(errno));
2813 static char *onefile[] = {
2819 send_file_list(char *whichf)
2825 char **dirlist, *dirname;
2830 if (strpbrk(whichf, "~{[*?") != NULL) {
2831 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
2833 memset(&gl, 0, sizeof(gl));
2834 gl.gl_matchc = MAXGLOBARGS;
2835 flags |= GLOB_LIMIT;
2837 if (glob(whichf, flags, 0, &gl)) {
2838 reply(550, "not found");
2840 } else if (gl.gl_pathc == 0) {
2842 perror_reply(550, whichf);
2845 dirlist = gl.gl_pathv;
2847 onefile[0] = whichf;
2852 while ((dirname = *dirlist++)) {
2853 if (stat(dirname, &st) < 0) {
2855 * If user typed "ls -l", etc, and the client
2856 * used NLST, do what the user meant.
2858 if (dirname[0] == '-' && *dirlist == NULL &&
2860 retrieve(_PATH_LS " %s", dirname);
2863 perror_reply(550, whichf);
2865 (void) fclose(dout);
2873 if (S_ISREG(st.st_mode)) {
2875 dout = dataconn("file list", (off_t)-1, "w");
2880 fprintf(dout, "%s%s\n", dirname,
2881 type == TYPE_A ? "\r" : "");
2882 byte_count += strlen(dirname) + 1;
2884 } else if (!S_ISDIR(st.st_mode))
2887 if ((dirp = opendir(dirname)) == NULL)
2890 while ((dir = readdir(dirp)) != NULL) {
2891 char nbuf[MAXPATHLEN];
2900 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
2902 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
2906 snprintf(nbuf, sizeof(nbuf),
2907 "%s/%s", dirname, dir->d_name);
2910 * We have to do a stat to insure it's
2911 * not a directory or special file.
2913 if (simple || (stat(nbuf, &st) == 0 &&
2914 S_ISREG(st.st_mode))) {
2916 dout = dataconn("file list", (off_t)-1,
2922 if (nbuf[0] == '.' && nbuf[1] == '/')
2923 fprintf(dout, "%s%s\n", &nbuf[2],
2924 type == TYPE_A ? "\r" : "");
2926 fprintf(dout, "%s%s\n", nbuf,
2927 type == TYPE_A ? "\r" : "");
2928 byte_count += strlen(nbuf) + 1;
2931 (void) closedir(dirp);
2935 reply(550, "No files found.");
2936 else if (ferror(dout) != 0)
2937 perror_reply(550, "Data connection");
2939 reply(226, "Transfer complete.");
2943 (void) fclose(dout);
2954 reapchild(int signo)
2956 while (wait3(NULL, WNOHANG, NULL) > 0);
2959 #ifdef OLD_SETPROCTITLE
2961 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.)
2962 * Warning, since this is usually started from inetd.conf, it often doesn't
2963 * have much of an environment or arglist to overwrite.
2966 setproctitle(const char *fmt, ...)
2974 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
2976 /* make ps print our process name */
2981 if (i > LastArgv - p - 2) {
2982 i = LastArgv - p - 2;
2987 if (ch != '\n' && ch != '\r')
2989 while (p < LastArgv)
2992 #endif /* OLD_SETPROCTITLE */
2995 logxfer(char *name, off_t size, time_t start)
2998 char path[MAXPATHLEN + 1];
3001 if (statfd >= 0 && getwd(path) != NULL) {
3003 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s/%s!%qd!%ld\n",
3004 ctime(&now)+4, ident, remotehost,
3005 path, name, (long long)size,
3006 (long)(now - start + (now == start)));
3007 write(statfd, buf, strlen(buf));
3012 doublequote(char *s)
3017 for (p = s, n = 0; *p; p++)
3021 if ((s2 = malloc(p - s + n + 1)) == NULL)
3024 for (p = s2; *s; s++, p++) {
3025 if ((*p = *s) == '"')