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"
107 static char version[] = "Version 6.00LS";
110 /* wrapper for KAME-special getnameinfo() */
111 #ifndef NI_WITHSCOPEID
112 #define NI_WITHSCOPEID 0
115 extern off_t restart_point;
118 union sockunion server_addr;
119 union sockunion ctrl_addr;
120 union sockunion data_source;
121 union sockunion data_dest;
122 union sockunion his_addr;
123 union sockunion pasv_addr;
130 int timeout = 900; /* timeout after 15 minutes of inactivity */
131 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
133 int restricted_data_ports = 1;
134 int paranoid = 1; /* be extra careful about security */
135 int anon_only = 0; /* Only anonymous ftp allowed */
142 int stru; /* avoid C keyword */
144 int usedefault = 1; /* for data transfers */
145 int pdata = -1; /* for passive mode */
146 int readonly=0; /* Server is in readonly mode. */
147 int noepsv=0; /* EPSV command is disabled. */
148 int noretr=0; /* RETR command is disabled. */
149 int noguestretr=0; /* RETR command is disabled for anon users. */
151 static volatile sig_atomic_t recvurg;
152 sig_atomic_t transflag;
155 #if !defined(CMASK) || CMASK == 0
159 int defumask = CMASK; /* default umask value */
164 #ifdef VIRTUAL_HOSTING
167 static struct ftphost {
168 struct ftphost *next;
169 struct addrinfo *hostinfo;
175 } *thishost, *firsthost;
178 char remotehost[MAXHOSTNAMELEN];
181 static char ttyline[20];
182 char *tty = ttyline; /* for klogin */
185 static int auth_pam(struct passwd**, const char*);
186 pam_handle_t *pamh = NULL;
189 static struct opie opiedata;
190 static char opieprompt[OPIE_CHALLENGE_MAX+1];
193 char *pid_file = NULL;
196 * Limit number of pathnames that glob can return.
197 * A limit of 0 indicates the number of pathnames is unlimited.
199 #define MAXGLOBARGS 16384
203 * Timeout intervals for retrying connections
204 * to hosts that don't accept PORT cmds. This
205 * is a kludge, but given the problems with TCP...
207 #define SWAITMAX 90 /* wait at most 90 seconds */
208 #define SWAITINT 5 /* interval between retries */
210 int swaitmax = SWAITMAX;
211 int swaitint = SWAITINT;
214 #ifdef OLD_SETPROCTITLE
215 char **Argv = NULL; /* pointer to argument vector */
216 char *LastArgv = NULL; /* end of argv */
217 #endif /* OLD_SETPROCTITLE */
218 char proctitle[LINE_MAX]; /* initial part of title */
219 #endif /* SETPROCTITLE */
221 #define LOGCMD(cmd, file) \
223 syslog(LOG_INFO,"%s %s%s", cmd, \
224 *(file) == '/' ? "" : curdir(), file);
225 #define LOGCMD2(cmd, file1, file2) \
227 syslog(LOG_INFO,"%s %s%s %s%s", cmd, \
228 *(file1) == '/' ? "" : curdir(), file1, \
229 *(file2) == '/' ? "" : curdir(), file2);
230 #define LOGBYTES(cmd, file, cnt) \
232 if (cnt == (off_t)-1) \
233 syslog(LOG_INFO,"%s %s%s", cmd, \
234 *(file) == '/' ? "" : curdir(), file); \
236 syslog(LOG_INFO, "%s %s%s = %qd bytes", \
237 cmd, (*(file) == '/') ? "" : curdir(), file, cnt); \
240 #ifdef VIRTUAL_HOSTING
241 static void inithosts(void);
242 static void selecthost(union sockunion *);
244 static void ack(char *);
245 static void sigurg(int);
246 static void myoob(void);
247 static int checkuser(char *, char *, int);
248 static FILE *dataconn(char *, off_t, char *);
249 static void dolog(struct sockaddr *);
250 static char *curdir(void);
251 static void end_login(void);
252 static FILE *getdatasock(char *);
253 static char *gunique(char *);
254 static void lostconn(int);
255 static void sigquit(int);
256 static int receive_data(FILE *, FILE *);
257 static int send_data(FILE *, FILE *, off_t, off_t, int);
258 static struct passwd *
260 static char *sgetsave(char *);
261 static void reapchild(int);
262 static void logxfer(char *, off_t, time_t);
267 static char path[MAXPATHLEN+1+1]; /* path + '/' + '\0' */
269 if (getcwd(path, sizeof(path)-2) == NULL)
271 if (path[1] != '\0') /* special case for root dir. */
273 /* For guest account, skip / since it's chrooted */
274 return (guest ? path+1 : path);
278 main(int argc, char *argv[], char **envp)
280 int addrlen, ch, on = 1, tos;
281 char *cp, line[LINE_MAX];
284 char *bindname = NULL;
285 int family = AF_UNSPEC;
289 tzset(); /* in case no timezone database in ~ftp */
290 sigemptyset(&sa.sa_mask);
291 sa.sa_flags = SA_RESTART;
293 #ifdef OLD_SETPROCTITLE
295 * Save start and extent of argv for setproctitle.
300 LastArgv = envp[-1] + strlen(envp[-1]);
301 #endif /* OLD_SETPROCTITLE */
304 while ((ch = getopt(argc, argv, "AdlDESURrt:T:u:vOoa:p:46")) != -1) {
319 logging++; /* > 1 == extra logging */
335 maxtimeout = atoi(optarg);
336 if (timeout > maxtimeout)
337 timeout = maxtimeout;
341 timeout = atoi(optarg);
342 if (maxtimeout < timeout)
343 maxtimeout = timeout;
347 restricted_data_ports = 0;
362 val = strtol(optarg, &optarg, 8);
363 if (*optarg != '\0' || val < 0)
364 warnx("bad value for -u");
379 if (family == AF_UNSPEC)
396 warnx("unknown flag -%c ignored", optopt);
401 #ifdef VIRTUAL_HOSTING
404 (void) freopen(_PATH_DEVNULL, "w", stderr);
407 * LOG_NDELAY sets up the logging connection immediately,
408 * necessary for anonymous ftp's that chroot and can't do it later.
410 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
414 struct addrinfo hints, *res;
417 * Detach from parent.
419 if (daemon(1, 1) < 0) {
420 syslog(LOG_ERR, "failed to become a daemon");
423 sa.sa_handler = reapchild;
424 (void)sigaction(SIGCHLD, &sa, NULL);
426 memset(&hints, 0, sizeof(hints));
428 hints.ai_family = family == AF_UNSPEC ? AF_INET : family;
429 hints.ai_socktype = SOCK_STREAM;
430 hints.ai_protocol = 0;
431 hints.ai_flags = AI_PASSIVE;
432 error = getaddrinfo(bindname, "ftp", &hints, &res);
434 if (family == AF_UNSPEC) {
435 hints.ai_family = AF_UNSPEC;
436 error = getaddrinfo(bindname, "ftp", &hints,
441 syslog(LOG_ERR, "%s", gai_strerror(error));
442 if (error == EAI_SYSTEM)
443 syslog(LOG_ERR, "%s", strerror(errno));
446 if (res->ai_addr == NULL) {
447 syslog(LOG_ERR, "-a %s: getaddrinfo failed", hostname);
450 family = res->ai_addr->sa_family;
452 * Open a socket, bind it to the FTP port, and start
455 ctl_sock = socket(family, SOCK_STREAM, 0);
457 syslog(LOG_ERR, "control socket: %m");
460 if (setsockopt(ctl_sock, SOL_SOCKET, SO_REUSEADDR,
461 (char *)&on, sizeof(on)) < 0)
462 syslog(LOG_ERR, "control setsockopt: %m");
463 #ifdef IPV6_BINDV6ONLY
464 if (family == AF_INET6 && enable_v4 == 0) {
465 if (setsockopt(ctl_sock, IPPROTO_IPV6, IPV6_BINDV6ONLY,
466 (char *)&on, sizeof (on)) < 0)
468 "control setsockopt(IPV6_BINDV6ONLY): %m");
470 #endif /* IPV6_BINDV6ONLY */
471 memcpy(&server_addr, res->ai_addr, res->ai_addr->sa_len);
472 if (bind(ctl_sock, (struct sockaddr *)&server_addr,
473 server_addr.su_len) < 0) {
474 syslog(LOG_ERR, "control bind: %m");
477 if (listen(ctl_sock, 32) < 0) {
478 syslog(LOG_ERR, "control listen: %m");
482 * Atomically write process ID
489 fd = open(pid_file, O_CREAT | O_WRONLY | O_TRUNC
490 | O_NONBLOCK | O_EXLOCK, 0644);
493 errx(1, "%s: file locked", pid_file);
495 err(1, "%s", pid_file);
497 snprintf(buf, sizeof(buf),
498 "%lu\n", (unsigned long) getpid());
499 if (write(fd, buf, strlen(buf)) < 0)
500 err(1, "%s: write", pid_file);
501 /* Leave the pid file open and locked */
504 * Loop forever accepting connection requests and forking off
505 * children to handle them.
508 addrlen = server_addr.su_len;
509 fd = accept(ctl_sock, (struct sockaddr *)&his_addr, &addrlen);
520 addrlen = sizeof(his_addr);
521 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
522 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
527 sa.sa_handler = SIG_DFL;
528 (void)sigaction(SIGCHLD, &sa, NULL);
530 sa.sa_handler = sigurg;
531 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
532 (void)sigaction(SIGURG, &sa, NULL);
534 sigfillset(&sa.sa_mask); /* block all signals in handler */
535 sa.sa_flags = SA_RESTART;
536 sa.sa_handler = sigquit;
537 (void)sigaction(SIGHUP, &sa, NULL);
538 (void)sigaction(SIGINT, &sa, NULL);
539 (void)sigaction(SIGQUIT, &sa, NULL);
540 (void)sigaction(SIGTERM, &sa, NULL);
542 sa.sa_handler = lostconn;
543 (void)sigaction(SIGPIPE, &sa, NULL);
545 addrlen = sizeof(ctrl_addr);
546 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
547 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
550 #ifdef VIRTUAL_HOSTING
551 /* select our identity from virtual host table */
552 selecthost(&ctrl_addr);
555 if (ctrl_addr.su_family == AF_INET)
557 tos = IPTOS_LOWDELAY;
558 if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(int)) < 0)
559 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
563 * Disable Nagle on the control channel so that we don't have to wait
564 * for peer's ACK before issuing our next reply.
566 if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
567 syslog(LOG_WARNING, "control setsockopt TCP_NODELAY: %m");
569 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
571 /* set this here so klogin can use it... */
572 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
574 /* Try to handle urgent data inline */
576 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
577 syslog(LOG_ERR, "setsockopt: %m");
581 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
582 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
584 dolog((struct sockaddr *)&his_addr);
586 * Set up default state
595 /* If logins are disabled, print out the message. */
596 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
597 while (fgets(line, sizeof(line), fd) != NULL) {
598 if ((cp = strchr(line, '\n')) != NULL)
600 lreply(530, "%s", line);
602 (void) fflush(stdout);
604 reply(530, "System not available.");
607 #ifdef VIRTUAL_HOSTING
608 if ((fd = fopen(thishost->welcome, "r")) != NULL) {
610 if ((fd = fopen(_PATH_FTPWELCOME, "r")) != NULL) {
612 while (fgets(line, sizeof(line), fd) != NULL) {
613 if ((cp = strchr(line, '\n')) != NULL)
615 lreply(220, "%s", line);
617 (void) fflush(stdout);
619 /* reply(220,) must follow */
621 #ifndef VIRTUAL_HOSTING
622 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
623 fatalerror("Ran out of memory.");
624 (void) gethostname(hostname, MAXHOSTNAMELEN - 1);
625 hostname[MAXHOSTNAMELEN - 1] = '\0';
627 reply(220, "%s FTP server (%s) ready.", hostname, version);
638 syslog(LOG_DEBUG, "lost connection");
646 syslog(LOG_ERR, "got signal %d", signo);
650 #ifdef VIRTUAL_HOSTING
652 * read in virtual host tables (if they exist)
660 struct ftphost *hrp, *lhrp;
662 struct addrinfo hints, *res, *ai;
665 * Fill in the default host information
667 if (gethostname(line, sizeof(line)) < 0)
669 if ((hrp = malloc(sizeof(struct ftphost))) == NULL ||
670 (hrp->hostname = strdup(line)) == NULL)
671 fatalerror("Ran out of memory.");
672 hrp->hostinfo = NULL;
674 memset(&hints, 0, sizeof(hints));
675 hints.ai_flags = AI_CANONNAME;
676 hints.ai_family = AF_UNSPEC;
677 getaddrinfo(hrp->hostname, NULL, &hints, &res);
680 hrp->statfile = _PATH_FTPDSTATFILE;
681 hrp->welcome = _PATH_FTPWELCOME;
682 hrp->loginmsg = _PATH_FTPLOGINMESG;
683 hrp->anonuser = "ftp";
685 thishost = firsthost = lhrp = hrp;
686 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
687 int addrsize, error, gothost;
691 while (fgets(line, sizeof(line), fp) != NULL) {
694 if ((cp = strchr(line, '\n')) == NULL) {
695 /* ignore long lines */
696 while (fgets(line, sizeof(line), fp) != NULL &&
697 strchr(line, '\n') == NULL)
702 cp = strtok(line, " \t");
703 /* skip comments and empty lines */
704 if (cp == NULL || line[0] == '#')
708 hints.ai_family = AF_UNSPEC;
709 hints.ai_flags = AI_PASSIVE;
710 error = getaddrinfo(cp, NULL, &hints, &res);
713 for (ai = res; ai != NULL && ai->ai_addr != NULL;
717 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
720 for (hi = hrp->hostinfo; hi != NULL;
722 if (hi->ai_addrlen == ai->ai_addrlen &&
725 ai->ai_addr->sa_len) == 0) {
733 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
736 hrp->statfile = _PATH_FTPDSTATFILE;
737 hrp->welcome = _PATH_FTPWELCOME;
738 hrp->loginmsg = _PATH_FTPLOGINMESG;
739 hrp->anonuser = "ftp";
747 * determine hostname to use.
748 * force defined name if there is a valid alias
749 * otherwise fallback to primary hostname
751 /* XXX: getaddrinfo() can't do alias check */
752 switch(hrp->hostinfo->ai_family) {
754 addr = &((struct sockaddr_in *)&hrp->hostinfo->ai_addr)->sin_addr;
755 addrsize = sizeof(struct sockaddr_in);
758 addr = &((struct sockaddr_in6 *)&hrp->hostinfo->ai_addr)->sin6_addr;
759 addrsize = sizeof(struct sockaddr_in6);
762 /* should not reach here */
763 if (hrp->hostinfo != NULL)
764 freeaddrinfo(hrp->hostinfo);
769 if ((hp = getipnodebyaddr((char*)addr, addrsize,
770 hrp->hostinfo->ai_family,
771 &hp_error)) != NULL) {
772 if (strcmp(cp, hp->h_name) != 0) {
773 if (hp->h_aliases == NULL)
777 while (hp->h_aliases[i] &&
778 strcmp(cp, hp->h_aliases[i]) != 0)
780 if (hp->h_aliases[i] == NULL)
785 hrp->hostname = strdup(cp);
787 /* ok, now we now peel off the rest */
789 while (i < 4 && (cp = strtok(NULL, " \t")) != NULL) {
790 if (*cp != '-' && (cp = strdup(cp)) != NULL) {
792 case 0: /* anon user permissions */
795 case 1: /* statistics file */
798 case 2: /* welcome message */
801 case 3: /* login message */
808 /* XXX: re-initialization for getaddrinfo() loop */
809 cp = strtok(line, " \t");
817 selecthost(union sockunion *su)
822 struct in6_addr *mapped_in6 = NULL;
828 * XXX IPv4 mapped IPv6 addr consideraton,
829 * specified in rfc2373.
831 if (su->su_family == AF_INET6 &&
832 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
833 mapped_in6 = &su->su_sin6.sin6_addr;
836 hrp = thishost = firsthost; /* default */
839 while (hrp != NULL) {
840 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
841 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
846 /* XXX IPv4 mapped IPv6 addr consideraton */
847 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
848 (memcmp(&mapped_in6->s6_addr[12],
849 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
850 sizeof(struct in_addr)) == 0)) {
859 /* setup static variables as appropriate */
860 hostname = thishost->hostname;
861 ftpuser = thishost->anonuser;
866 * Helper function for sgetpwnam().
871 char *new = malloc((unsigned) strlen(s) + 1);
874 perror_reply(421, "Local resource failure: malloc");
878 (void) strcpy(new, s);
883 * Save the result of a getpwnam. Used for USER command, since
884 * the data returned must not be clobbered by any other command
887 static struct passwd *
888 sgetpwnam(char *name)
890 static struct passwd save;
893 if ((p = getpwnam(name)) == NULL)
897 free(save.pw_passwd);
903 save.pw_name = sgetsave(p->pw_name);
904 save.pw_passwd = sgetsave(p->pw_passwd);
905 save.pw_gecos = sgetsave(p->pw_gecos);
906 save.pw_dir = sgetsave(p->pw_dir);
907 save.pw_shell = sgetsave(p->pw_shell);
911 static int login_attempts; /* number of failed login attempts */
912 static int askpasswd; /* had user command, ask for passwd */
913 static char curname[MAXLOGNAME]; /* current USER name */
917 * Sets global passwd pointer pw if named account exists and is acceptable;
918 * sets askpasswd if a PASS command is expected. If logged in previously,
919 * need to reset state. If name is "ftp" or "anonymous", the name is not in
920 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
921 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
922 * requesting login privileges. Disallow anyone who does not have a standard
923 * shell as returned by getusershell(). Disallow anyone mentioned in the file
924 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
933 reply(530, "Can't change user from guest login.");
935 } else if (dochroot) {
936 reply(530, "Can't change user from chroot user.");
943 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
944 if (checkuser(_PATH_FTPUSERS, "ftp", 0) ||
945 checkuser(_PATH_FTPUSERS, "anonymous", 0))
946 reply(530, "User %s access denied.", name);
947 #ifdef VIRTUAL_HOSTING
948 else if ((pw = sgetpwnam(thishost->anonuser)) != NULL) {
950 else if ((pw = sgetpwnam("ftp")) != NULL) {
955 "Guest login ok, send your email address as password.");
957 reply(530, "User %s unknown.", name);
958 if (!askpasswd && logging)
960 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
963 if (anon_only != 0) {
964 reply(530, "Sorry, only anonymous ftp allowed.");
968 if ((pw = sgetpwnam(name))) {
969 if ((shell = pw->pw_shell) == NULL || *shell == 0)
970 shell = _PATH_BSHELL;
971 while ((cp = getusershell()) != NULL)
972 if (strcmp(cp, shell) == 0)
976 if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1)) {
977 reply(530, "User %s access denied.", name);
980 "FTP LOGIN REFUSED FROM %s, %s",
982 pw = (struct passwd *) NULL;
987 strncpy(curname, name, sizeof(curname)-1);
991 /* XXX Kluge! The conversation mechanism needs to be fixed. */
993 if (opiechallenge(&opiedata, name, opieprompt) == 0) {
994 pwok = (pw != NULL) &&
995 opieaccessfile(remotehost) &&
996 opiealways(pw->pw_dir);
997 reply(331, "Response to %s %s for %s.",
998 opieprompt, pwok ? "requested" : "required", name);
1001 reply(331, "Password required for %s.", name);
1005 * Delay before reading passwd after first failed
1006 * attempt to slow down passwd-guessing programs.
1009 sleep((unsigned) login_attempts);
1013 * Check if a user is in the file "fname"
1016 checkuser(char *fname, char *name, int pwset)
1020 char *p, line[BUFSIZ];
1022 if ((fd = fopen(fname, "r")) != NULL) {
1023 while (!found && fgets(line, sizeof(line), fd) != NULL)
1024 if ((p = strchr(line, '\n')) != NULL) {
1029 * if first chr is '@', check group membership
1031 if (line[0] == '@') {
1035 if ((grp = getgrnam(line+1)) == NULL)
1038 * Check user's default group
1040 if (pwset && grp->gr_gid == pw->pw_gid)
1043 * Check supplementary groups
1045 while (!found && grp->gr_mem[i])
1046 found = strcmp(name,
1051 * Otherwise, just check for username match
1054 found = strcmp(line, name) == 0;
1062 * Terminate login as previous user, if any, resetting state;
1063 * used when USER command is given or login fails.
1072 (void) seteuid((uid_t)0);
1074 ftpd_logwtmp(ttyline, "", NULL);
1077 setusercontext(NULL, getpwuid(0), (uid_t)0,
1078 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1081 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1082 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1083 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1084 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1085 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1086 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1097 * the following code is stolen from imap-uw PAM authentication module and
1100 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1103 const char *uname; /* user name */
1104 const char *pass; /* password */
1106 typedef struct cred_t cred_t;
1109 auth_conv(int num_msg, const struct pam_message **msg,
1110 struct pam_response **resp, void *appdata)
1113 cred_t *cred = (cred_t *) appdata;
1114 struct pam_response *reply;
1116 reply = calloc(num_msg, sizeof *reply);
1120 for (i = 0; i < num_msg; i++) {
1121 switch (msg[i]->msg_style) {
1122 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1123 reply[i].resp_retcode = PAM_SUCCESS;
1124 reply[i].resp = COPY_STRING(cred->uname);
1125 /* PAM frees resp. */
1127 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1128 reply[i].resp_retcode = PAM_SUCCESS;
1129 reply[i].resp = COPY_STRING(cred->pass);
1130 /* PAM frees resp. */
1134 reply[i].resp_retcode = PAM_SUCCESS;
1135 reply[i].resp = NULL;
1137 default: /* unknown message style */
1139 return PAM_CONV_ERR;
1148 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1149 * authenticated, or 1 if not authenticated. If some sort of PAM system
1150 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1151 * function returns -1. This can be used as an indication that we should
1152 * fall back to a different authentication mechanism.
1155 auth_pam(struct passwd **ppw, const char *pass)
1157 pam_handle_t *pamh = NULL;
1158 const char *tmpl_user;
1162 cred_t auth_cred = { (*ppw)->pw_name, pass };
1163 struct pam_conv conv = { &auth_conv, &auth_cred };
1165 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1166 if (e != PAM_SUCCESS) {
1167 syslog(LOG_ERR, "pam_start: %s", pam_strerror(pamh, e));
1171 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1172 if (e != PAM_SUCCESS) {
1173 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1174 pam_strerror(pamh, e));
1178 e = pam_authenticate(pamh, 0);
1182 * With PAM we support the concept of a "template"
1183 * user. The user enters a login name which is
1184 * authenticated by PAM, usually via a remote service
1185 * such as RADIUS or TACACS+. If authentication
1186 * succeeds, a different but related "template" name
1187 * is used for setting the credentials, shell, and
1188 * home directory. The name the user enters need only
1189 * exist on the remote authentication server, but the
1190 * template name must be present in the local password
1193 * This is supported by two various mechanisms in the
1194 * individual modules. However, from the application's
1195 * point of view, the template user is always passed
1196 * back as a changed value of the PAM_USER item.
1198 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1200 tmpl_user = (const char *) item;
1201 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1202 *ppw = getpwnam(tmpl_user);
1204 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1205 pam_strerror(pamh, e));
1210 case PAM_USER_UNKNOWN:
1216 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1222 e = pam_acct_mgmt(pamh, 0);
1223 if (e == PAM_NEW_AUTHTOK_REQD) {
1224 e = pam_chauthtok(pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
1225 if (e != PAM_SUCCESS) {
1226 syslog(LOG_ERR, "pam_chauthtok: %s", pam_strerror(pamh, e));
1229 } else if (e != PAM_SUCCESS) {
1235 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1236 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1243 #endif /* USE_PAM */
1251 login_cap_t *lc = NULL;
1258 if (logged_in || askpasswd == 0) {
1259 reply(503, "Login with USER first.");
1263 if (!guest) { /* "ftp" is only account allowed no password */
1265 rval = 1; /* failure below */
1269 rval = auth_pam(&pw, passwd);
1275 if (opieverify(&opiedata, passwd) == 0)
1276 xpasswd = pw->pw_passwd;
1278 xpasswd = crypt(passwd, pw->pw_passwd);
1279 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1285 rval = strcmp(pw->pw_passwd, xpasswd);
1286 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1287 rval = 1; /* failure */
1290 * If rval == 1, the user failed the authentication check
1291 * above. If rval == 0, either PAM or local authentication
1295 reply(530, "Login incorrect.");
1298 "FTP LOGIN FAILED FROM %s, %s",
1299 remotehost, curname);
1301 if (login_attempts++ >= 5) {
1303 "repeated login failures from %s",
1310 login_attempts = 0; /* this time successful */
1311 if (setegid((gid_t)pw->pw_gid) < 0) {
1312 reply(550, "Can't set gid.");
1315 /* May be overridden by login.conf */
1316 (void) umask(defumask);
1318 if ((lc = login_getpwclass(pw)) != NULL) {
1319 char remote_ip[MAXHOSTNAMELEN];
1321 getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1322 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1323 NI_NUMERICHOST|NI_WITHSCOPEID);
1324 remote_ip[sizeof(remote_ip) - 1] = 0;
1325 if (!auth_hostok(lc, remotehost, remote_ip)) {
1326 syslog(LOG_INFO|LOG_AUTH,
1327 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1329 reply(530, "Permission denied.\n");
1333 if (!auth_timeok(lc, time(NULL))) {
1334 reply(530, "Login not available right now.\n");
1339 setusercontext(lc, pw, (uid_t)0,
1340 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1341 LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1343 setlogin(pw->pw_name);
1344 (void) initgroups(pw->pw_name, pw->pw_gid);
1349 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1350 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1351 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1352 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1357 /* open wtmp before chroot */
1358 ftpd_logwtmp(ttyline, pw->pw_name, (struct sockaddr *)&his_addr);
1361 if (guest && stats && statfd < 0)
1362 #ifdef VIRTUAL_HOSTING
1363 if ((statfd = open(thishost->statfile, O_WRONLY|O_APPEND)) < 0)
1365 if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0)
1370 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1371 login_getcapbool(lc, "ftp-chroot", 0) ||
1373 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1);
1376 * We MUST do a chdir() after the chroot. Otherwise
1377 * the old current directory will be accessible as "."
1378 * outside the new root!
1380 if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
1381 reply(550, "Can't set guest privileges.");
1384 } else if (dochroot) {
1385 if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
1386 reply(550, "Can't change root.");
1389 } else if (chdir(pw->pw_dir) < 0) {
1390 if (chdir("/") < 0) {
1391 reply(530, "User %s: can't change directory to %s.",
1392 pw->pw_name, pw->pw_dir);
1395 lreply(230, "No directory! Logging in with home=/");
1397 if (seteuid((uid_t)pw->pw_uid) < 0) {
1398 reply(550, "Can't set uid.");
1403 * Display a login message, if it exists.
1404 * N.B. reply(230,) must follow the message.
1406 #ifdef VIRTUAL_HOSTING
1407 if ((fd = fopen(thishost->loginmsg, "r")) != NULL) {
1409 if ((fd = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) {
1411 char *cp, line[LINE_MAX];
1413 while (fgets(line, sizeof(line), fd) != NULL) {
1414 if ((cp = strchr(line, '\n')) != NULL)
1416 lreply(230, "%s", line);
1418 (void) fflush(stdout);
1424 ident = strdup(passwd);
1426 fatalerror("Ran out of memory.");
1428 reply(230, "Guest login ok, access restrictions apply.");
1430 #ifdef VIRTUAL_HOSTING
1431 if (thishost != firsthost)
1432 snprintf(proctitle, sizeof(proctitle),
1433 "%s: anonymous(%s)/%s", remotehost, hostname,
1437 snprintf(proctitle, sizeof(proctitle),
1438 "%s: anonymous/%s", remotehost, passwd);
1439 setproctitle("%s", proctitle);
1440 #endif /* SETPROCTITLE */
1442 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1443 remotehost, passwd);
1446 reply(230, "User %s logged in, "
1447 "access restrictions apply.", pw->pw_name);
1449 reply(230, "User %s logged in.", pw->pw_name);
1452 snprintf(proctitle, sizeof(proctitle),
1453 "%s: user/%s", remotehost, pw->pw_name);
1454 setproctitle("%s", proctitle);
1455 #endif /* SETPROCTITLE */
1457 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1458 remotehost, pw->pw_name);
1465 /* Forget all about it... */
1473 retrieve(char *cmd, char *name)
1477 int (*closefunc)(FILE *);
1481 fin = fopen(name, "r"), closefunc = fclose;
1486 (void) snprintf(line, sizeof(line), cmd, name), name = line;
1487 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1489 st.st_blksize = BUFSIZ;
1493 perror_reply(550, name);
1495 LOGCMD("get", name);
1501 if (cmd == 0 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
1502 reply(550, "%s: not a plain file.", name);
1505 if (restart_point) {
1506 if (type == TYPE_A) {
1513 if ((c=getc(fin)) == EOF) {
1514 perror_reply(550, name);
1520 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1521 perror_reply(550, name);
1525 dout = dataconn(name, st.st_size, "w");
1529 send_data(fin, dout, st.st_blksize, st.st_size,
1530 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1531 if (cmd == 0 && guest && stats)
1532 logxfer(name, st.st_size, start);
1533 (void) fclose(dout);
1538 LOGBYTES("get", name, byte_count);
1543 store(char *name, char *mode, int unique)
1547 int (*closefunc)(FILE *);
1549 if ((unique || guest) && stat(name, &st) == 0 &&
1550 (name = gunique(name)) == NULL) {
1551 LOGCMD(*mode == 'w' ? "put" : "append", name);
1557 fout = fopen(name, mode);
1560 perror_reply(553, name);
1561 LOGCMD(*mode == 'w' ? "put" : "append", name);
1565 if (restart_point) {
1566 if (type == TYPE_A) {
1573 if ((c=getc(fout)) == EOF) {
1574 perror_reply(550, name);
1581 * We must do this seek to "current" position
1582 * because we are changing from reading to
1585 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1586 perror_reply(550, name);
1589 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1590 perror_reply(550, name);
1594 din = dataconn(name, (off_t)-1, "r");
1597 if (receive_data(din, fout) == 0) {
1599 reply(226, "Transfer complete (unique file name:%s).",
1602 reply(226, "Transfer complete.");
1608 LOGBYTES(*mode == 'w' ? "put" : "append", name, byte_count);
1613 getdatasock(char *mode)
1615 int on = 1, s, t, tries;
1618 return (fdopen(data, mode));
1619 (void) seteuid((uid_t)0);
1621 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1624 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
1625 (char *) &on, sizeof(on)) < 0)
1627 /* anchor socket to avoid multi-homing problems */
1628 data_source = ctrl_addr;
1629 data_source.su_port = htons(20); /* ftp-data port */
1630 for (tries = 1; ; tries++) {
1631 if (bind(s, (struct sockaddr *)&data_source,
1632 data_source.su_len) >= 0)
1634 if (errno != EADDRINUSE || tries > 10)
1638 (void) seteuid((uid_t)pw->pw_uid);
1640 if (data_source.su_family == AF_INET)
1642 on = IPTOS_THROUGHPUT;
1643 if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on, sizeof(int)) < 0)
1644 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
1649 * Turn off push flag to keep sender TCP from sending short packets
1650 * at the boundaries of each write(). Should probably do a SO_SNDBUF
1651 * to set the send buffer size as well, but that may not be desirable
1652 * in heavy-load situations.
1655 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, (char *)&on, sizeof on) < 0)
1656 syslog(LOG_WARNING, "setsockopt (TCP_NOPUSH): %m");
1660 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&on, sizeof on) < 0)
1661 syslog(LOG_WARNING, "setsockopt (SO_SNDBUF): %m");
1664 return (fdopen(s, mode));
1666 /* Return the real value of errno (close may change it) */
1668 (void) seteuid((uid_t)pw->pw_uid);
1675 dataconn(char *name, off_t size, char *mode)
1683 if (size != (off_t) -1)
1684 (void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)", size);
1688 union sockunion from;
1690 int s, fromlen = ctrl_addr.su_len;
1691 struct timeval timeout;
1695 FD_SET(pdata, &set);
1697 timeout.tv_usec = 0;
1698 timeout.tv_sec = 120;
1701 * Granted a socket is in the blocking I/O mode,
1702 * accept() will block after a successful select()
1703 * if the selected connection dies in between.
1704 * Therefore set the non-blocking I/O flag here.
1706 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1707 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1709 if (select(pdata+1, &set, (fd_set *) 0, (fd_set *) 0, &timeout) <= 0 ||
1710 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1712 (void) close(pdata);
1715 * Unset the blocking I/O flag on the child socket
1716 * again so stdio can work on it.
1718 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1719 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1722 if (from.su_family == AF_INET)
1724 tos = IPTOS_THROUGHPUT;
1725 (void) setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&tos,
1729 reply(150, "Opening %s mode data connection for '%s'%s.",
1730 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1731 return (fdopen(pdata, mode));
1733 reply(425, "Can't open data connection.");
1734 (void) close(pdata);
1739 reply(125, "Using existing data connection for '%s'%s.",
1742 return (fdopen(data, mode));
1745 data_dest = his_addr;
1747 file = getdatasock(mode);
1749 char hostbuf[BUFSIZ], portbuf[BUFSIZ];
1750 getnameinfo((struct sockaddr *)&data_source,
1751 data_source.su_len, hostbuf, sizeof(hostbuf) - 1,
1752 portbuf, sizeof(portbuf),
1753 NI_NUMERICHOST|NI_NUMERICSERV|NI_WITHSCOPEID);
1754 reply(425, "Can't create data socket (%s,%s): %s.",
1755 hostbuf, portbuf, strerror(errno));
1758 data = fileno(file);
1759 while (connect(data, (struct sockaddr *)&data_dest,
1760 data_dest.su_len) < 0) {
1761 if (errno == EADDRINUSE && retry < swaitmax) {
1762 sleep((unsigned) swaitint);
1766 perror_reply(425, "Can't build data connection");
1767 (void) fclose(file);
1771 reply(150, "Opening %s mode data connection for '%s'%s.",
1772 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1777 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1778 * encapsulation of the data subject to Mode, Structure, and Type.
1780 * NB: Form isn't handled.
1783 send_data(FILE *instr, FILE *outstr, off_t blksize, off_t filesize, int isreg)
1785 int c, filefd, netfd;
1793 while ((c = getc(instr)) != EOF) {
1800 (void) putc('\r', outstr);
1802 (void) putc(c, outstr);
1812 reply(226, "Transfer complete.");
1818 * isreg is only set if we are not doing restart and we
1819 * are sending a regular file
1821 netfd = fileno(outstr);
1822 filefd = fileno(instr);
1829 err = cnt = offset = 0;
1831 while (err != -1 && filesize > 0) {
1832 err = sendfile(filefd, netfd, offset, 0,
1833 (struct sf_hdtr *) NULL, &cnt, 0);
1848 reply(226, "Transfer complete.");
1853 if ((buf = malloc((u_int)blksize)) == NULL) {
1855 perror_reply(451, "Local resource failure: malloc");
1859 while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
1860 write(netfd, buf, cnt) == cnt)
1869 reply(226, "Transfer complete.");
1873 reply(550, "Unimplemented TYPE %d in send_data", type);
1879 perror_reply(426, "Data connection");
1884 perror_reply(551, "Error on input file");
1895 * Transfer data from peer to "outstr" using the appropriate encapulation of
1896 * the data subject to Mode, Structure, and Type.
1898 * N.B.: Form isn't handled.
1901 receive_data(FILE *instr, FILE *outstr)
1914 while ((cnt = read(fileno(instr), buf, sizeof(buf))) > 0) {
1917 if (write(fileno(outstr), buf, cnt) != cnt)
1929 reply(553, "TYPE E not implemented.");
1934 while ((c = getc(instr)) != EOF) {
1943 if ((c = getc(instr)) != '\n') {
1944 (void) putc ('\r', outstr);
1945 if (c == '\0' || c == EOF)
1949 (void) putc(c, outstr);
1962 "WARNING! %d bare linefeeds received in ASCII mode",
1964 (void)printf(" File may not have transferred correctly.\r\n");
1968 reply(550, "Unimplemented TYPE %d in receive_data", type);
1975 perror_reply(426, "Data Connection");
1980 perror_reply(452, "Error writing file");
1991 statfilecmd(char *filename)
1995 char line[LINE_MAX];
1997 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
1998 fin = ftpd_popen(line, "r");
1999 lreply(211, "status of %s:", filename);
2000 while ((c = getc(fin)) != EOF) {
2002 if (ferror(stdout)){
2003 perror_reply(421, "control connection");
2004 (void) ftpd_pclose(fin);
2009 perror_reply(551, filename);
2010 (void) ftpd_pclose(fin);
2013 (void) putc('\r', stdout);
2015 (void) putc(c, stdout);
2017 (void) ftpd_pclose(fin);
2018 reply(211, "End of Status");
2024 union sockunion *su;
2026 char hname[INET6_ADDRSTRLEN];
2029 lreply(211, "%s FTP server status:", hostname, version);
2030 printf(" %s\r\n", version);
2031 printf(" Connected to %s", remotehost);
2032 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2033 hname, sizeof(hname) - 1, NULL, 0,
2034 NI_NUMERICHOST|NI_WITHSCOPEID)) {
2035 if (strcmp(hname, remotehost) != 0)
2036 printf(" (%s)", hname);
2041 printf(" Logged in anonymously\r\n");
2043 printf(" Logged in as %s\r\n", pw->pw_name);
2044 } else if (askpasswd)
2045 printf(" Waiting for password\r\n");
2047 printf(" Waiting for user name\r\n");
2048 printf(" TYPE: %s", typenames[type]);
2049 if (type == TYPE_A || type == TYPE_E)
2050 printf(", FORM: %s", formnames[form]);
2053 printf(" %d", NBBY);
2055 printf(" %d", bytesize); /* need definition! */
2057 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2058 strunames[stru], modenames[mode]);
2060 printf(" Data connection open\r\n");
2061 else if (pdata != -1) {
2065 } else if (usedefault == 0) {
2069 #define UC(b) (((int) b) & 0xff)
2071 printf(" EPSV only mode (EPSV ALL)\r\n");
2076 if (su->su_family == AF_INET) {
2077 a = (u_char *) &su->su_sin.sin_addr;
2078 p = (u_char *) &su->su_sin.sin_port;
2079 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2080 ispassive ? "PASV" : "PORT",
2081 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2082 UC(p[0]), UC(p[1]));
2089 switch (su->su_family) {
2091 a = (u_char *) &su->su_sin.sin_addr;
2092 p = (u_char *) &su->su_sin.sin_port;
2093 alen = sizeof(su->su_sin.sin_addr);
2097 a = (u_char *) &su->su_sin6.sin6_addr;
2098 p = (u_char *) &su->su_sin6.sin6_port;
2099 alen = sizeof(su->su_sin6.sin6_addr);
2107 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2109 for (i = 0; i < alen; i++)
2110 printf("%d,", UC(a[i]));
2111 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2120 switch (su->su_family) {
2132 if (!getnameinfo((struct sockaddr *)su, su->su_len,
2133 hname, sizeof(hname) - 1, NULL, 0,
2135 printf(" %s |%d|%s|%d|\r\n",
2136 ispassive ? "EPSV" : "EPRT",
2137 af, hname, htons(su->su_port));
2143 printf(" No data connection\r\n");
2144 reply(211, "End of status");
2151 reply(451, "Error in server: %s\n", s);
2152 reply(221, "Closing connection due to server error.");
2158 reply(int n, const char *fmt, ...)
2163 (void)printf("%d ", n);
2164 (void)vprintf(fmt, ap);
2165 (void)printf("\r\n");
2166 (void)fflush(stdout);
2168 syslog(LOG_DEBUG, "<--- %d ", n);
2169 vsyslog(LOG_DEBUG, fmt, ap);
2174 lreply(int n, const char *fmt, ...)
2179 (void)printf("%d- ", n);
2180 (void)vprintf(fmt, ap);
2181 (void)printf("\r\n");
2182 (void)fflush(stdout);
2184 syslog(LOG_DEBUG, "<--- %d- ", n);
2185 vsyslog(LOG_DEBUG, fmt, ap);
2193 reply(250, "%s command successful.", s);
2200 reply(502, "%s command not implemented.", s);
2209 if ((cp = strchr(cbuf,'\n')))
2211 reply(500, "'%s': command not understood.", cbuf);
2219 LOGCMD("delete", name);
2220 if (stat(name, &st) < 0) {
2221 perror_reply(550, name);
2224 if ((st.st_mode&S_IFMT) == S_IFDIR) {
2225 if (rmdir(name) < 0) {
2226 perror_reply(550, name);
2231 if (unlink(name) < 0) {
2232 perror_reply(550, name);
2243 if (chdir(path) < 0)
2244 perror_reply(550, path);
2253 LOGCMD("mkdir", name);
2254 if (mkdir(name, 0777) < 0)
2255 perror_reply(550, name);
2257 reply(257, "MKD command successful.");
2261 removedir(char *name)
2264 LOGCMD("rmdir", name);
2265 if (rmdir(name) < 0)
2266 perror_reply(550, name);
2274 char path[MAXPATHLEN + 1];
2276 if (getwd(path) == (char *)NULL)
2277 reply(550, "%s.", path);
2279 reply(257, "\"%s\" is current directory.", path);
2283 renamefrom(char *name)
2287 if (stat(name, &st) < 0) {
2288 perror_reply(550, name);
2291 reply(350, "File exists, ready for destination name");
2296 renamecmd(char *from, char *to)
2300 LOGCMD2("rename", from, to);
2302 if (guest && (stat(to, &st) == 0)) {
2303 reply(550, "%s: permission denied", to);
2307 if (rename(from, to) < 0)
2308 perror_reply(550, "rename");
2314 dolog(struct sockaddr *who)
2318 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2321 #ifdef VIRTUAL_HOSTING
2322 if (thishost != firsthost)
2323 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2324 remotehost, hostname);
2327 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2329 setproctitle("%s", proctitle);
2330 #endif /* SETPROCTITLE */
2333 #ifdef VIRTUAL_HOSTING
2334 if (thishost != firsthost)
2335 syslog(LOG_INFO, "connection from %s (to %s)",
2336 remotehost, hostname);
2340 char who_name[MAXHOSTNAMELEN];
2342 error = getnameinfo(who, who->sa_len,
2343 who_name, sizeof(who_name) - 1,
2345 NI_NUMERICHOST|NI_WITHSCOPEID);
2346 syslog(LOG_INFO, "connection from %s (%s)", remotehost,
2347 error == 0 ? who_name : "");
2353 * Record logout in wtmp file
2354 * and exit with supplied status.
2357 dologout(int status)
2360 * Prevent reception of SIGURG from resulting in a resumption
2361 * back to the main program loop.
2366 (void) seteuid((uid_t)0);
2367 ftpd_logwtmp(ttyline, "", NULL);
2369 /* beware of flushing buffers after a SIGPIPE */
2385 /* only process if transfer occurring */
2389 if (getline(cp, 7, stdin) == NULL) {
2390 reply(221, "You could at least say goodbye.");
2394 if (strcmp(cp, "ABOR\r\n") == 0) {
2396 reply(426, "Transfer aborted. Data connection closed.");
2397 reply(226, "Abort successful");
2399 if (strcmp(cp, "STAT\r\n") == 0) {
2401 if (file_size != (off_t) -1)
2402 reply(213, "Status: %qd of %qd bytes transferred",
2403 byte_count, file_size);
2405 reply(213, "Status: %qd bytes transferred", byte_count);
2410 * Note: a response of 425 is not mentioned as a possible response to
2411 * the PASV command in RFC959. However, it has been blessed as
2412 * a legitimate response by Jon Postel in a telephone conversation
2413 * with Rick Adams on 25 Jan 89.
2421 if (pdata >= 0) /* close old port if one set */
2424 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2426 perror_reply(425, "Can't open passive connection");
2430 (void) seteuid((uid_t)0);
2433 if (ctrl_addr.su_family == AF_INET) {
2434 int on = restricted_data_ports ? IP_PORTRANGE_HIGH
2435 : IP_PORTRANGE_DEFAULT;
2437 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2438 (char *)&on, sizeof(on)) < 0)
2442 #ifdef IPV6_PORTRANGE
2443 if (ctrl_addr.su_family == AF_INET6) {
2444 int on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2445 : IPV6_PORTRANGE_DEFAULT;
2447 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2448 (char *)&on, sizeof(on)) < 0)
2453 pasv_addr = ctrl_addr;
2454 pasv_addr.su_port = 0;
2455 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2458 (void) seteuid((uid_t)pw->pw_uid);
2460 len = sizeof(pasv_addr);
2461 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2463 if (listen(pdata, 1) < 0)
2465 if (pasv_addr.su_family == AF_INET)
2466 a = (char *) &pasv_addr.su_sin.sin_addr;
2467 else if (pasv_addr.su_family == AF_INET6 &&
2468 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2469 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2473 p = (char *) &pasv_addr.su_port;
2475 #define UC(b) (((int) b) & 0xff)
2477 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2478 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2482 (void) seteuid((uid_t)pw->pw_uid);
2483 (void) close(pdata);
2485 perror_reply(425, "Can't open passive connection");
2490 * Long Passive defined in RFC 1639.
2491 * 228 Entering Long Passive Mode
2492 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2496 long_passive(char *cmd, int pf)
2501 if (pdata >= 0) /* close old port if one set */
2504 if (pf != PF_UNSPEC) {
2505 if (ctrl_addr.su_family != pf) {
2506 switch (ctrl_addr.su_family) {
2519 * only EPRT/EPSV ready clients will understand this
2521 if (strcmp(cmd, "EPSV") == 0 && pf) {
2522 reply(522, "Network protocol mismatch, "
2525 reply(501, "Network protocol mismatch"); /*XXX*/
2531 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2533 perror_reply(425, "Can't open passive connection");
2537 (void) seteuid((uid_t)0);
2539 pasv_addr = ctrl_addr;
2540 pasv_addr.su_port = 0;
2541 len = pasv_addr.su_len;
2544 if (ctrl_addr.su_family == AF_INET) {
2545 int on = restricted_data_ports ? IP_PORTRANGE_HIGH
2546 : IP_PORTRANGE_DEFAULT;
2548 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2549 (char *)&on, sizeof(on)) < 0)
2553 #ifdef IPV6_PORTRANGE
2554 if (ctrl_addr.su_family == AF_INET6) {
2555 int on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2556 : IPV6_PORTRANGE_DEFAULT;
2558 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2559 (char *)&on, sizeof(on)) < 0)
2564 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2567 (void) seteuid((uid_t)pw->pw_uid);
2569 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2571 if (listen(pdata, 1) < 0)
2574 #define UC(b) (((int) b) & 0xff)
2576 if (strcmp(cmd, "LPSV") == 0) {
2577 p = (char *)&pasv_addr.su_port;
2578 switch (pasv_addr.su_family) {
2580 a = (char *) &pasv_addr.su_sin.sin_addr;
2583 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2584 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2585 2, UC(p[0]), UC(p[1]));
2588 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
2589 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2592 a = (char *) &pasv_addr.su_sin6.sin6_addr;
2594 "Entering Long Passive Mode "
2595 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2596 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2597 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2598 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2599 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2600 2, UC(p[0]), UC(p[1]));
2603 } else if (strcmp(cmd, "EPSV") == 0) {
2604 switch (pasv_addr.su_family) {
2607 reply(229, "Entering Extended Passive Mode (|||%d|)",
2608 ntohs(pasv_addr.su_port));
2612 /* more proper error code? */
2616 (void) seteuid((uid_t)pw->pw_uid);
2617 (void) close(pdata);
2619 perror_reply(425, "Can't open passive connection");
2624 * Generate unique name for file with basename "local".
2625 * The file named "local" is already known to exist.
2626 * Generates failure reply on error.
2629 gunique(char *local)
2631 static char new[MAXPATHLEN];
2636 cp = strrchr(local, '/');
2639 if (stat(cp ? local : ".", &st) < 0) {
2640 perror_reply(553, cp ? local : ".");
2641 return ((char *) 0);
2645 /* -4 is for the .nn<null> we put on the end below */
2646 (void) snprintf(new, sizeof(new) - 4, "%s", local);
2647 cp = new + strlen(new);
2649 for (count = 1; count < 100; count++) {
2650 (void)sprintf(cp, "%d", count);
2651 if (stat(new, &st) < 0)
2654 reply(452, "Unique file name cannot be created.");
2659 * Format and send reply containing system error number.
2662 perror_reply(int code, char *string)
2665 reply(code, "%s: %s.", string, strerror(errno));
2668 static char *onefile[] = {
2674 send_file_list(char *whichf)
2680 char **dirlist, *dirname;
2685 if (strpbrk(whichf, "~{[*?") != NULL) {
2686 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
2688 memset(&gl, 0, sizeof(gl));
2689 gl.gl_matchc = MAXGLOBARGS;
2690 flags |= GLOB_LIMIT;
2692 if (glob(whichf, flags, 0, &gl)) {
2693 reply(550, "not found");
2695 } else if (gl.gl_pathc == 0) {
2697 perror_reply(550, whichf);
2700 dirlist = gl.gl_pathv;
2702 onefile[0] = whichf;
2707 while ((dirname = *dirlist++)) {
2708 if (stat(dirname, &st) < 0) {
2710 * If user typed "ls -l", etc, and the client
2711 * used NLST, do what the user meant.
2713 if (dirname[0] == '-' && *dirlist == NULL &&
2715 retrieve(_PATH_LS " %s", dirname);
2718 perror_reply(550, whichf);
2720 (void) fclose(dout);
2728 if (S_ISREG(st.st_mode)) {
2730 dout = dataconn("file list", (off_t)-1, "w");
2735 fprintf(dout, "%s%s\n", dirname,
2736 type == TYPE_A ? "\r" : "");
2737 byte_count += strlen(dirname) + 1;
2739 } else if (!S_ISDIR(st.st_mode))
2742 if ((dirp = opendir(dirname)) == NULL)
2745 while ((dir = readdir(dirp)) != NULL) {
2746 char nbuf[MAXPATHLEN];
2755 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
2757 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
2761 snprintf(nbuf, sizeof(nbuf),
2762 "%s/%s", dirname, dir->d_name);
2765 * We have to do a stat to insure it's
2766 * not a directory or special file.
2768 if (simple || (stat(nbuf, &st) == 0 &&
2769 S_ISREG(st.st_mode))) {
2771 dout = dataconn("file list", (off_t)-1,
2777 if (nbuf[0] == '.' && nbuf[1] == '/')
2778 fprintf(dout, "%s%s\n", &nbuf[2],
2779 type == TYPE_A ? "\r" : "");
2781 fprintf(dout, "%s%s\n", nbuf,
2782 type == TYPE_A ? "\r" : "");
2783 byte_count += strlen(nbuf) + 1;
2786 (void) closedir(dirp);
2790 reply(550, "No files found.");
2791 else if (ferror(dout) != 0)
2792 perror_reply(550, "Data connection");
2794 reply(226, "Transfer complete.");
2798 (void) fclose(dout);
2809 reapchild(int signo)
2811 while (wait3(NULL, WNOHANG, NULL) > 0);
2814 #ifdef OLD_SETPROCTITLE
2816 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.)
2817 * Warning, since this is usually started from inetd.conf, it often doesn't
2818 * have much of an environment or arglist to overwrite.
2821 setproctitle(const char *fmt, ...)
2829 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
2831 /* make ps print our process name */
2836 if (i > LastArgv - p - 2) {
2837 i = LastArgv - p - 2;
2842 if (ch != '\n' && ch != '\r')
2844 while (p < LastArgv)
2847 #endif /* OLD_SETPROCTITLE */
2850 logxfer(char *name, off_t size, time_t start)
2853 char path[MAXPATHLEN + 1];
2856 if (statfd >= 0 && getwd(path) != NULL) {
2858 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s/%s!%qd!%ld\n",
2859 ctime(&now)+4, ident, remotehost,
2860 path, name, (long long)size,
2861 (long)(now - start + (now == start)));
2862 write(statfd, buf, strlen(buf));