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)
656 struct ftphost *hrp, *lhrp;
658 struct addrinfo hints, *res, *ai;
661 * Fill in the default host information
663 if (gethostname(line, sizeof(line)) < 0)
665 if ((hrp = malloc(sizeof(struct ftphost))) == NULL ||
666 (hrp->hostname = strdup(line)) == NULL)
667 fatalerror("Ran out of memory.");
668 hrp->hostinfo = NULL;
670 memset(&hints, 0, sizeof(hints));
671 hints.ai_flags = AI_CANONNAME;
672 hints.ai_family = AF_UNSPEC;
673 getaddrinfo(hrp->hostname, NULL, &hints, &res);
676 hrp->statfile = _PATH_FTPDSTATFILE;
677 hrp->welcome = _PATH_FTPWELCOME;
678 hrp->loginmsg = _PATH_FTPLOGINMESG;
679 hrp->anonuser = "ftp";
681 thishost = firsthost = lhrp = hrp;
682 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
683 int addrsize, error, gothost;
687 while (fgets(line, sizeof(line), fp) != NULL) {
690 if ((cp = strchr(line, '\n')) == NULL) {
691 /* ignore long lines */
692 while (fgets(line, sizeof(line), fp) != NULL &&
693 strchr(line, '\n') == NULL)
698 cp = strtok(line, " \t");
699 /* skip comments and empty lines */
700 if (cp == NULL || line[0] == '#')
704 hints.ai_family = AF_UNSPEC;
705 hints.ai_flags = AI_PASSIVE;
706 error = getaddrinfo(cp, NULL, &hints, &res);
709 for (ai = res; ai != NULL && ai->ai_addr != NULL;
713 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
716 for (hi = hrp->hostinfo; hi != NULL;
718 if (hi->ai_addrlen == ai->ai_addrlen &&
721 ai->ai_addr->sa_len) == 0) {
729 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
732 hrp->statfile = _PATH_FTPDSTATFILE;
733 hrp->welcome = _PATH_FTPWELCOME;
734 hrp->loginmsg = _PATH_FTPLOGINMESG;
735 hrp->anonuser = "ftp";
743 * determine hostname to use.
744 * force defined name if there is a valid alias
745 * otherwise fallback to primary hostname
747 /* XXX: getaddrinfo() can't do alias check */
748 switch(hrp->hostinfo->ai_family) {
750 addr = &((struct sockaddr_in *)&hrp->hostinfo->ai_addr)->sin_addr;
751 addrsize = sizeof(struct sockaddr_in);
754 addr = &((struct sockaddr_in6 *)&hrp->hostinfo->ai_addr)->sin6_addr;
755 addrsize = sizeof(struct sockaddr_in6);
758 /* should not reach here */
759 if (hrp->hostinfo != NULL)
760 freeaddrinfo(hrp->hostinfo);
765 if ((hp = getipnodebyaddr((char*)addr, addrsize,
766 hrp->hostinfo->ai_family,
767 &hp_error)) != NULL) {
768 if (strcmp(cp, hp->h_name) != 0) {
769 if (hp->h_aliases == NULL)
773 while (hp->h_aliases[i] &&
774 strcmp(cp, hp->h_aliases[i]) != 0)
776 if (hp->h_aliases[i] == NULL)
781 hrp->hostname = strdup(cp);
783 /* ok, now we now peel off the rest */
785 while (i < 4 && (cp = strtok(NULL, " \t")) != NULL) {
786 if (*cp != '-' && (cp = strdup(cp)) != NULL) {
788 case 0: /* anon user permissions */
791 case 1: /* statistics file */
794 case 2: /* welcome message */
797 case 3: /* login message */
804 /* XXX: re-initialization for getaddrinfo() loop */
805 cp = strtok(line, " \t");
813 selecthost(union sockunion *su)
818 struct in6_addr *mapped_in6 = NULL;
824 * XXX IPv4 mapped IPv6 addr consideraton,
825 * specified in rfc2373.
827 if (su->su_family == AF_INET6 &&
828 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
829 mapped_in6 = &su->su_sin6.sin6_addr;
832 hrp = thishost = firsthost; /* default */
835 while (hrp != NULL) {
836 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
837 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
842 /* XXX IPv4 mapped IPv6 addr consideraton */
843 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
844 (memcmp(&mapped_in6->s6_addr[12],
845 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
846 sizeof(struct in_addr)) == 0)) {
855 /* setup static variables as appropriate */
856 hostname = thishost->hostname;
857 ftpuser = thishost->anonuser;
862 * Helper function for sgetpwnam().
867 char *new = malloc((unsigned) strlen(s) + 1);
870 perror_reply(421, "Local resource failure: malloc");
874 (void) strcpy(new, s);
879 * Save the result of a getpwnam. Used for USER command, since
880 * the data returned must not be clobbered by any other command
883 static struct passwd *
884 sgetpwnam(char *name)
886 static struct passwd save;
889 if ((p = getpwnam(name)) == NULL)
893 free(save.pw_passwd);
899 save.pw_name = sgetsave(p->pw_name);
900 save.pw_passwd = sgetsave(p->pw_passwd);
901 save.pw_gecos = sgetsave(p->pw_gecos);
902 save.pw_dir = sgetsave(p->pw_dir);
903 save.pw_shell = sgetsave(p->pw_shell);
907 static int login_attempts; /* number of failed login attempts */
908 static int askpasswd; /* had user command, ask for passwd */
909 static char curname[MAXLOGNAME]; /* current USER name */
913 * Sets global passwd pointer pw if named account exists and is acceptable;
914 * sets askpasswd if a PASS command is expected. If logged in previously,
915 * need to reset state. If name is "ftp" or "anonymous", the name is not in
916 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
917 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
918 * requesting login privileges. Disallow anyone who does not have a standard
919 * shell as returned by getusershell(). Disallow anyone mentioned in the file
920 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
929 reply(530, "Can't change user from guest login.");
931 } else if (dochroot) {
932 reply(530, "Can't change user from chroot user.");
939 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
940 if (checkuser(_PATH_FTPUSERS, "ftp", 0) ||
941 checkuser(_PATH_FTPUSERS, "anonymous", 0))
942 reply(530, "User %s access denied.", name);
943 #ifdef VIRTUAL_HOSTING
944 else if ((pw = sgetpwnam(thishost->anonuser)) != NULL) {
946 else if ((pw = sgetpwnam("ftp")) != NULL) {
951 "Guest login ok, send your email address as password.");
953 reply(530, "User %s unknown.", name);
954 if (!askpasswd && logging)
956 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
959 if (anon_only != 0) {
960 reply(530, "Sorry, only anonymous ftp allowed.");
964 if ((pw = sgetpwnam(name))) {
965 if ((shell = pw->pw_shell) == NULL || *shell == 0)
966 shell = _PATH_BSHELL;
967 while ((cp = getusershell()) != NULL)
968 if (strcmp(cp, shell) == 0)
972 if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1)) {
973 reply(530, "User %s access denied.", name);
976 "FTP LOGIN REFUSED FROM %s, %s",
978 pw = (struct passwd *) NULL;
983 strncpy(curname, name, sizeof(curname)-1);
987 /* XXX Kluge! The conversation mechanism needs to be fixed. */
989 if (opiechallenge(&opiedata, name, opieprompt) == 0) {
990 pwok = (pw != NULL) &&
991 opieaccessfile(remotehost) &&
992 opiealways(pw->pw_dir);
993 reply(331, "Response to %s %s for %s.",
994 opieprompt, pwok ? "requested" : "required", name);
997 reply(331, "Password required for %s.", name);
1001 * Delay before reading passwd after first failed
1002 * attempt to slow down passwd-guessing programs.
1005 sleep((unsigned) login_attempts);
1009 * Check if a user is in the file "fname"
1012 checkuser(char *fname, char *name, int pwset)
1016 char *p, line[BUFSIZ];
1018 if ((fd = fopen(fname, "r")) != NULL) {
1019 while (!found && fgets(line, sizeof(line), fd) != NULL)
1020 if ((p = strchr(line, '\n')) != NULL) {
1025 * if first chr is '@', check group membership
1027 if (line[0] == '@') {
1031 if ((grp = getgrnam(line+1)) == NULL)
1034 * Check user's default group
1036 if (pwset && grp->gr_gid == pw->pw_gid)
1039 * Check supplementary groups
1041 while (!found && grp->gr_mem[i])
1042 found = strcmp(name,
1047 * Otherwise, just check for username match
1050 found = strcmp(line, name) == 0;
1058 * Terminate login as previous user, if any, resetting state;
1059 * used when USER command is given or login fails.
1068 (void) seteuid((uid_t)0);
1070 ftpd_logwtmp(ttyline, "", NULL);
1073 setusercontext(NULL, getpwuid(0), (uid_t)0,
1074 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1077 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1078 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1079 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1080 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1081 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1082 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1093 * the following code is stolen from imap-uw PAM authentication module and
1096 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1099 const char *uname; /* user name */
1100 const char *pass; /* password */
1102 typedef struct cred_t cred_t;
1105 auth_conv(int num_msg, const struct pam_message **msg,
1106 struct pam_response **resp, void *appdata)
1109 cred_t *cred = (cred_t *) appdata;
1110 struct pam_response *reply;
1112 reply = calloc(num_msg, sizeof *reply);
1116 for (i = 0; i < num_msg; i++) {
1117 switch (msg[i]->msg_style) {
1118 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1119 reply[i].resp_retcode = PAM_SUCCESS;
1120 reply[i].resp = COPY_STRING(cred->uname);
1121 /* PAM frees resp. */
1123 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1124 reply[i].resp_retcode = PAM_SUCCESS;
1125 reply[i].resp = COPY_STRING(cred->pass);
1126 /* PAM frees resp. */
1130 reply[i].resp_retcode = PAM_SUCCESS;
1131 reply[i].resp = NULL;
1133 default: /* unknown message style */
1135 return PAM_CONV_ERR;
1144 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1145 * authenticated, or 1 if not authenticated. If some sort of PAM system
1146 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1147 * function returns -1. This can be used as an indication that we should
1148 * fall back to a different authentication mechanism.
1151 auth_pam(struct passwd **ppw, const char *pass)
1153 pam_handle_t *pamh = NULL;
1154 const char *tmpl_user;
1158 cred_t auth_cred = { (*ppw)->pw_name, pass };
1159 struct pam_conv conv = { &auth_conv, &auth_cred };
1161 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1162 if (e != PAM_SUCCESS) {
1163 syslog(LOG_ERR, "pam_start: %s", pam_strerror(pamh, e));
1167 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1168 if (e != PAM_SUCCESS) {
1169 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1170 pam_strerror(pamh, e));
1174 e = pam_authenticate(pamh, 0);
1178 * With PAM we support the concept of a "template"
1179 * user. The user enters a login name which is
1180 * authenticated by PAM, usually via a remote service
1181 * such as RADIUS or TACACS+. If authentication
1182 * succeeds, a different but related "template" name
1183 * is used for setting the credentials, shell, and
1184 * home directory. The name the user enters need only
1185 * exist on the remote authentication server, but the
1186 * template name must be present in the local password
1189 * This is supported by two various mechanisms in the
1190 * individual modules. However, from the application's
1191 * point of view, the template user is always passed
1192 * back as a changed value of the PAM_USER item.
1194 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1196 tmpl_user = (const char *) item;
1197 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1198 *ppw = getpwnam(tmpl_user);
1200 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1201 pam_strerror(pamh, e));
1206 case PAM_USER_UNKNOWN:
1212 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1218 e = pam_acct_mgmt(pamh, 0);
1219 if (e == PAM_NEW_AUTHTOK_REQD) {
1220 e = pam_chauthtok(pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
1221 if (e != PAM_SUCCESS) {
1222 syslog(LOG_ERR, "pam_chauthtok: %s", pam_strerror(pamh, e));
1225 } else if (e != PAM_SUCCESS) {
1231 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1232 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1239 #endif /* USE_PAM */
1247 login_cap_t *lc = NULL;
1254 if (logged_in || askpasswd == 0) {
1255 reply(503, "Login with USER first.");
1259 if (!guest) { /* "ftp" is only account allowed no password */
1261 rval = 1; /* failure below */
1265 rval = auth_pam(&pw, passwd);
1271 if (opieverify(&opiedata, passwd) == 0)
1272 xpasswd = pw->pw_passwd;
1274 xpasswd = crypt(passwd, pw->pw_passwd);
1275 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1281 rval = strcmp(pw->pw_passwd, xpasswd);
1282 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1283 rval = 1; /* failure */
1286 * If rval == 1, the user failed the authentication check
1287 * above. If rval == 0, either PAM or local authentication
1291 reply(530, "Login incorrect.");
1294 "FTP LOGIN FAILED FROM %s, %s",
1295 remotehost, curname);
1297 if (login_attempts++ >= 5) {
1299 "repeated login failures from %s",
1306 login_attempts = 0; /* this time successful */
1307 if (setegid((gid_t)pw->pw_gid) < 0) {
1308 reply(550, "Can't set gid.");
1311 /* May be overridden by login.conf */
1312 (void) umask(defumask);
1314 if ((lc = login_getpwclass(pw)) != NULL) {
1315 char remote_ip[MAXHOSTNAMELEN];
1317 getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1318 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1320 remote_ip[sizeof(remote_ip) - 1] = 0;
1321 if (!auth_hostok(lc, remotehost, remote_ip)) {
1322 syslog(LOG_INFO|LOG_AUTH,
1323 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1325 reply(530, "Permission denied.\n");
1329 if (!auth_timeok(lc, time(NULL))) {
1330 reply(530, "Login not available right now.\n");
1335 setusercontext(lc, pw, (uid_t)0,
1336 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1337 LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1339 setlogin(pw->pw_name);
1340 (void) initgroups(pw->pw_name, pw->pw_gid);
1345 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1346 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1347 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1348 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1353 /* open wtmp before chroot */
1354 ftpd_logwtmp(ttyline, pw->pw_name, (struct sockaddr *)&his_addr);
1357 if (guest && stats && statfd < 0)
1358 #ifdef VIRTUAL_HOSTING
1359 if ((statfd = open(thishost->statfile, O_WRONLY|O_APPEND)) < 0)
1361 if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0)
1366 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1367 login_getcapbool(lc, "ftp-chroot", 0) ||
1369 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1);
1372 * We MUST do a chdir() after the chroot. Otherwise
1373 * the old current directory will be accessible as "."
1374 * outside the new root!
1376 if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
1377 reply(550, "Can't set guest privileges.");
1380 } else if (dochroot) {
1381 if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
1382 reply(550, "Can't change root.");
1385 } else if (chdir(pw->pw_dir) < 0) {
1386 if (chdir("/") < 0) {
1387 reply(530, "User %s: can't change directory to %s.",
1388 pw->pw_name, pw->pw_dir);
1391 lreply(230, "No directory! Logging in with home=/");
1393 if (seteuid((uid_t)pw->pw_uid) < 0) {
1394 reply(550, "Can't set uid.");
1399 * Display a login message, if it exists.
1400 * N.B. reply(230,) must follow the message.
1402 #ifdef VIRTUAL_HOSTING
1403 if ((fd = fopen(thishost->loginmsg, "r")) != NULL) {
1405 if ((fd = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) {
1407 char *cp, line[LINE_MAX];
1409 while (fgets(line, sizeof(line), fd) != NULL) {
1410 if ((cp = strchr(line, '\n')) != NULL)
1412 lreply(230, "%s", line);
1414 (void) fflush(stdout);
1420 ident = strdup(passwd);
1422 fatalerror("Ran out of memory.");
1424 reply(230, "Guest login ok, access restrictions apply.");
1426 #ifdef VIRTUAL_HOSTING
1427 if (thishost != firsthost)
1428 snprintf(proctitle, sizeof(proctitle),
1429 "%s: anonymous(%s)/%s", remotehost, hostname,
1433 snprintf(proctitle, sizeof(proctitle),
1434 "%s: anonymous/%s", remotehost, passwd);
1435 setproctitle("%s", proctitle);
1436 #endif /* SETPROCTITLE */
1438 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1439 remotehost, passwd);
1442 reply(230, "User %s logged in, "
1443 "access restrictions apply.", pw->pw_name);
1445 reply(230, "User %s logged in.", pw->pw_name);
1448 snprintf(proctitle, sizeof(proctitle),
1449 "%s: user/%s", remotehost, pw->pw_name);
1450 setproctitle("%s", proctitle);
1451 #endif /* SETPROCTITLE */
1453 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1454 remotehost, pw->pw_name);
1461 /* Forget all about it... */
1469 retrieve(char *cmd, char *name)
1473 int (*closefunc)(FILE *);
1477 fin = fopen(name, "r"), closefunc = fclose;
1482 (void) snprintf(line, sizeof(line), cmd, name), name = line;
1483 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1485 st.st_blksize = BUFSIZ;
1489 perror_reply(550, name);
1491 LOGCMD("get", name);
1497 if (cmd == 0 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
1498 reply(550, "%s: not a plain file.", name);
1501 if (restart_point) {
1502 if (type == TYPE_A) {
1509 if ((c=getc(fin)) == EOF) {
1510 perror_reply(550, name);
1516 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1517 perror_reply(550, name);
1521 dout = dataconn(name, st.st_size, "w");
1525 send_data(fin, dout, st.st_blksize, st.st_size,
1526 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1527 if (cmd == 0 && guest && stats)
1528 logxfer(name, st.st_size, start);
1529 (void) fclose(dout);
1534 LOGBYTES("get", name, byte_count);
1539 store(char *name, char *mode, int unique)
1543 int (*closefunc)(FILE *);
1545 if ((unique || guest) && stat(name, &st) == 0 &&
1546 (name = gunique(name)) == NULL) {
1547 LOGCMD(*mode == 'w' ? "put" : "append", name);
1553 fout = fopen(name, mode);
1556 perror_reply(553, name);
1557 LOGCMD(*mode == 'w' ? "put" : "append", name);
1561 if (restart_point) {
1562 if (type == TYPE_A) {
1569 if ((c=getc(fout)) == EOF) {
1570 perror_reply(550, name);
1577 * We must do this seek to "current" position
1578 * because we are changing from reading to
1581 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1582 perror_reply(550, name);
1585 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1586 perror_reply(550, name);
1590 din = dataconn(name, (off_t)-1, "r");
1593 if (receive_data(din, fout) == 0) {
1595 reply(226, "Transfer complete (unique file name:%s).",
1598 reply(226, "Transfer complete.");
1604 LOGBYTES(*mode == 'w' ? "put" : "append", name, byte_count);
1609 getdatasock(char *mode)
1611 int on = 1, s, t, tries;
1614 return (fdopen(data, mode));
1615 (void) seteuid((uid_t)0);
1617 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1620 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
1621 (char *) &on, sizeof(on)) < 0)
1623 /* anchor socket to avoid multi-homing problems */
1624 data_source = ctrl_addr;
1625 data_source.su_port = htons(20); /* ftp-data port */
1626 for (tries = 1; ; tries++) {
1627 if (bind(s, (struct sockaddr *)&data_source,
1628 data_source.su_len) >= 0)
1630 if (errno != EADDRINUSE || tries > 10)
1634 (void) seteuid((uid_t)pw->pw_uid);
1636 if (data_source.su_family == AF_INET)
1638 on = IPTOS_THROUGHPUT;
1639 if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on, sizeof(int)) < 0)
1640 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
1645 * Turn off push flag to keep sender TCP from sending short packets
1646 * at the boundaries of each write(). Should probably do a SO_SNDBUF
1647 * to set the send buffer size as well, but that may not be desirable
1648 * in heavy-load situations.
1651 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, (char *)&on, sizeof on) < 0)
1652 syslog(LOG_WARNING, "setsockopt (TCP_NOPUSH): %m");
1656 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&on, sizeof on) < 0)
1657 syslog(LOG_WARNING, "setsockopt (SO_SNDBUF): %m");
1660 return (fdopen(s, mode));
1662 /* Return the real value of errno (close may change it) */
1664 (void) seteuid((uid_t)pw->pw_uid);
1671 dataconn(char *name, off_t size, char *mode)
1679 if (size != (off_t) -1)
1680 (void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)", size);
1684 union sockunion from;
1686 int s, fromlen = ctrl_addr.su_len;
1687 struct timeval timeout;
1691 FD_SET(pdata, &set);
1693 timeout.tv_usec = 0;
1694 timeout.tv_sec = 120;
1697 * Granted a socket is in the blocking I/O mode,
1698 * accept() will block after a successful select()
1699 * if the selected connection dies in between.
1700 * Therefore set the non-blocking I/O flag here.
1702 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1703 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1705 if (select(pdata+1, &set, (fd_set *) 0, (fd_set *) 0, &timeout) <= 0 ||
1706 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1708 (void) close(pdata);
1711 * Unset the blocking I/O flag on the child socket
1712 * again so stdio can work on it.
1714 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1715 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1718 if (from.su_family == AF_INET)
1720 tos = IPTOS_THROUGHPUT;
1721 (void) setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&tos,
1725 reply(150, "Opening %s mode data connection for '%s'%s.",
1726 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1727 return (fdopen(pdata, mode));
1729 reply(425, "Can't open data connection.");
1730 (void) close(pdata);
1735 reply(125, "Using existing data connection for '%s'%s.",
1738 return (fdopen(data, mode));
1741 data_dest = his_addr;
1743 file = getdatasock(mode);
1745 char hostbuf[BUFSIZ], portbuf[BUFSIZ];
1746 getnameinfo((struct sockaddr *)&data_source,
1747 data_source.su_len, hostbuf, sizeof(hostbuf) - 1,
1748 portbuf, sizeof(portbuf),
1749 NI_NUMERICHOST|NI_NUMERICSERV);
1750 reply(425, "Can't create data socket (%s,%s): %s.",
1751 hostbuf, portbuf, strerror(errno));
1754 data = fileno(file);
1755 while (connect(data, (struct sockaddr *)&data_dest,
1756 data_dest.su_len) < 0) {
1757 if (errno == EADDRINUSE && retry < swaitmax) {
1758 sleep((unsigned) swaitint);
1762 perror_reply(425, "Can't build data connection");
1763 (void) fclose(file);
1767 reply(150, "Opening %s mode data connection for '%s'%s.",
1768 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1773 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1774 * encapsulation of the data subject to Mode, Structure, and Type.
1776 * NB: Form isn't handled.
1779 send_data(FILE *instr, FILE *outstr, off_t blksize, off_t filesize, int isreg)
1781 int c, filefd, netfd;
1789 while ((c = getc(instr)) != EOF) {
1796 (void) putc('\r', outstr);
1798 (void) putc(c, outstr);
1808 reply(226, "Transfer complete.");
1814 * isreg is only set if we are not doing restart and we
1815 * are sending a regular file
1817 netfd = fileno(outstr);
1818 filefd = fileno(instr);
1825 err = cnt = offset = 0;
1827 while (err != -1 && filesize > 0) {
1828 err = sendfile(filefd, netfd, offset, 0,
1829 (struct sf_hdtr *) NULL, &cnt, 0);
1831 * Calculate byte_count before OOB processing.
1832 * It can be used in myoob() later.
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[NI_MAXHOST];
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, NI_NUMERICHOST)) {
2034 if (strcmp(hname, remotehost) != 0)
2035 printf(" (%s)", hname);
2040 printf(" Logged in anonymously\r\n");
2042 printf(" Logged in as %s\r\n", pw->pw_name);
2043 } else if (askpasswd)
2044 printf(" Waiting for password\r\n");
2046 printf(" Waiting for user name\r\n");
2047 printf(" TYPE: %s", typenames[type]);
2048 if (type == TYPE_A || type == TYPE_E)
2049 printf(", FORM: %s", formnames[form]);
2052 printf(" %d", NBBY);
2054 printf(" %d", bytesize); /* need definition! */
2056 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2057 strunames[stru], modenames[mode]);
2059 printf(" Data connection open\r\n");
2060 else if (pdata != -1) {
2064 } else if (usedefault == 0) {
2068 #define UC(b) (((int) b) & 0xff)
2070 printf(" EPSV only mode (EPSV ALL)\r\n");
2075 if (su->su_family == AF_INET) {
2076 a = (u_char *) &su->su_sin.sin_addr;
2077 p = (u_char *) &su->su_sin.sin_port;
2078 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2079 ispassive ? "PASV" : "PORT",
2080 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2081 UC(p[0]), UC(p[1]));
2088 switch (su->su_family) {
2090 a = (u_char *) &su->su_sin.sin_addr;
2091 p = (u_char *) &su->su_sin.sin_port;
2092 alen = sizeof(su->su_sin.sin_addr);
2096 a = (u_char *) &su->su_sin6.sin6_addr;
2097 p = (u_char *) &su->su_sin6.sin6_port;
2098 alen = sizeof(su->su_sin6.sin6_addr);
2106 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2108 for (i = 0; i < alen; i++)
2109 printf("%d,", UC(a[i]));
2110 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2119 switch (su->su_family) {
2131 union sockunion tmp;
2134 if (tmp.su_family == AF_INET6)
2135 tmp.su_sin6.sin6_scope_id = 0;
2136 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2137 hname, sizeof(hname) - 1, NULL, 0,
2139 printf(" %s |%d|%s|%d|\r\n",
2140 ispassive ? "EPSV" : "EPRT",
2141 af, hname, htons(tmp.su_port));
2147 printf(" No data connection\r\n");
2148 reply(211, "End of status");
2155 reply(451, "Error in server: %s\n", s);
2156 reply(221, "Closing connection due to server error.");
2162 reply(int n, const char *fmt, ...)
2167 (void)printf("%d ", n);
2168 (void)vprintf(fmt, ap);
2169 (void)printf("\r\n");
2170 (void)fflush(stdout);
2172 syslog(LOG_DEBUG, "<--- %d ", n);
2173 vsyslog(LOG_DEBUG, fmt, ap);
2178 lreply(int n, const char *fmt, ...)
2183 (void)printf("%d- ", n);
2184 (void)vprintf(fmt, ap);
2185 (void)printf("\r\n");
2186 (void)fflush(stdout);
2188 syslog(LOG_DEBUG, "<--- %d- ", n);
2189 vsyslog(LOG_DEBUG, fmt, ap);
2197 reply(250, "%s command successful.", s);
2204 reply(502, "%s command not implemented.", s);
2213 if ((cp = strchr(cbuf,'\n')))
2215 reply(500, "'%s': command not understood.", cbuf);
2223 LOGCMD("delete", name);
2224 if (stat(name, &st) < 0) {
2225 perror_reply(550, name);
2228 if ((st.st_mode&S_IFMT) == S_IFDIR) {
2229 if (rmdir(name) < 0) {
2230 perror_reply(550, name);
2235 if (unlink(name) < 0) {
2236 perror_reply(550, name);
2247 if (chdir(path) < 0)
2248 perror_reply(550, path);
2257 LOGCMD("mkdir", name);
2258 if (guest && noguestmkd)
2259 reply(550, "%s: permission denied", name);
2260 else if (mkdir(name, 0777) < 0)
2261 perror_reply(550, name);
2263 reply(257, "MKD command successful.");
2267 removedir(char *name)
2270 LOGCMD("rmdir", name);
2271 if (rmdir(name) < 0)
2272 perror_reply(550, name);
2280 char path[MAXPATHLEN + 1];
2282 if (getwd(path) == (char *)NULL)
2283 reply(550, "%s.", path);
2285 reply(257, "\"%s\" is current directory.", path);
2289 renamefrom(char *name)
2293 if (stat(name, &st) < 0) {
2294 perror_reply(550, name);
2297 reply(350, "File exists, ready for destination name");
2302 renamecmd(char *from, char *to)
2306 LOGCMD2("rename", from, to);
2308 if (guest && (stat(to, &st) == 0)) {
2309 reply(550, "%s: permission denied", to);
2313 if (rename(from, to) < 0)
2314 perror_reply(550, "rename");
2320 dolog(struct sockaddr *who)
2324 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2327 #ifdef VIRTUAL_HOSTING
2328 if (thishost != firsthost)
2329 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2330 remotehost, hostname);
2333 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2335 setproctitle("%s", proctitle);
2336 #endif /* SETPROCTITLE */
2339 #ifdef VIRTUAL_HOSTING
2340 if (thishost != firsthost)
2341 syslog(LOG_INFO, "connection from %s (to %s)",
2342 remotehost, hostname);
2346 char who_name[MAXHOSTNAMELEN];
2348 error = getnameinfo(who, who->sa_len,
2349 who_name, sizeof(who_name) - 1,
2350 NULL, 0, NI_NUMERICHOST);
2351 syslog(LOG_INFO, "connection from %s (%s)", remotehost,
2352 error == 0 ? who_name : "");
2358 * Record logout in wtmp file
2359 * and exit with supplied status.
2362 dologout(int status)
2365 * Prevent reception of SIGURG from resulting in a resumption
2366 * back to the main program loop.
2371 (void) seteuid((uid_t)0);
2372 ftpd_logwtmp(ttyline, "", NULL);
2374 /* beware of flushing buffers after a SIGPIPE */
2390 /* only process if transfer occurring */
2394 if (getline(cp, 7, stdin) == NULL) {
2395 reply(221, "You could at least say goodbye.");
2399 if (strcmp(cp, "ABOR\r\n") == 0) {
2401 reply(426, "Transfer aborted. Data connection closed.");
2402 reply(226, "Abort successful");
2404 if (strcmp(cp, "STAT\r\n") == 0) {
2406 if (file_size != (off_t) -1)
2407 reply(213, "Status: %qd of %qd bytes transferred",
2408 byte_count, file_size);
2410 reply(213, "Status: %qd bytes transferred", byte_count);
2415 * Note: a response of 425 is not mentioned as a possible response to
2416 * the PASV command in RFC959. However, it has been blessed as
2417 * a legitimate response by Jon Postel in a telephone conversation
2418 * with Rick Adams on 25 Jan 89.
2426 if (pdata >= 0) /* close old port if one set */
2429 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2431 perror_reply(425, "Can't open passive connection");
2435 (void) seteuid((uid_t)0);
2438 if (ctrl_addr.su_family == AF_INET) {
2439 int on = restricted_data_ports ? IP_PORTRANGE_HIGH
2440 : IP_PORTRANGE_DEFAULT;
2442 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2443 (char *)&on, sizeof(on)) < 0)
2447 #ifdef IPV6_PORTRANGE
2448 if (ctrl_addr.su_family == AF_INET6) {
2449 int on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2450 : IPV6_PORTRANGE_DEFAULT;
2452 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2453 (char *)&on, sizeof(on)) < 0)
2458 pasv_addr = ctrl_addr;
2459 pasv_addr.su_port = 0;
2460 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2463 (void) seteuid((uid_t)pw->pw_uid);
2465 len = sizeof(pasv_addr);
2466 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2468 if (listen(pdata, 1) < 0)
2470 if (pasv_addr.su_family == AF_INET)
2471 a = (char *) &pasv_addr.su_sin.sin_addr;
2472 else if (pasv_addr.su_family == AF_INET6 &&
2473 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2474 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2478 p = (char *) &pasv_addr.su_port;
2480 #define UC(b) (((int) b) & 0xff)
2482 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2483 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2487 (void) seteuid((uid_t)pw->pw_uid);
2488 (void) close(pdata);
2490 perror_reply(425, "Can't open passive connection");
2495 * Long Passive defined in RFC 1639.
2496 * 228 Entering Long Passive Mode
2497 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2501 long_passive(char *cmd, int pf)
2506 if (pdata >= 0) /* close old port if one set */
2509 if (pf != PF_UNSPEC) {
2510 if (ctrl_addr.su_family != pf) {
2511 switch (ctrl_addr.su_family) {
2524 * only EPRT/EPSV ready clients will understand this
2526 if (strcmp(cmd, "EPSV") == 0 && pf) {
2527 reply(522, "Network protocol mismatch, "
2530 reply(501, "Network protocol mismatch"); /*XXX*/
2536 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2538 perror_reply(425, "Can't open passive connection");
2542 (void) seteuid((uid_t)0);
2544 pasv_addr = ctrl_addr;
2545 pasv_addr.su_port = 0;
2546 len = pasv_addr.su_len;
2549 if (ctrl_addr.su_family == AF_INET) {
2550 int on = restricted_data_ports ? IP_PORTRANGE_HIGH
2551 : IP_PORTRANGE_DEFAULT;
2553 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2554 (char *)&on, sizeof(on)) < 0)
2558 #ifdef IPV6_PORTRANGE
2559 if (ctrl_addr.su_family == AF_INET6) {
2560 int on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2561 : IPV6_PORTRANGE_DEFAULT;
2563 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2564 (char *)&on, sizeof(on)) < 0)
2569 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2572 (void) seteuid((uid_t)pw->pw_uid);
2574 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2576 if (listen(pdata, 1) < 0)
2579 #define UC(b) (((int) b) & 0xff)
2581 if (strcmp(cmd, "LPSV") == 0) {
2582 p = (char *)&pasv_addr.su_port;
2583 switch (pasv_addr.su_family) {
2585 a = (char *) &pasv_addr.su_sin.sin_addr;
2588 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2589 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2590 2, UC(p[0]), UC(p[1]));
2593 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
2594 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2597 a = (char *) &pasv_addr.su_sin6.sin6_addr;
2599 "Entering Long Passive Mode "
2600 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2601 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2602 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2603 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2604 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2605 2, UC(p[0]), UC(p[1]));
2608 } else if (strcmp(cmd, "EPSV") == 0) {
2609 switch (pasv_addr.su_family) {
2612 reply(229, "Entering Extended Passive Mode (|||%d|)",
2613 ntohs(pasv_addr.su_port));
2617 /* more proper error code? */
2621 (void) seteuid((uid_t)pw->pw_uid);
2622 (void) close(pdata);
2624 perror_reply(425, "Can't open passive connection");
2629 * Generate unique name for file with basename "local".
2630 * The file named "local" is already known to exist.
2631 * Generates failure reply on error.
2634 gunique(char *local)
2636 static char new[MAXPATHLEN];
2641 cp = strrchr(local, '/');
2644 if (stat(cp ? local : ".", &st) < 0) {
2645 perror_reply(553, cp ? local : ".");
2646 return ((char *) 0);
2650 /* -4 is for the .nn<null> we put on the end below */
2651 (void) snprintf(new, sizeof(new) - 4, "%s", local);
2652 cp = new + strlen(new);
2654 for (count = 1; count < 100; count++) {
2655 (void)sprintf(cp, "%d", count);
2656 if (stat(new, &st) < 0)
2659 reply(452, "Unique file name cannot be created.");
2664 * Format and send reply containing system error number.
2667 perror_reply(int code, char *string)
2670 reply(code, "%s: %s.", string, strerror(errno));
2673 static char *onefile[] = {
2679 send_file_list(char *whichf)
2685 char **dirlist, *dirname;
2690 if (strpbrk(whichf, "~{[*?") != NULL) {
2691 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
2693 memset(&gl, 0, sizeof(gl));
2694 gl.gl_matchc = MAXGLOBARGS;
2695 flags |= GLOB_LIMIT;
2697 if (glob(whichf, flags, 0, &gl)) {
2698 reply(550, "not found");
2700 } else if (gl.gl_pathc == 0) {
2702 perror_reply(550, whichf);
2705 dirlist = gl.gl_pathv;
2707 onefile[0] = whichf;
2712 while ((dirname = *dirlist++)) {
2713 if (stat(dirname, &st) < 0) {
2715 * If user typed "ls -l", etc, and the client
2716 * used NLST, do what the user meant.
2718 if (dirname[0] == '-' && *dirlist == NULL &&
2720 retrieve(_PATH_LS " %s", dirname);
2723 perror_reply(550, whichf);
2725 (void) fclose(dout);
2733 if (S_ISREG(st.st_mode)) {
2735 dout = dataconn("file list", (off_t)-1, "w");
2740 fprintf(dout, "%s%s\n", dirname,
2741 type == TYPE_A ? "\r" : "");
2742 byte_count += strlen(dirname) + 1;
2744 } else if (!S_ISDIR(st.st_mode))
2747 if ((dirp = opendir(dirname)) == NULL)
2750 while ((dir = readdir(dirp)) != NULL) {
2751 char nbuf[MAXPATHLEN];
2760 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
2762 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
2766 snprintf(nbuf, sizeof(nbuf),
2767 "%s/%s", dirname, dir->d_name);
2770 * We have to do a stat to insure it's
2771 * not a directory or special file.
2773 if (simple || (stat(nbuf, &st) == 0 &&
2774 S_ISREG(st.st_mode))) {
2776 dout = dataconn("file list", (off_t)-1,
2782 if (nbuf[0] == '.' && nbuf[1] == '/')
2783 fprintf(dout, "%s%s\n", &nbuf[2],
2784 type == TYPE_A ? "\r" : "");
2786 fprintf(dout, "%s%s\n", nbuf,
2787 type == TYPE_A ? "\r" : "");
2788 byte_count += strlen(nbuf) + 1;
2791 (void) closedir(dirp);
2795 reply(550, "No files found.");
2796 else if (ferror(dout) != 0)
2797 perror_reply(550, "Data connection");
2799 reply(226, "Transfer complete.");
2803 (void) fclose(dout);
2814 reapchild(int signo)
2816 while (wait3(NULL, WNOHANG, NULL) > 0);
2819 #ifdef OLD_SETPROCTITLE
2821 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.)
2822 * Warning, since this is usually started from inetd.conf, it often doesn't
2823 * have much of an environment or arglist to overwrite.
2826 setproctitle(const char *fmt, ...)
2834 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
2836 /* make ps print our process name */
2841 if (i > LastArgv - p - 2) {
2842 i = LastArgv - p - 2;
2847 if (ch != '\n' && ch != '\r')
2849 while (p < LastArgv)
2852 #endif /* OLD_SETPROCTITLE */
2855 logxfer(char *name, off_t size, time_t start)
2858 char path[MAXPATHLEN + 1];
2861 if (statfd >= 0 && getwd(path) != NULL) {
2863 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s/%s!%qd!%ld\n",
2864 ctime(&now)+4, ident, remotehost,
2865 path, name, (long long)size,
2866 (long)(now - start + (now == start)));
2867 write(statfd, buf, strlen(buf));