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 */
133 int stru; /* avoid C keyword */
135 int usedefault = 1; /* for data transfers */
136 int pdata = -1; /* for passive mode */
137 int readonly=0; /* Server is in readonly mode. */
138 int noepsv=0; /* EPSV command is disabled. */
139 int noretr=0; /* RETR command is disabled. */
140 int noguestretr=0; /* RETR command is disabled for anon users. */
141 int noguestmkd=0; /* MKD command is disabled for anon users. */
143 static volatile sig_atomic_t recvurg;
144 sig_atomic_t transflag;
147 #if !defined(CMASK) || CMASK == 0
151 int defumask = CMASK; /* default umask value */
156 #ifdef VIRTUAL_HOSTING
159 static struct ftphost {
160 struct ftphost *next;
161 struct addrinfo *hostinfo;
167 } *thishost, *firsthost;
170 char remotehost[MAXHOSTNAMELEN];
173 static char ttyline[20];
174 char *tty = ttyline; /* for klogin */
177 static int auth_pam(struct passwd**, const char*);
178 pam_handle_t *pamh = NULL;
181 static struct opie opiedata;
182 static char opieprompt[OPIE_CHALLENGE_MAX+1];
185 char *pid_file = NULL;
188 * Limit number of pathnames that glob can return.
189 * A limit of 0 indicates the number of pathnames is unlimited.
191 #define MAXGLOBARGS 16384
195 * Timeout intervals for retrying connections
196 * to hosts that don't accept PORT cmds. This
197 * is a kludge, but given the problems with TCP...
199 #define SWAITMAX 90 /* wait at most 90 seconds */
200 #define SWAITINT 5 /* interval between retries */
202 int swaitmax = SWAITMAX;
203 int swaitint = SWAITINT;
206 #ifdef OLD_SETPROCTITLE
207 char **Argv = NULL; /* pointer to argument vector */
208 char *LastArgv = NULL; /* end of argv */
209 #endif /* OLD_SETPROCTITLE */
210 char proctitle[LINE_MAX]; /* initial part of title */
211 #endif /* SETPROCTITLE */
213 #define LOGCMD(cmd, file) \
215 syslog(LOG_INFO,"%s %s%s", cmd, \
216 *(file) == '/' ? "" : curdir(), file);
217 #define LOGCMD2(cmd, file1, file2) \
219 syslog(LOG_INFO,"%s %s%s %s%s", cmd, \
220 *(file1) == '/' ? "" : curdir(), file1, \
221 *(file2) == '/' ? "" : curdir(), file2);
222 #define LOGBYTES(cmd, file, cnt) \
224 if (cnt == (off_t)-1) \
225 syslog(LOG_INFO,"%s %s%s", cmd, \
226 *(file) == '/' ? "" : curdir(), file); \
228 syslog(LOG_INFO, "%s %s%s = %qd bytes", \
229 cmd, (*(file) == '/') ? "" : curdir(), file, cnt); \
232 #ifdef VIRTUAL_HOSTING
233 static void inithosts(void);
234 static void selecthost(union sockunion *);
236 static void ack(char *);
237 static void sigurg(int);
238 static void myoob(void);
239 static int checkuser(char *, char *, int);
240 static FILE *dataconn(char *, off_t, char *);
241 static void dolog(struct sockaddr *);
242 static char *curdir(void);
243 static void end_login(void);
244 static FILE *getdatasock(char *);
245 static char *gunique(char *);
246 static void lostconn(int);
247 static void sigquit(int);
248 static int receive_data(FILE *, FILE *);
249 static int send_data(FILE *, FILE *, off_t, off_t, int);
250 static struct passwd *
252 static char *sgetsave(char *);
253 static void reapchild(int);
254 static void logxfer(char *, off_t, time_t);
259 static char path[MAXPATHLEN+1+1]; /* path + '/' + '\0' */
261 if (getcwd(path, sizeof(path)-2) == NULL)
263 if (path[1] != '\0') /* special case for root dir. */
265 /* For guest account, skip / since it's chrooted */
266 return (guest ? path+1 : path);
270 main(int argc, char *argv[], char **envp)
272 int addrlen, ch, on = 1, tos;
273 char *cp, line[LINE_MAX];
276 char *bindname = NULL;
277 int family = AF_UNSPEC;
281 tzset(); /* in case no timezone database in ~ftp */
282 sigemptyset(&sa.sa_mask);
283 sa.sa_flags = SA_RESTART;
285 #ifdef OLD_SETPROCTITLE
287 * Save start and extent of argv for setproctitle.
292 LastArgv = envp[-1] + strlen(envp[-1]);
293 #endif /* OLD_SETPROCTITLE */
296 while ((ch = getopt(argc, argv, "AdlDESURrt:T:u:vMOoa:p:46")) != -1) {
311 logging++; /* > 1 == extra logging */
327 maxtimeout = atoi(optarg);
328 if (timeout > maxtimeout)
329 timeout = maxtimeout;
333 timeout = atoi(optarg);
334 if (maxtimeout < timeout)
335 maxtimeout = timeout;
339 restricted_data_ports = 0;
354 val = strtol(optarg, &optarg, 8);
355 if (*optarg != '\0' || val < 0)
356 warnx("bad value for -u");
371 if (family == AF_UNSPEC)
392 warnx("unknown flag -%c ignored", optopt);
397 #ifdef VIRTUAL_HOSTING
400 (void) freopen(_PATH_DEVNULL, "w", stderr);
403 * LOG_NDELAY sets up the logging connection immediately,
404 * necessary for anonymous ftp's that chroot and can't do it later.
406 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
410 struct addrinfo hints, *res;
413 * Detach from parent.
415 if (daemon(1, 1) < 0) {
416 syslog(LOG_ERR, "failed to become a daemon");
419 sa.sa_handler = reapchild;
420 (void)sigaction(SIGCHLD, &sa, NULL);
422 memset(&hints, 0, sizeof(hints));
424 hints.ai_family = family == AF_UNSPEC ? AF_INET : family;
425 hints.ai_socktype = SOCK_STREAM;
426 hints.ai_protocol = 0;
427 hints.ai_flags = AI_PASSIVE;
428 error = getaddrinfo(bindname, "ftp", &hints, &res);
430 if (family == AF_UNSPEC) {
431 hints.ai_family = AF_UNSPEC;
432 error = getaddrinfo(bindname, "ftp", &hints,
437 syslog(LOG_ERR, "%s", gai_strerror(error));
438 if (error == EAI_SYSTEM)
439 syslog(LOG_ERR, "%s", strerror(errno));
442 if (res->ai_addr == NULL) {
443 syslog(LOG_ERR, "-a %s: getaddrinfo failed", hostname);
446 family = res->ai_addr->sa_family;
448 * Open a socket, bind it to the FTP port, and start
451 ctl_sock = socket(family, SOCK_STREAM, 0);
453 syslog(LOG_ERR, "control socket: %m");
456 if (setsockopt(ctl_sock, SOL_SOCKET, SO_REUSEADDR,
457 (char *)&on, sizeof(on)) < 0)
458 syslog(LOG_ERR, "control setsockopt: %m");
459 #ifdef IPV6_BINDV6ONLY
460 if (family == AF_INET6 && enable_v4 == 0) {
461 if (setsockopt(ctl_sock, IPPROTO_IPV6, IPV6_BINDV6ONLY,
462 (char *)&on, sizeof (on)) < 0)
464 "control setsockopt(IPV6_BINDV6ONLY): %m");
466 #endif /* IPV6_BINDV6ONLY */
467 memcpy(&server_addr, res->ai_addr, res->ai_addr->sa_len);
468 if (bind(ctl_sock, (struct sockaddr *)&server_addr,
469 server_addr.su_len) < 0) {
470 syslog(LOG_ERR, "control bind: %m");
473 if (listen(ctl_sock, 32) < 0) {
474 syslog(LOG_ERR, "control listen: %m");
478 * Atomically write process ID
485 fd = open(pid_file, O_CREAT | O_WRONLY | O_TRUNC
486 | O_NONBLOCK | O_EXLOCK, 0644);
489 errx(1, "%s: file locked", pid_file);
491 err(1, "%s", pid_file);
493 snprintf(buf, sizeof(buf),
494 "%lu\n", (unsigned long) getpid());
495 if (write(fd, buf, strlen(buf)) < 0)
496 err(1, "%s: write", pid_file);
497 /* Leave the pid file open and locked */
500 * Loop forever accepting connection requests and forking off
501 * children to handle them.
504 addrlen = server_addr.su_len;
505 fd = accept(ctl_sock, (struct sockaddr *)&his_addr, &addrlen);
516 addrlen = sizeof(his_addr);
517 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
518 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
523 sa.sa_handler = SIG_DFL;
524 (void)sigaction(SIGCHLD, &sa, NULL);
526 sa.sa_handler = sigurg;
527 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
528 (void)sigaction(SIGURG, &sa, NULL);
530 sigfillset(&sa.sa_mask); /* block all signals in handler */
531 sa.sa_flags = SA_RESTART;
532 sa.sa_handler = sigquit;
533 (void)sigaction(SIGHUP, &sa, NULL);
534 (void)sigaction(SIGINT, &sa, NULL);
535 (void)sigaction(SIGQUIT, &sa, NULL);
536 (void)sigaction(SIGTERM, &sa, NULL);
538 sa.sa_handler = lostconn;
539 (void)sigaction(SIGPIPE, &sa, NULL);
541 addrlen = sizeof(ctrl_addr);
542 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
543 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
546 #ifdef VIRTUAL_HOSTING
547 /* select our identity from virtual host table */
548 selecthost(&ctrl_addr);
551 if (ctrl_addr.su_family == AF_INET)
553 tos = IPTOS_LOWDELAY;
554 if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(int)) < 0)
555 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
559 * Disable Nagle on the control channel so that we don't have to wait
560 * for peer's ACK before issuing our next reply.
562 if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
563 syslog(LOG_WARNING, "control setsockopt TCP_NODELAY: %m");
565 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
567 /* set this here so klogin can use it... */
568 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
570 /* Try to handle urgent data inline */
572 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
573 syslog(LOG_ERR, "setsockopt: %m");
577 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
578 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
580 dolog((struct sockaddr *)&his_addr);
582 * Set up default state
591 /* If logins are disabled, print out the message. */
592 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
593 while (fgets(line, sizeof(line), fd) != NULL) {
594 if ((cp = strchr(line, '\n')) != NULL)
596 lreply(530, "%s", line);
598 (void) fflush(stdout);
600 reply(530, "System not available.");
603 #ifdef VIRTUAL_HOSTING
604 if ((fd = fopen(thishost->welcome, "r")) != NULL) {
606 if ((fd = fopen(_PATH_FTPWELCOME, "r")) != NULL) {
608 while (fgets(line, sizeof(line), fd) != NULL) {
609 if ((cp = strchr(line, '\n')) != NULL)
611 lreply(220, "%s", line);
613 (void) fflush(stdout);
615 /* reply(220,) must follow */
617 #ifndef VIRTUAL_HOSTING
618 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
619 fatalerror("Ran out of memory.");
620 (void) gethostname(hostname, MAXHOSTNAMELEN - 1);
621 hostname[MAXHOSTNAMELEN - 1] = '\0';
623 reply(220, "%s FTP server (%s) ready.", hostname, version);
634 syslog(LOG_DEBUG, "lost connection");
642 syslog(LOG_ERR, "got signal %d", signo);
646 #ifdef VIRTUAL_HOSTING
648 * read in virtual host tables (if they exist)
657 char *cp, *mp, *line;
659 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
660 struct ftphost *hrp, *lhrp;
661 struct addrinfo hints, *res, *ai;
664 * Fill in the default host information
666 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
667 fatalerror("Ran out of memory.");
668 if (gethostname(hostname, MAXHOSTNAMELEN) < 0)
670 hostname[MAXHOSTNAMELEN - 1] = '\0';
671 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
672 fatalerror("Ran out of memory.");
673 hrp->hostname = hostname;
674 hrp->hostinfo = NULL;
676 memset(&hints, 0, sizeof(hints));
677 hints.ai_flags = AI_CANONNAME;
678 hints.ai_family = AF_UNSPEC;
679 getaddrinfo(hrp->hostname, NULL, &hints, &res);
682 hrp->statfile = _PATH_FTPDSTATFILE;
683 hrp->welcome = _PATH_FTPWELCOME;
684 hrp->loginmsg = _PATH_FTPLOGINMESG;
685 hrp->anonuser = "ftp";
687 thishost = firsthost = lhrp = hrp;
688 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
689 int addrsize, error, gothost;
693 while ((line = fgetln(fp, &len)) != NULL) {
699 if (line[len - 1] == '\n') {
700 line[len - 1] = '\0';
703 if ((mp = malloc(len + 1)) == NULL)
704 fatalerror("Ran out of memory.");
705 memcpy(mp, line, len);
709 cp = strtok(line, " \t");
710 /* skip empty lines */
717 statfile = _PATH_FTPDSTATFILE;
718 welcome = _PATH_FTPWELCOME;
719 loginmsg = _PATH_FTPLOGINMESG;
722 * Preparse the line so we can use its info
723 * for all the addresses associated with
724 * the virtual host name.
725 * Field 0, the virtual host name, is special:
726 * it's already parsed off and will be strdup'ed
727 * later, after we know its canonical form.
729 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
730 if (*cp != '-' && (cp = strdup(cp)))
732 case 1: /* anon user permissions */
735 case 2: /* statistics file */
738 case 3: /* welcome message */
741 case 4: /* login message */
744 default: /* programming error */
750 hints.ai_family = AF_UNSPEC;
751 hints.ai_flags = AI_PASSIVE;
752 error = getaddrinfo(vhost, NULL, &hints, &res);
755 for (ai = res; ai != NULL && ai->ai_addr != NULL;
759 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
762 for (hi = hrp->hostinfo; hi != NULL;
764 if (hi->ai_addrlen == ai->ai_addrlen &&
767 ai->ai_addr->sa_len) == 0) {
775 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
779 insert = 0; /* host already in the chain */
783 * determine hostname to use.
784 * force defined name if there is a valid alias
785 * otherwise fallback to primary hostname
787 /* XXX: getaddrinfo() can't do alias check */
788 switch(hrp->hostinfo->ai_family) {
790 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
791 addrsize = sizeof(struct in_addr);
794 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
795 addrsize = sizeof(struct in6_addr);
798 /* should not reach here */
799 if (hrp->hostinfo != NULL)
800 freeaddrinfo(hrp->hostinfo);
805 if ((hp = getipnodebyaddr((char*)addr, addrsize,
806 hrp->hostinfo->ai_family,
807 &hp_error)) != NULL) {
808 if (strcmp(vhost, hp->h_name) != 0) {
809 if (hp->h_aliases == NULL)
813 while (hp->h_aliases[i] &&
814 strcmp(vhost, hp->h_aliases[i]) != 0)
816 if (hp->h_aliases[i] == NULL)
821 if ((hrp->hostname = strdup(vhost)) == NULL)
823 hrp->anonuser = anonuser;
824 hrp->statfile = statfile;
825 hrp->welcome = welcome;
826 hrp->loginmsg = loginmsg;
843 selecthost(union sockunion *su)
848 struct in6_addr *mapped_in6 = NULL;
854 * XXX IPv4 mapped IPv6 addr consideraton,
855 * specified in rfc2373.
857 if (su->su_family == AF_INET6 &&
858 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
859 mapped_in6 = &su->su_sin6.sin6_addr;
862 hrp = thishost = firsthost; /* default */
865 while (hrp != NULL) {
866 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
867 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
872 /* XXX IPv4 mapped IPv6 addr consideraton */
873 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
874 (memcmp(&mapped_in6->s6_addr[12],
875 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
876 sizeof(struct in_addr)) == 0)) {
885 /* setup static variables as appropriate */
886 hostname = thishost->hostname;
887 ftpuser = thishost->anonuser;
892 * Helper function for sgetpwnam().
897 char *new = malloc((unsigned) strlen(s) + 1);
900 perror_reply(421, "Local resource failure: malloc");
904 (void) strcpy(new, s);
909 * Save the result of a getpwnam. Used for USER command, since
910 * the data returned must not be clobbered by any other command
913 static struct passwd *
914 sgetpwnam(char *name)
916 static struct passwd save;
919 if ((p = getpwnam(name)) == NULL)
923 free(save.pw_passwd);
929 save.pw_name = sgetsave(p->pw_name);
930 save.pw_passwd = sgetsave(p->pw_passwd);
931 save.pw_gecos = sgetsave(p->pw_gecos);
932 save.pw_dir = sgetsave(p->pw_dir);
933 save.pw_shell = sgetsave(p->pw_shell);
937 static int login_attempts; /* number of failed login attempts */
938 static int askpasswd; /* had user command, ask for passwd */
939 static char curname[MAXLOGNAME]; /* current USER name */
943 * Sets global passwd pointer pw if named account exists and is acceptable;
944 * sets askpasswd if a PASS command is expected. If logged in previously,
945 * need to reset state. If name is "ftp" or "anonymous", the name is not in
946 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
947 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
948 * requesting login privileges. Disallow anyone who does not have a standard
949 * shell as returned by getusershell(). Disallow anyone mentioned in the file
950 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
959 reply(530, "Can't change user from guest login.");
961 } else if (dochroot) {
962 reply(530, "Can't change user from chroot user.");
969 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
970 if (checkuser(_PATH_FTPUSERS, "ftp", 0) ||
971 checkuser(_PATH_FTPUSERS, "anonymous", 0))
972 reply(530, "User %s access denied.", name);
973 #ifdef VIRTUAL_HOSTING
974 else if ((pw = sgetpwnam(thishost->anonuser)) != NULL) {
976 else if ((pw = sgetpwnam("ftp")) != NULL) {
981 "Guest login ok, send your email address as password.");
983 reply(530, "User %s unknown.", name);
984 if (!askpasswd && logging)
986 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
989 if (anon_only != 0) {
990 reply(530, "Sorry, only anonymous ftp allowed.");
994 if ((pw = sgetpwnam(name))) {
995 if ((shell = pw->pw_shell) == NULL || *shell == 0)
996 shell = _PATH_BSHELL;
997 while ((cp = getusershell()) != NULL)
998 if (strcmp(cp, shell) == 0)
1002 if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1)) {
1003 reply(530, "User %s access denied.", name);
1006 "FTP LOGIN REFUSED FROM %s, %s",
1008 pw = (struct passwd *) NULL;
1013 strncpy(curname, name, sizeof(curname)-1);
1017 /* XXX Kluge! The conversation mechanism needs to be fixed. */
1019 if (opiechallenge(&opiedata, name, opieprompt) == 0) {
1020 pwok = (pw != NULL) &&
1021 opieaccessfile(remotehost) &&
1022 opiealways(pw->pw_dir);
1023 reply(331, "Response to %s %s for %s.",
1024 opieprompt, pwok ? "requested" : "required", name);
1027 reply(331, "Password required for %s.", name);
1031 * Delay before reading passwd after first failed
1032 * attempt to slow down passwd-guessing programs.
1035 sleep((unsigned) login_attempts);
1039 * Check if a user is in the file "fname"
1042 checkuser(char *fname, char *name, int pwset)
1047 char *line, *mp, *p;
1049 if ((fd = fopen(fname, "r")) != NULL) {
1050 while (!found && (line = fgetln(fd, &len)) != NULL) {
1054 if (line[len - 1] == '\n') {
1055 line[len - 1] = '\0';
1058 if ((mp = malloc(len + 1)) == NULL)
1059 fatalerror("Ran out of memory.");
1060 memcpy(mp, line, len);
1064 /* avoid possible leading and trailing whitespace */
1065 p = strtok(line, " \t");
1066 /* skip empty lines */
1070 * if first chr is '@', check group membership
1076 if ((grp = getgrnam(p+1)) == NULL)
1079 * Check user's default group
1081 if (pwset && grp->gr_gid == pw->pw_gid)
1084 * Check supplementary groups
1086 while (!found && grp->gr_mem[i])
1087 found = strcmp(name,
1092 * Otherwise, just check for username match
1095 found = strcmp(p, name) == 0;
1106 * Terminate login as previous user, if any, resetting state;
1107 * used when USER command is given or login fails.
1116 (void) seteuid((uid_t)0);
1118 ftpd_logwtmp(ttyline, "", NULL);
1121 setusercontext(NULL, getpwuid(0), (uid_t)0,
1122 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1125 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1126 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1127 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1128 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1129 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1130 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1141 * the following code is stolen from imap-uw PAM authentication module and
1144 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1147 const char *uname; /* user name */
1148 const char *pass; /* password */
1150 typedef struct cred_t cred_t;
1153 auth_conv(int num_msg, const struct pam_message **msg,
1154 struct pam_response **resp, void *appdata)
1157 cred_t *cred = (cred_t *) appdata;
1158 struct pam_response *reply;
1160 reply = calloc(num_msg, sizeof *reply);
1164 for (i = 0; i < num_msg; i++) {
1165 switch (msg[i]->msg_style) {
1166 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1167 reply[i].resp_retcode = PAM_SUCCESS;
1168 reply[i].resp = COPY_STRING(cred->uname);
1169 /* PAM frees resp. */
1171 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1172 reply[i].resp_retcode = PAM_SUCCESS;
1173 reply[i].resp = COPY_STRING(cred->pass);
1174 /* PAM frees resp. */
1178 reply[i].resp_retcode = PAM_SUCCESS;
1179 reply[i].resp = NULL;
1181 default: /* unknown message style */
1183 return PAM_CONV_ERR;
1192 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1193 * authenticated, or 1 if not authenticated. If some sort of PAM system
1194 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1195 * function returns -1. This can be used as an indication that we should
1196 * fall back to a different authentication mechanism.
1199 auth_pam(struct passwd **ppw, const char *pass)
1201 pam_handle_t *pamh = NULL;
1202 const char *tmpl_user;
1206 cred_t auth_cred = { (*ppw)->pw_name, pass };
1207 struct pam_conv conv = { &auth_conv, &auth_cred };
1209 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1210 if (e != PAM_SUCCESS) {
1211 syslog(LOG_ERR, "pam_start: %s", pam_strerror(pamh, e));
1215 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1216 if (e != PAM_SUCCESS) {
1217 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1218 pam_strerror(pamh, e));
1222 e = pam_authenticate(pamh, 0);
1226 * With PAM we support the concept of a "template"
1227 * user. The user enters a login name which is
1228 * authenticated by PAM, usually via a remote service
1229 * such as RADIUS or TACACS+. If authentication
1230 * succeeds, a different but related "template" name
1231 * is used for setting the credentials, shell, and
1232 * home directory. The name the user enters need only
1233 * exist on the remote authentication server, but the
1234 * template name must be present in the local password
1237 * This is supported by two various mechanisms in the
1238 * individual modules. However, from the application's
1239 * point of view, the template user is always passed
1240 * back as a changed value of the PAM_USER item.
1242 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1244 tmpl_user = (const char *) item;
1245 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1246 *ppw = getpwnam(tmpl_user);
1248 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1249 pam_strerror(pamh, e));
1254 case PAM_USER_UNKNOWN:
1260 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1266 e = pam_acct_mgmt(pamh, 0);
1267 if (e == PAM_NEW_AUTHTOK_REQD) {
1268 e = pam_chauthtok(pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
1269 if (e != PAM_SUCCESS) {
1270 syslog(LOG_ERR, "pam_chauthtok: %s", pam_strerror(pamh, e));
1273 } else if (e != PAM_SUCCESS) {
1279 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1280 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1287 #endif /* USE_PAM */
1295 login_cap_t *lc = NULL;
1302 if (logged_in || askpasswd == 0) {
1303 reply(503, "Login with USER first.");
1307 if (!guest) { /* "ftp" is only account allowed no password */
1309 rval = 1; /* failure below */
1313 rval = auth_pam(&pw, passwd);
1319 if (opieverify(&opiedata, passwd) == 0)
1320 xpasswd = pw->pw_passwd;
1322 xpasswd = crypt(passwd, pw->pw_passwd);
1323 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1329 rval = strcmp(pw->pw_passwd, xpasswd);
1330 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1331 rval = 1; /* failure */
1334 * If rval == 1, the user failed the authentication check
1335 * above. If rval == 0, either PAM or local authentication
1339 reply(530, "Login incorrect.");
1342 "FTP LOGIN FAILED FROM %s, %s",
1343 remotehost, curname);
1345 if (login_attempts++ >= 5) {
1347 "repeated login failures from %s",
1354 login_attempts = 0; /* this time successful */
1355 if (setegid((gid_t)pw->pw_gid) < 0) {
1356 reply(550, "Can't set gid.");
1359 /* May be overridden by login.conf */
1360 (void) umask(defumask);
1362 if ((lc = login_getpwclass(pw)) != NULL) {
1363 char remote_ip[MAXHOSTNAMELEN];
1365 getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1366 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1368 remote_ip[sizeof(remote_ip) - 1] = 0;
1369 if (!auth_hostok(lc, remotehost, remote_ip)) {
1370 syslog(LOG_INFO|LOG_AUTH,
1371 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1373 reply(530, "Permission denied.\n");
1377 if (!auth_timeok(lc, time(NULL))) {
1378 reply(530, "Login not available right now.\n");
1383 setusercontext(lc, pw, (uid_t)0,
1384 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1385 LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1387 setlogin(pw->pw_name);
1388 (void) initgroups(pw->pw_name, pw->pw_gid);
1393 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1394 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1395 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1396 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1401 /* open wtmp before chroot */
1402 ftpd_logwtmp(ttyline, pw->pw_name, (struct sockaddr *)&his_addr);
1405 if (guest && stats && statfd < 0)
1406 #ifdef VIRTUAL_HOSTING
1407 if ((statfd = open(thishost->statfile, O_WRONLY|O_APPEND)) < 0)
1409 if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0)
1414 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1415 login_getcapbool(lc, "ftp-chroot", 0) ||
1417 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1);
1420 * We MUST do a chdir() after the chroot. Otherwise
1421 * the old current directory will be accessible as "."
1422 * outside the new root!
1424 if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
1425 reply(550, "Can't set guest privileges.");
1428 } else if (dochroot) {
1429 if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
1430 reply(550, "Can't change root.");
1433 } else if (chdir(pw->pw_dir) < 0) {
1434 if (chdir("/") < 0) {
1435 reply(530, "User %s: can't change directory to %s.",
1436 pw->pw_name, pw->pw_dir);
1439 lreply(230, "No directory! Logging in with home=/");
1441 if (seteuid((uid_t)pw->pw_uid) < 0) {
1442 reply(550, "Can't set uid.");
1447 * Display a login message, if it exists.
1448 * N.B. reply(230,) must follow the message.
1450 #ifdef VIRTUAL_HOSTING
1451 if ((fd = fopen(thishost->loginmsg, "r")) != NULL) {
1453 if ((fd = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) {
1455 char *cp, line[LINE_MAX];
1457 while (fgets(line, sizeof(line), fd) != NULL) {
1458 if ((cp = strchr(line, '\n')) != NULL)
1460 lreply(230, "%s", line);
1462 (void) fflush(stdout);
1468 ident = strdup(passwd);
1470 fatalerror("Ran out of memory.");
1472 reply(230, "Guest login ok, access restrictions apply.");
1474 #ifdef VIRTUAL_HOSTING
1475 if (thishost != firsthost)
1476 snprintf(proctitle, sizeof(proctitle),
1477 "%s: anonymous(%s)/%s", remotehost, hostname,
1481 snprintf(proctitle, sizeof(proctitle),
1482 "%s: anonymous/%s", remotehost, passwd);
1483 setproctitle("%s", proctitle);
1484 #endif /* SETPROCTITLE */
1486 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1487 remotehost, passwd);
1490 reply(230, "User %s logged in, "
1491 "access restrictions apply.", pw->pw_name);
1493 reply(230, "User %s logged in.", pw->pw_name);
1496 snprintf(proctitle, sizeof(proctitle),
1497 "%s: user/%s", remotehost, pw->pw_name);
1498 setproctitle("%s", proctitle);
1499 #endif /* SETPROCTITLE */
1501 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1502 remotehost, pw->pw_name);
1509 /* Forget all about it... */
1517 retrieve(char *cmd, char *name)
1521 int (*closefunc)(FILE *);
1525 fin = fopen(name, "r"), closefunc = fclose;
1530 (void) snprintf(line, sizeof(line), cmd, name), name = line;
1531 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1533 st.st_blksize = BUFSIZ;
1537 perror_reply(550, name);
1539 LOGCMD("get", name);
1545 if (cmd == 0 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
1546 reply(550, "%s: not a plain file.", name);
1549 if (restart_point) {
1550 if (type == TYPE_A) {
1557 if ((c=getc(fin)) == EOF) {
1558 perror_reply(550, name);
1564 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1565 perror_reply(550, name);
1569 dout = dataconn(name, st.st_size, "w");
1573 send_data(fin, dout, st.st_blksize, st.st_size,
1574 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1575 if (cmd == 0 && guest && stats)
1576 logxfer(name, st.st_size, start);
1577 (void) fclose(dout);
1582 LOGBYTES("get", name, byte_count);
1587 store(char *name, char *mode, int unique)
1591 int (*closefunc)(FILE *);
1593 if ((unique || guest) && stat(name, &st) == 0 &&
1594 (name = gunique(name)) == NULL) {
1595 LOGCMD(*mode == 'w' ? "put" : "append", name);
1601 fout = fopen(name, mode);
1604 perror_reply(553, name);
1605 LOGCMD(*mode == 'w' ? "put" : "append", name);
1609 if (restart_point) {
1610 if (type == TYPE_A) {
1617 if ((c=getc(fout)) == EOF) {
1618 perror_reply(550, name);
1625 * We must do this seek to "current" position
1626 * because we are changing from reading to
1629 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1630 perror_reply(550, name);
1633 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1634 perror_reply(550, name);
1638 din = dataconn(name, (off_t)-1, "r");
1641 if (receive_data(din, fout) == 0) {
1643 reply(226, "Transfer complete (unique file name:%s).",
1646 reply(226, "Transfer complete.");
1652 LOGBYTES(*mode == 'w' ? "put" : "append", name, byte_count);
1657 getdatasock(char *mode)
1659 int on = 1, s, t, tries;
1662 return (fdopen(data, mode));
1663 (void) seteuid((uid_t)0);
1665 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1668 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
1669 (char *) &on, sizeof(on)) < 0)
1671 /* anchor socket to avoid multi-homing problems */
1672 data_source = ctrl_addr;
1673 data_source.su_port = htons(20); /* ftp-data port */
1674 for (tries = 1; ; tries++) {
1675 if (bind(s, (struct sockaddr *)&data_source,
1676 data_source.su_len) >= 0)
1678 if (errno != EADDRINUSE || tries > 10)
1682 (void) seteuid((uid_t)pw->pw_uid);
1684 if (data_source.su_family == AF_INET)
1686 on = IPTOS_THROUGHPUT;
1687 if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on, sizeof(int)) < 0)
1688 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
1693 * Turn off push flag to keep sender TCP from sending short packets
1694 * at the boundaries of each write(). Should probably do a SO_SNDBUF
1695 * to set the send buffer size as well, but that may not be desirable
1696 * in heavy-load situations.
1699 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, (char *)&on, sizeof on) < 0)
1700 syslog(LOG_WARNING, "setsockopt (TCP_NOPUSH): %m");
1704 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&on, sizeof on) < 0)
1705 syslog(LOG_WARNING, "setsockopt (SO_SNDBUF): %m");
1708 return (fdopen(s, mode));
1710 /* Return the real value of errno (close may change it) */
1712 (void) seteuid((uid_t)pw->pw_uid);
1719 dataconn(char *name, off_t size, char *mode)
1727 if (size != (off_t) -1)
1728 (void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)", size);
1732 union sockunion from;
1734 int s, fromlen = ctrl_addr.su_len;
1735 struct timeval timeout;
1739 FD_SET(pdata, &set);
1741 timeout.tv_usec = 0;
1742 timeout.tv_sec = 120;
1745 * Granted a socket is in the blocking I/O mode,
1746 * accept() will block after a successful select()
1747 * if the selected connection dies in between.
1748 * Therefore set the non-blocking I/O flag here.
1750 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1751 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1753 if (select(pdata+1, &set, (fd_set *) 0, (fd_set *) 0, &timeout) <= 0 ||
1754 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1756 (void) close(pdata);
1759 * Unset the blocking I/O flag on the child socket
1760 * again so stdio can work on it.
1762 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1763 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1766 if (from.su_family == AF_INET)
1768 tos = IPTOS_THROUGHPUT;
1769 (void) setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&tos,
1773 reply(150, "Opening %s mode data connection for '%s'%s.",
1774 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1775 return (fdopen(pdata, mode));
1777 reply(425, "Can't open data connection.");
1778 (void) close(pdata);
1783 reply(125, "Using existing data connection for '%s'%s.",
1786 return (fdopen(data, mode));
1789 data_dest = his_addr;
1791 file = getdatasock(mode);
1793 char hostbuf[BUFSIZ], portbuf[BUFSIZ];
1794 getnameinfo((struct sockaddr *)&data_source,
1795 data_source.su_len, hostbuf, sizeof(hostbuf) - 1,
1796 portbuf, sizeof(portbuf),
1797 NI_NUMERICHOST|NI_NUMERICSERV);
1798 reply(425, "Can't create data socket (%s,%s): %s.",
1799 hostbuf, portbuf, strerror(errno));
1802 data = fileno(file);
1803 while (connect(data, (struct sockaddr *)&data_dest,
1804 data_dest.su_len) < 0) {
1805 if (errno == EADDRINUSE && retry < swaitmax) {
1806 sleep((unsigned) swaitint);
1810 perror_reply(425, "Can't build data connection");
1811 (void) fclose(file);
1815 reply(150, "Opening %s mode data connection for '%s'%s.",
1816 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1821 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1822 * encapsulation of the data subject to Mode, Structure, and Type.
1824 * NB: Form isn't handled.
1827 send_data(FILE *instr, FILE *outstr, off_t blksize, off_t filesize, int isreg)
1829 int c, filefd, netfd;
1837 while ((c = getc(instr)) != EOF) {
1844 (void) putc('\r', outstr);
1846 (void) putc(c, outstr);
1856 reply(226, "Transfer complete.");
1862 * isreg is only set if we are not doing restart and we
1863 * are sending a regular file
1865 netfd = fileno(outstr);
1866 filefd = fileno(instr);
1873 err = cnt = offset = 0;
1875 while (err != -1 && filesize > 0) {
1876 err = sendfile(filefd, netfd, offset, 0,
1877 (struct sf_hdtr *) NULL, &cnt, 0);
1879 * Calculate byte_count before OOB processing.
1880 * It can be used in myoob() later.
1897 reply(226, "Transfer complete.");
1902 if ((buf = malloc((u_int)blksize)) == NULL) {
1904 perror_reply(451, "Local resource failure: malloc");
1908 while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
1909 write(netfd, buf, cnt) == cnt)
1918 reply(226, "Transfer complete.");
1922 reply(550, "Unimplemented TYPE %d in send_data", type);
1928 perror_reply(426, "Data connection");
1933 perror_reply(551, "Error on input file");
1944 * Transfer data from peer to "outstr" using the appropriate encapulation of
1945 * the data subject to Mode, Structure, and Type.
1947 * N.B.: Form isn't handled.
1950 receive_data(FILE *instr, FILE *outstr)
1963 while ((cnt = read(fileno(instr), buf, sizeof(buf))) > 0) {
1966 if (write(fileno(outstr), buf, cnt) != cnt)
1978 reply(553, "TYPE E not implemented.");
1983 while ((c = getc(instr)) != EOF) {
1992 if ((c = getc(instr)) != '\n') {
1993 (void) putc ('\r', outstr);
1994 if (c == '\0' || c == EOF)
1998 (void) putc(c, outstr);
2011 "WARNING! %d bare linefeeds received in ASCII mode",
2013 (void)printf(" File may not have transferred correctly.\r\n");
2017 reply(550, "Unimplemented TYPE %d in receive_data", type);
2024 perror_reply(426, "Data Connection");
2029 perror_reply(452, "Error writing file");
2040 statfilecmd(char *filename)
2044 char line[LINE_MAX];
2046 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2047 fin = ftpd_popen(line, "r");
2048 lreply(211, "status of %s:", filename);
2049 while ((c = getc(fin)) != EOF) {
2051 if (ferror(stdout)){
2052 perror_reply(421, "control connection");
2053 (void) ftpd_pclose(fin);
2058 perror_reply(551, filename);
2059 (void) ftpd_pclose(fin);
2062 (void) putc('\r', stdout);
2064 (void) putc(c, stdout);
2066 (void) ftpd_pclose(fin);
2067 reply(211, "End of Status");
2073 union sockunion *su;
2075 char hname[NI_MAXHOST];
2078 lreply(211, "%s FTP server status:", hostname, version);
2079 printf(" %s\r\n", version);
2080 printf(" Connected to %s", remotehost);
2081 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2082 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2083 if (strcmp(hname, remotehost) != 0)
2084 printf(" (%s)", hname);
2089 printf(" Logged in anonymously\r\n");
2091 printf(" Logged in as %s\r\n", pw->pw_name);
2092 } else if (askpasswd)
2093 printf(" Waiting for password\r\n");
2095 printf(" Waiting for user name\r\n");
2096 printf(" TYPE: %s", typenames[type]);
2097 if (type == TYPE_A || type == TYPE_E)
2098 printf(", FORM: %s", formnames[form]);
2101 printf(" %d", NBBY);
2103 printf(" %d", bytesize); /* need definition! */
2105 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2106 strunames[stru], modenames[mode]);
2108 printf(" Data connection open\r\n");
2109 else if (pdata != -1) {
2113 } else if (usedefault == 0) {
2117 #define UC(b) (((int) b) & 0xff)
2119 printf(" EPSV only mode (EPSV ALL)\r\n");
2124 if (su->su_family == AF_INET) {
2125 a = (u_char *) &su->su_sin.sin_addr;
2126 p = (u_char *) &su->su_sin.sin_port;
2127 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2128 ispassive ? "PASV" : "PORT",
2129 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2130 UC(p[0]), UC(p[1]));
2137 switch (su->su_family) {
2139 a = (u_char *) &su->su_sin.sin_addr;
2140 p = (u_char *) &su->su_sin.sin_port;
2141 alen = sizeof(su->su_sin.sin_addr);
2145 a = (u_char *) &su->su_sin6.sin6_addr;
2146 p = (u_char *) &su->su_sin6.sin6_port;
2147 alen = sizeof(su->su_sin6.sin6_addr);
2155 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2157 for (i = 0; i < alen; i++)
2158 printf("%d,", UC(a[i]));
2159 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2168 switch (su->su_family) {
2180 union sockunion tmp;
2183 if (tmp.su_family == AF_INET6)
2184 tmp.su_sin6.sin6_scope_id = 0;
2185 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2186 hname, sizeof(hname) - 1, NULL, 0,
2188 printf(" %s |%d|%s|%d|\r\n",
2189 ispassive ? "EPSV" : "EPRT",
2190 af, hname, htons(tmp.su_port));
2196 printf(" No data connection\r\n");
2197 reply(211, "End of status");
2204 reply(451, "Error in server: %s\n", s);
2205 reply(221, "Closing connection due to server error.");
2211 reply(int n, const char *fmt, ...)
2216 (void)printf("%d ", n);
2217 (void)vprintf(fmt, ap);
2218 (void)printf("\r\n");
2219 (void)fflush(stdout);
2221 syslog(LOG_DEBUG, "<--- %d ", n);
2222 vsyslog(LOG_DEBUG, fmt, ap);
2227 lreply(int n, const char *fmt, ...)
2232 (void)printf("%d- ", n);
2233 (void)vprintf(fmt, ap);
2234 (void)printf("\r\n");
2235 (void)fflush(stdout);
2237 syslog(LOG_DEBUG, "<--- %d- ", n);
2238 vsyslog(LOG_DEBUG, fmt, ap);
2246 reply(250, "%s command successful.", s);
2253 reply(502, "%s command not implemented.", s);
2262 if ((cp = strchr(cbuf,'\n')))
2264 reply(500, "'%s': command not understood.", cbuf);
2272 LOGCMD("delete", name);
2273 if (stat(name, &st) < 0) {
2274 perror_reply(550, name);
2277 if ((st.st_mode&S_IFMT) == S_IFDIR) {
2278 if (rmdir(name) < 0) {
2279 perror_reply(550, name);
2284 if (unlink(name) < 0) {
2285 perror_reply(550, name);
2296 if (chdir(path) < 0)
2297 perror_reply(550, path);
2306 LOGCMD("mkdir", name);
2307 if (guest && noguestmkd)
2308 reply(550, "%s: permission denied", name);
2309 else if (mkdir(name, 0777) < 0)
2310 perror_reply(550, name);
2312 reply(257, "MKD command successful.");
2316 removedir(char *name)
2319 LOGCMD("rmdir", name);
2320 if (rmdir(name) < 0)
2321 perror_reply(550, name);
2329 char path[MAXPATHLEN + 1];
2331 if (getwd(path) == (char *)NULL)
2332 reply(550, "%s.", path);
2334 reply(257, "\"%s\" is current directory.", path);
2338 renamefrom(char *name)
2342 if (stat(name, &st) < 0) {
2343 perror_reply(550, name);
2346 reply(350, "File exists, ready for destination name");
2351 renamecmd(char *from, char *to)
2355 LOGCMD2("rename", from, to);
2357 if (guest && (stat(to, &st) == 0)) {
2358 reply(550, "%s: permission denied", to);
2362 if (rename(from, to) < 0)
2363 perror_reply(550, "rename");
2369 dolog(struct sockaddr *who)
2373 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2376 #ifdef VIRTUAL_HOSTING
2377 if (thishost != firsthost)
2378 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2379 remotehost, hostname);
2382 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2384 setproctitle("%s", proctitle);
2385 #endif /* SETPROCTITLE */
2388 #ifdef VIRTUAL_HOSTING
2389 if (thishost != firsthost)
2390 syslog(LOG_INFO, "connection from %s (to %s)",
2391 remotehost, hostname);
2395 char who_name[MAXHOSTNAMELEN];
2397 error = getnameinfo(who, who->sa_len,
2398 who_name, sizeof(who_name) - 1,
2399 NULL, 0, NI_NUMERICHOST);
2400 syslog(LOG_INFO, "connection from %s (%s)", remotehost,
2401 error == 0 ? who_name : "");
2407 * Record logout in wtmp file
2408 * and exit with supplied status.
2411 dologout(int status)
2414 * Prevent reception of SIGURG from resulting in a resumption
2415 * back to the main program loop.
2420 (void) seteuid((uid_t)0);
2421 ftpd_logwtmp(ttyline, "", NULL);
2423 /* beware of flushing buffers after a SIGPIPE */
2439 /* only process if transfer occurring */
2443 if (getline(cp, 7, stdin) == NULL) {
2444 reply(221, "You could at least say goodbye.");
2448 if (strcmp(cp, "ABOR\r\n") == 0) {
2450 reply(426, "Transfer aborted. Data connection closed.");
2451 reply(226, "Abort successful");
2453 if (strcmp(cp, "STAT\r\n") == 0) {
2455 if (file_size != (off_t) -1)
2456 reply(213, "Status: %qd of %qd bytes transferred",
2457 byte_count, file_size);
2459 reply(213, "Status: %qd bytes transferred", byte_count);
2464 * Note: a response of 425 is not mentioned as a possible response to
2465 * the PASV command in RFC959. However, it has been blessed as
2466 * a legitimate response by Jon Postel in a telephone conversation
2467 * with Rick Adams on 25 Jan 89.
2475 if (pdata >= 0) /* close old port if one set */
2478 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2480 perror_reply(425, "Can't open passive connection");
2484 (void) seteuid((uid_t)0);
2487 if (ctrl_addr.su_family == AF_INET) {
2488 int on = restricted_data_ports ? IP_PORTRANGE_HIGH
2489 : IP_PORTRANGE_DEFAULT;
2491 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2492 (char *)&on, sizeof(on)) < 0)
2496 #ifdef IPV6_PORTRANGE
2497 if (ctrl_addr.su_family == AF_INET6) {
2498 int on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2499 : IPV6_PORTRANGE_DEFAULT;
2501 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2502 (char *)&on, sizeof(on)) < 0)
2507 pasv_addr = ctrl_addr;
2508 pasv_addr.su_port = 0;
2509 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2512 (void) seteuid((uid_t)pw->pw_uid);
2514 len = sizeof(pasv_addr);
2515 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2517 if (listen(pdata, 1) < 0)
2519 if (pasv_addr.su_family == AF_INET)
2520 a = (char *) &pasv_addr.su_sin.sin_addr;
2521 else if (pasv_addr.su_family == AF_INET6 &&
2522 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2523 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2527 p = (char *) &pasv_addr.su_port;
2529 #define UC(b) (((int) b) & 0xff)
2531 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2532 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2536 (void) seteuid((uid_t)pw->pw_uid);
2537 (void) close(pdata);
2539 perror_reply(425, "Can't open passive connection");
2544 * Long Passive defined in RFC 1639.
2545 * 228 Entering Long Passive Mode
2546 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2550 long_passive(char *cmd, int pf)
2555 if (pdata >= 0) /* close old port if one set */
2558 if (pf != PF_UNSPEC) {
2559 if (ctrl_addr.su_family != pf) {
2560 switch (ctrl_addr.su_family) {
2573 * only EPRT/EPSV ready clients will understand this
2575 if (strcmp(cmd, "EPSV") == 0 && pf) {
2576 reply(522, "Network protocol mismatch, "
2579 reply(501, "Network protocol mismatch"); /*XXX*/
2585 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2587 perror_reply(425, "Can't open passive connection");
2591 (void) seteuid((uid_t)0);
2593 pasv_addr = ctrl_addr;
2594 pasv_addr.su_port = 0;
2595 len = pasv_addr.su_len;
2598 if (ctrl_addr.su_family == AF_INET) {
2599 int on = restricted_data_ports ? IP_PORTRANGE_HIGH
2600 : IP_PORTRANGE_DEFAULT;
2602 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2603 (char *)&on, sizeof(on)) < 0)
2607 #ifdef IPV6_PORTRANGE
2608 if (ctrl_addr.su_family == AF_INET6) {
2609 int on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2610 : IPV6_PORTRANGE_DEFAULT;
2612 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2613 (char *)&on, sizeof(on)) < 0)
2618 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2621 (void) seteuid((uid_t)pw->pw_uid);
2623 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2625 if (listen(pdata, 1) < 0)
2628 #define UC(b) (((int) b) & 0xff)
2630 if (strcmp(cmd, "LPSV") == 0) {
2631 p = (char *)&pasv_addr.su_port;
2632 switch (pasv_addr.su_family) {
2634 a = (char *) &pasv_addr.su_sin.sin_addr;
2637 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2638 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2639 2, UC(p[0]), UC(p[1]));
2642 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
2643 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2646 a = (char *) &pasv_addr.su_sin6.sin6_addr;
2648 "Entering Long Passive Mode "
2649 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2650 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2651 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2652 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2653 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2654 2, UC(p[0]), UC(p[1]));
2657 } else if (strcmp(cmd, "EPSV") == 0) {
2658 switch (pasv_addr.su_family) {
2661 reply(229, "Entering Extended Passive Mode (|||%d|)",
2662 ntohs(pasv_addr.su_port));
2666 /* more proper error code? */
2670 (void) seteuid((uid_t)pw->pw_uid);
2671 (void) close(pdata);
2673 perror_reply(425, "Can't open passive connection");
2678 * Generate unique name for file with basename "local".
2679 * The file named "local" is already known to exist.
2680 * Generates failure reply on error.
2683 gunique(char *local)
2685 static char new[MAXPATHLEN];
2690 cp = strrchr(local, '/');
2693 if (stat(cp ? local : ".", &st) < 0) {
2694 perror_reply(553, cp ? local : ".");
2695 return ((char *) 0);
2699 /* -4 is for the .nn<null> we put on the end below */
2700 (void) snprintf(new, sizeof(new) - 4, "%s", local);
2701 cp = new + strlen(new);
2703 for (count = 1; count < 100; count++) {
2704 (void)sprintf(cp, "%d", count);
2705 if (stat(new, &st) < 0)
2708 reply(452, "Unique file name cannot be created.");
2713 * Format and send reply containing system error number.
2716 perror_reply(int code, char *string)
2719 reply(code, "%s: %s.", string, strerror(errno));
2722 static char *onefile[] = {
2728 send_file_list(char *whichf)
2734 char **dirlist, *dirname;
2739 if (strpbrk(whichf, "~{[*?") != NULL) {
2740 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
2742 memset(&gl, 0, sizeof(gl));
2743 gl.gl_matchc = MAXGLOBARGS;
2744 flags |= GLOB_LIMIT;
2746 if (glob(whichf, flags, 0, &gl)) {
2747 reply(550, "not found");
2749 } else if (gl.gl_pathc == 0) {
2751 perror_reply(550, whichf);
2754 dirlist = gl.gl_pathv;
2756 onefile[0] = whichf;
2761 while ((dirname = *dirlist++)) {
2762 if (stat(dirname, &st) < 0) {
2764 * If user typed "ls -l", etc, and the client
2765 * used NLST, do what the user meant.
2767 if (dirname[0] == '-' && *dirlist == NULL &&
2769 retrieve(_PATH_LS " %s", dirname);
2772 perror_reply(550, whichf);
2774 (void) fclose(dout);
2782 if (S_ISREG(st.st_mode)) {
2784 dout = dataconn("file list", (off_t)-1, "w");
2789 fprintf(dout, "%s%s\n", dirname,
2790 type == TYPE_A ? "\r" : "");
2791 byte_count += strlen(dirname) + 1;
2793 } else if (!S_ISDIR(st.st_mode))
2796 if ((dirp = opendir(dirname)) == NULL)
2799 while ((dir = readdir(dirp)) != NULL) {
2800 char nbuf[MAXPATHLEN];
2809 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
2811 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
2815 snprintf(nbuf, sizeof(nbuf),
2816 "%s/%s", dirname, dir->d_name);
2819 * We have to do a stat to insure it's
2820 * not a directory or special file.
2822 if (simple || (stat(nbuf, &st) == 0 &&
2823 S_ISREG(st.st_mode))) {
2825 dout = dataconn("file list", (off_t)-1,
2831 if (nbuf[0] == '.' && nbuf[1] == '/')
2832 fprintf(dout, "%s%s\n", &nbuf[2],
2833 type == TYPE_A ? "\r" : "");
2835 fprintf(dout, "%s%s\n", nbuf,
2836 type == TYPE_A ? "\r" : "");
2837 byte_count += strlen(nbuf) + 1;
2840 (void) closedir(dirp);
2844 reply(550, "No files found.");
2845 else if (ferror(dout) != 0)
2846 perror_reply(550, "Data connection");
2848 reply(226, "Transfer complete.");
2852 (void) fclose(dout);
2863 reapchild(int signo)
2865 while (wait3(NULL, WNOHANG, NULL) > 0);
2868 #ifdef OLD_SETPROCTITLE
2870 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.)
2871 * Warning, since this is usually started from inetd.conf, it often doesn't
2872 * have much of an environment or arglist to overwrite.
2875 setproctitle(const char *fmt, ...)
2883 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
2885 /* make ps print our process name */
2890 if (i > LastArgv - p - 2) {
2891 i = LastArgv - p - 2;
2896 if (ch != '\n' && ch != '\r')
2898 while (p < LastArgv)
2901 #endif /* OLD_SETPROCTITLE */
2904 logxfer(char *name, off_t size, time_t start)
2907 char path[MAXPATHLEN + 1];
2910 if (statfd >= 0 && getwd(path) != NULL) {
2912 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s/%s!%qd!%ld\n",
2913 ctime(&now)+4, ident, remotehost,
2914 path, name, (long long)size,
2915 (long)(now - start + (now == start)));
2916 write(statfd, buf, strlen(buf));