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[] =
47 "$FreeBSD: src/libexec/ftpd/ftpd.c,v 1.62.2.48 2003/02/14 12:42:42 yar Exp $";
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>
90 #include <login_cap.h>
98 #include <security/pam_appl.h>
101 #include "pathnames.h"
110 static char version[] = "Version 6.00LS";
113 extern off_t restart_point;
116 union sockunion server_addr;
117 union sockunion ctrl_addr;
118 union sockunion data_source;
119 union sockunion data_dest;
120 union sockunion his_addr;
121 union sockunion pasv_addr;
126 int hostinfo = 1; /* print host-specific info in messages */
131 int timeout = 900; /* timeout after 15 minutes of inactivity */
132 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
134 int restricted_data_ports = 1;
135 int paranoid = 1; /* be extra careful about security */
136 int anon_only = 0; /* Only anonymous ftp allowed */
144 int stru; /* avoid C keyword */
146 int usedefault = 1; /* for data transfers */
147 int pdata = -1; /* for passive mode */
148 int readonly=0; /* Server is in readonly mode. */
149 int noepsv=0; /* EPSV command is disabled. */
150 int noretr=0; /* RETR command is disabled. */
151 int noguestretr=0; /* RETR command is disabled for anon users. */
152 int noguestmkd=0; /* MKD command is disabled for anon users. */
153 int noguestmod=1; /* anon users may not modify existing files. */
155 static volatile sig_atomic_t recvurg;
156 sig_atomic_t transflag;
159 #if !defined(CMASK) || CMASK == 0
163 int defumask = CMASK; /* default umask value */
168 #ifdef VIRTUAL_HOSTING
171 static struct ftphost {
172 struct ftphost *next;
173 struct addrinfo *hostinfo;
179 } *thishost, *firsthost;
182 char remotehost[MAXHOSTNAMELEN];
185 static char ttyline[20];
186 char *tty = ttyline; /* for klogin */
189 static int auth_pam __P((struct passwd**, const char*));
192 char *pid_file = NULL;
195 * Limit number of pathnames that glob can return.
196 * A limit of 0 indicates the number of pathnames is unlimited.
198 #define MAXGLOBARGS 16384
202 * Timeout intervals for retrying connections
203 * to hosts that don't accept PORT cmds. This
204 * is a kludge, but given the problems with TCP...
206 #define SWAITMAX 90 /* wait at most 90 seconds */
207 #define SWAITINT 5 /* interval between retries */
209 int swaitmax = SWAITMAX;
210 int swaitint = SWAITINT;
213 #ifdef OLD_SETPROCTITLE
214 char **Argv = NULL; /* pointer to argument vector */
215 char *LastArgv = NULL; /* end of argv */
216 #endif /* OLD_SETPROCTITLE */
217 char proctitle[LINE_MAX]; /* initial part of title */
218 #endif /* SETPROCTITLE */
224 #define LOGCMD(cmd, file) \
226 syslog(LOG_INFO,"%s %s%s", cmd, \
227 *(file) == '/' ? "" : curdir(), file);
228 #define LOGCMD2(cmd, file1, file2) \
230 syslog(LOG_INFO,"%s %s%s %s%s", cmd, \
231 *(file1) == '/' ? "" : curdir(), file1, \
232 *(file2) == '/' ? "" : curdir(), file2);
233 #define LOGBYTES(cmd, file, cnt) \
235 if (cnt == (off_t)-1) \
236 syslog(LOG_INFO,"%s %s%s", cmd, \
237 *(file) == '/' ? "" : curdir(), file); \
239 syslog(LOG_INFO, "%s %s%s = %qd bytes", \
240 cmd, (*(file) == '/') ? "" : curdir(), file, cnt); \
243 #ifdef VIRTUAL_HOSTING
244 static void inithosts __P((void));
245 static void selecthost __P((union sockunion *));
247 static void ack __P((char *));
248 static void sigurg __P((int));
249 static void myoob __P((void));
250 static int checkuser __P((char *, char *, int, char **));
251 static FILE *dataconn __P((char *, off_t, char *));
252 static void dolog __P((struct sockaddr *));
253 static char *curdir __P((void));
254 static void end_login __P((void));
255 static FILE *getdatasock __P((char *));
256 static int guniquefd __P((char *, char **));
257 static void lostconn __P((int));
258 static void sigquit __P((int));
259 static int receive_data __P((FILE *, FILE *));
260 static int send_data __P((FILE *, FILE *, off_t, off_t, int));
261 static struct passwd *
262 sgetpwnam __P((char *));
263 static char *sgetsave __P((char *));
264 static void reapchild __P((int));
265 static void logxfer __P((char *, off_t, time_t));
266 static char *doublequote __P((char *));
271 static char path[MAXPATHLEN+1+1]; /* path + '/' + '\0' */
273 if (getcwd(path, sizeof(path)-2) == NULL)
275 if (path[1] != '\0') /* special case for root dir. */
277 /* For guest account, skip / since it's chrooted */
278 return (guest ? path+1 : path);
282 main(argc, argv, envp)
287 int addrlen, ch, on = 1, tos;
288 char *cp, line[LINE_MAX];
291 char *bindname = NULL;
292 const char *bindport = "ftp";
293 int family = AF_UNSPEC;
297 tzset(); /* in case no timezone database in ~ftp */
298 sigemptyset(&sa.sa_mask);
299 sa.sa_flags = SA_RESTART;
301 #ifdef OLD_SETPROCTITLE
303 * Save start and extent of argv for setproctitle.
308 LastArgv = envp[-1] + strlen(envp[-1]);
309 #endif /* OLD_SETPROCTITLE */
312 while ((ch = getopt(argc, argv,
313 "46a:AdDEhlmMoOp:P:rRSt:T:u:UvW")) != -1) {
317 if (family == AF_UNSPEC)
350 logging++; /* > 1 == extra logging */
390 timeout = atoi(optarg);
391 if (maxtimeout < timeout)
392 maxtimeout = timeout;
396 maxtimeout = atoi(optarg);
397 if (timeout > maxtimeout)
398 timeout = maxtimeout;
405 val = strtol(optarg, &optarg, 8);
406 if (*optarg != '\0' || val < 0)
407 warnx("bad value for -u");
413 restricted_data_ports = 0;
425 warnx("unknown flag -%c ignored", optopt);
430 #ifdef VIRTUAL_HOSTING
433 (void) freopen(_PATH_DEVNULL, "w", stderr);
436 * LOG_NDELAY sets up the logging connection immediately,
437 * necessary for anonymous ftp's that chroot and can't do it later.
439 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
443 struct addrinfo hints, *res;
446 * Detach from parent.
448 if (daemon(1, 1) < 0) {
449 syslog(LOG_ERR, "failed to become a daemon");
452 sa.sa_handler = reapchild;
453 (void)sigaction(SIGCHLD, &sa, NULL);
455 memset(&hints, 0, sizeof(hints));
457 hints.ai_family = family == AF_UNSPEC ? AF_INET : family;
458 hints.ai_socktype = SOCK_STREAM;
459 hints.ai_protocol = 0;
460 hints.ai_flags = AI_PASSIVE;
461 error = getaddrinfo(bindname, bindport, &hints, &res);
463 if (family == AF_UNSPEC) {
464 hints.ai_family = AF_UNSPEC;
465 error = getaddrinfo(bindname, bindport, &hints,
470 syslog(LOG_ERR, "%s", gai_strerror(error));
471 if (error == EAI_SYSTEM)
472 syslog(LOG_ERR, "%s", strerror(errno));
475 if (res->ai_addr == NULL) {
476 syslog(LOG_ERR, "-a %s: getaddrinfo failed", hostname);
479 family = res->ai_addr->sa_family;
481 * Open a socket, bind it to the FTP port, and start
484 ctl_sock = socket(family, SOCK_STREAM, 0);
486 syslog(LOG_ERR, "control socket: %m");
489 if (setsockopt(ctl_sock, SOL_SOCKET, SO_REUSEADDR,
490 &on, sizeof(on)) < 0)
492 "control setsockopt (SO_REUSEADDR): %m");
493 if (family == AF_INET6 && enable_v4 == 0) {
494 if (setsockopt(ctl_sock, IPPROTO_IPV6, IPV6_V6ONLY,
495 &on, sizeof (on)) < 0)
497 "control setsockopt (IPV6_V6ONLY): %m");
499 memcpy(&server_addr, res->ai_addr, res->ai_addr->sa_len);
500 if (bind(ctl_sock, (struct sockaddr *)&server_addr,
501 server_addr.su_len) < 0) {
502 syslog(LOG_ERR, "control bind: %m");
505 if (listen(ctl_sock, 32) < 0) {
506 syslog(LOG_ERR, "control listen: %m");
510 * Atomically write process ID
517 fd = open(pid_file, O_CREAT | O_WRONLY | O_TRUNC
518 | O_NONBLOCK | O_EXLOCK, 0644);
521 errx(1, "%s: file locked", pid_file);
523 err(1, "%s", pid_file);
525 snprintf(buf, sizeof(buf),
526 "%lu\n", (unsigned long) getpid());
527 if (write(fd, buf, strlen(buf)) < 0)
528 err(1, "%s: write", pid_file);
529 /* Leave the pid file open and locked */
532 * Loop forever accepting connection requests and forking off
533 * children to handle them.
536 addrlen = server_addr.su_len;
537 fd = accept(ctl_sock, (struct sockaddr *)&his_addr, &addrlen);
548 addrlen = sizeof(his_addr);
549 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
550 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
555 sa.sa_handler = SIG_DFL;
556 (void)sigaction(SIGCHLD, &sa, NULL);
558 sa.sa_handler = sigurg;
559 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
560 (void)sigaction(SIGURG, &sa, NULL);
562 sigfillset(&sa.sa_mask); /* block all signals in handler */
563 sa.sa_flags = SA_RESTART;
564 sa.sa_handler = sigquit;
565 (void)sigaction(SIGHUP, &sa, NULL);
566 (void)sigaction(SIGINT, &sa, NULL);
567 (void)sigaction(SIGQUIT, &sa, NULL);
568 (void)sigaction(SIGTERM, &sa, NULL);
570 sa.sa_handler = lostconn;
571 (void)sigaction(SIGPIPE, &sa, NULL);
573 addrlen = sizeof(ctrl_addr);
574 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
575 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
578 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
579 #ifdef VIRTUAL_HOSTING
580 /* select our identity from virtual host table */
581 selecthost(&ctrl_addr);
584 if (ctrl_addr.su_family == AF_INET)
586 tos = IPTOS_LOWDELAY;
587 if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
588 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
592 * Disable Nagle on the control channel so that we don't have to wait
593 * for peer's ACK before issuing our next reply.
595 if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
596 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
598 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
600 /* set this here so klogin can use it... */
601 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
603 /* Try to handle urgent data inline */
605 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
606 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
610 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
611 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
613 dolog((struct sockaddr *)&his_addr);
615 * Set up default state
624 /* If logins are disabled, print out the message. */
625 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
626 while (fgets(line, sizeof(line), fd) != NULL) {
627 if ((cp = strchr(line, '\n')) != NULL)
629 lreply(530, "%s", line);
631 (void) fflush(stdout);
633 reply(530, "System not available.");
636 #ifdef VIRTUAL_HOSTING
637 if ((fd = fopen(thishost->welcome, "r")) != NULL) {
639 if ((fd = fopen(_PATH_FTPWELCOME, "r")) != NULL) {
641 while (fgets(line, sizeof(line), fd) != NULL) {
642 if ((cp = strchr(line, '\n')) != NULL)
644 lreply(220, "%s", line);
646 (void) fflush(stdout);
648 /* reply(220,) must follow */
650 #ifndef VIRTUAL_HOSTING
651 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
652 fatalerror("Ran out of memory.");
653 (void) gethostname(hostname, MAXHOSTNAMELEN - 1);
654 hostname[MAXHOSTNAMELEN - 1] = '\0';
657 reply(220, "%s FTP server (%s) ready.", hostname, version);
659 reply(220, "FTP server ready.");
671 syslog(LOG_DEBUG, "lost connection");
680 syslog(LOG_ERR, "got signal %d", signo);
684 #ifdef VIRTUAL_HOSTING
686 * read in virtual host tables (if they exist)
695 char *cp, *mp, *line;
697 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
698 struct ftphost *hrp, *lhrp;
699 struct addrinfo hints, *res, *ai;
702 * Fill in the default host information
704 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
705 fatalerror("Ran out of memory.");
706 if (gethostname(hostname, MAXHOSTNAMELEN) < 0)
708 hostname[MAXHOSTNAMELEN - 1] = '\0';
709 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
710 fatalerror("Ran out of memory.");
711 hrp->hostname = hostname;
712 hrp->hostinfo = NULL;
714 memset(&hints, 0, sizeof(hints));
715 hints.ai_flags = AI_CANONNAME;
716 hints.ai_family = AF_UNSPEC;
717 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
719 hrp->statfile = _PATH_FTPDSTATFILE;
720 hrp->welcome = _PATH_FTPWELCOME;
721 hrp->loginmsg = _PATH_FTPLOGINMESG;
722 hrp->anonuser = "ftp";
724 thishost = firsthost = lhrp = hrp;
725 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
726 int addrsize, gothost;
730 while ((line = fgetln(fp, &len)) != NULL) {
736 if (line[len - 1] == '\n') {
737 line[len - 1] = '\0';
740 if ((mp = malloc(len + 1)) == NULL)
741 fatalerror("Ran out of memory.");
742 memcpy(mp, line, len);
746 cp = strtok(line, " \t");
747 /* skip empty lines */
754 statfile = _PATH_FTPDSTATFILE;
755 welcome = _PATH_FTPWELCOME;
756 loginmsg = _PATH_FTPLOGINMESG;
759 * Preparse the line so we can use its info
760 * for all the addresses associated with
761 * the virtual host name.
762 * Field 0, the virtual host name, is special:
763 * it's already parsed off and will be strdup'ed
764 * later, after we know its canonical form.
766 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
767 if (*cp != '-' && (cp = strdup(cp)))
769 case 1: /* anon user permissions */
772 case 2: /* statistics file */
775 case 3: /* welcome message */
778 case 4: /* login message */
781 default: /* programming error */
787 hints.ai_family = AF_UNSPEC;
788 hints.ai_flags = AI_PASSIVE;
789 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
791 for (ai = res; ai != NULL && ai->ai_addr != NULL;
795 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
798 for (hi = hrp->hostinfo; hi != NULL;
800 if (hi->ai_addrlen == ai->ai_addrlen &&
803 ai->ai_addr->sa_len) == 0) {
811 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
813 hrp->hostname = NULL;
816 if (hrp->hostinfo && hrp->hostinfo != res)
817 freeaddrinfo(hrp->hostinfo);
818 insert = 0; /* host already in the chain */
823 * determine hostname to use.
824 * force defined name if there is a valid alias
825 * otherwise fallback to primary hostname
827 /* XXX: getaddrinfo() can't do alias check */
828 switch(hrp->hostinfo->ai_family) {
830 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
831 addrsize = sizeof(struct in_addr);
834 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
835 addrsize = sizeof(struct in6_addr);
838 /* should not reach here */
839 freeaddrinfo(hrp->hostinfo);
841 free(hrp); /*not in chain, can free*/
843 hrp->hostinfo = NULL; /*mark as blank*/
847 if ((hp = getipnodebyaddr(addr, addrsize,
848 hrp->hostinfo->ai_family,
849 &hp_error)) != NULL) {
850 if (strcmp(vhost, hp->h_name) != 0) {
851 if (hp->h_aliases == NULL)
855 while (hp->h_aliases[i] &&
856 strcmp(vhost, hp->h_aliases[i]) != 0)
858 if (hp->h_aliases[i] == NULL)
864 strcmp(hrp->hostname, vhost) != 0) {
866 hrp->hostname = NULL;
868 if (hrp->hostname == NULL &&
869 (hrp->hostname = strdup(vhost)) == NULL) {
870 freeaddrinfo(hrp->hostinfo);
871 hrp->hostinfo = NULL; /* mark as blank */
876 hrp->anonuser = anonuser;
877 hrp->statfile = statfile;
878 hrp->welcome = welcome;
879 hrp->loginmsg = loginmsg;
903 struct in6_addr *mapped_in6 = NULL;
909 * XXX IPv4 mapped IPv6 addr consideraton,
910 * specified in rfc2373.
912 if (su->su_family == AF_INET6 &&
913 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
914 mapped_in6 = &su->su_sin6.sin6_addr;
917 hrp = thishost = firsthost; /* default */
920 while (hrp != NULL) {
921 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
922 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
927 /* XXX IPv4 mapped IPv6 addr consideraton */
928 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
929 (memcmp(&mapped_in6->s6_addr[12],
930 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
931 sizeof(struct in_addr)) == 0)) {
940 /* setup static variables as appropriate */
941 hostname = thishost->hostname;
942 ftpuser = thishost->anonuser;
947 * Helper function for sgetpwnam().
953 char *new = malloc((unsigned) strlen(s) + 1);
956 perror_reply(421, "Local resource failure: malloc");
960 (void) strcpy(new, s);
965 * Save the result of a getpwnam. Used for USER command, since
966 * the data returned must not be clobbered by any other command
969 static struct passwd *
973 static struct passwd save;
976 if ((p = getpwnam(name)) == NULL)
980 free(save.pw_passwd);
986 save.pw_name = sgetsave(p->pw_name);
987 save.pw_passwd = sgetsave(p->pw_passwd);
988 save.pw_gecos = sgetsave(p->pw_gecos);
989 save.pw_dir = sgetsave(p->pw_dir);
990 save.pw_shell = sgetsave(p->pw_shell);
994 static int login_attempts; /* number of failed login attempts */
995 static int askpasswd; /* had user command, ask for passwd */
996 static char curname[MAXLOGNAME]; /* current USER name */
1000 * Sets global passwd pointer pw if named account exists and is acceptable;
1001 * sets askpasswd if a PASS command is expected. If logged in previously,
1002 * need to reset state. If name is "ftp" or "anonymous", the name is not in
1003 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
1004 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
1005 * requesting login privileges. Disallow anyone who does not have a standard
1006 * shell as returned by getusershell(). Disallow anyone mentioned in the file
1007 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
1017 reply(530, "Can't change user from guest login.");
1019 } else if (dochroot) {
1020 reply(530, "Can't change user from chroot user.");
1027 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1028 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL) ||
1029 checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL))
1030 reply(530, "User %s access denied.", name);
1031 #ifdef VIRTUAL_HOSTING
1032 else if ((pw = sgetpwnam(thishost->anonuser)) != NULL) {
1034 else if ((pw = sgetpwnam("ftp")) != NULL) {
1039 "Guest login ok, send your email address as password.");
1041 reply(530, "User %s unknown.", name);
1042 if (!askpasswd && logging)
1044 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1047 if (anon_only != 0) {
1048 reply(530, "Sorry, only anonymous ftp allowed.");
1052 if ((pw = sgetpwnam(name))) {
1053 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1054 shell = _PATH_BSHELL;
1055 while ((cp = getusershell()) != NULL)
1056 if (strcmp(cp, shell) == 0)
1060 if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1, NULL)) {
1061 reply(530, "User %s access denied.", name);
1064 "FTP LOGIN REFUSED FROM %s, %s",
1066 pw = (struct passwd *) NULL;
1071 strncpy(curname, name, sizeof(curname)-1);
1073 pwok = skeyaccess(name, NULL, remotehost, remotehost);
1074 reply(331, "%s", skey_challenge(name, pw, pwok));
1076 reply(331, "Password required for %s.", name);
1080 * Delay before reading passwd after first failed
1081 * attempt to slow down passwd-guessing programs.
1084 sleep((unsigned) login_attempts);
1088 * Check if a user is in the file "fname",
1089 * return a pointer to a malloc'd string with the rest
1090 * of the matching line in "residue" if not NULL.
1093 checkuser(fname, name, pwset, residue)
1102 char *line, *mp, *p;
1104 if ((fd = fopen(fname, "r")) != NULL) {
1105 while (!found && (line = fgetln(fd, &len)) != NULL) {
1109 if (line[len - 1] == '\n') {
1110 line[len - 1] = '\0';
1113 if ((mp = malloc(len + 1)) == NULL)
1114 fatalerror("Ran out of memory.");
1115 memcpy(mp, line, len);
1119 /* avoid possible leading and trailing whitespace */
1120 p = strtok(line, " \t");
1121 /* skip empty lines */
1125 * if first chr is '@', check group membership
1131 if (p[1] == '\0') /* single @ matches anyone */
1134 if ((grp = getgrnam(p+1)) == NULL)
1137 * Check user's default group
1139 if (pwset && grp->gr_gid == pw->pw_gid)
1142 * Check supplementary groups
1144 while (!found && grp->gr_mem[i])
1145 found = strcmp(name,
1151 * Otherwise, just check for username match
1154 found = strcmp(p, name) == 0;
1156 * Save the rest of line to "residue" if matched
1158 if (found && residue) {
1159 if ((p = strtok(NULL, "")) != NULL)
1160 p += strspn(p, " \t");
1162 if ((*residue = strdup(p)) == NULL)
1163 fatalerror("Ran out of memory.");
1177 * Terminate login as previous user, if any, resetting state;
1178 * used when USER command is given or login fails.
1184 (void) seteuid((uid_t)0);
1185 if (logged_in && dowtmp)
1186 ftpd_logwtmp(ttyline, "", NULL);
1189 setusercontext(NULL, getpwuid(0), (uid_t)0,
1190 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1200 * the following code is stolen from imap-uw PAM authentication module and
1203 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1206 const char *uname; /* user name */
1207 const char *pass; /* password */
1209 typedef struct cred_t cred_t;
1212 auth_conv(int num_msg, const struct pam_message **msg,
1213 struct pam_response **resp, void *appdata)
1216 cred_t *cred = (cred_t *) appdata;
1217 struct pam_response *reply =
1218 malloc(sizeof(struct pam_response) * num_msg);
1220 for (i = 0; i < num_msg; i++) {
1221 switch (msg[i]->msg_style) {
1222 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1223 reply[i].resp_retcode = PAM_SUCCESS;
1224 reply[i].resp = COPY_STRING(cred->uname);
1225 /* PAM frees resp. */
1227 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1228 reply[i].resp_retcode = PAM_SUCCESS;
1229 reply[i].resp = COPY_STRING(cred->pass);
1230 /* PAM frees resp. */
1234 reply[i].resp_retcode = PAM_SUCCESS;
1235 reply[i].resp = NULL;
1237 default: /* unknown message style */
1239 return PAM_CONV_ERR;
1248 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1249 * authenticated, or 1 if not authenticated. If some sort of PAM system
1250 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1251 * function returns -1. This can be used as an indication that we should
1252 * fall back to a different authentication mechanism.
1255 auth_pam(struct passwd **ppw, const char *pass)
1257 pam_handle_t *pamh = NULL;
1258 const char *tmpl_user;
1262 cred_t auth_cred = { (*ppw)->pw_name, pass };
1263 struct pam_conv conv = { &auth_conv, &auth_cred };
1265 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1266 if (e != PAM_SUCCESS) {
1267 syslog(LOG_ERR, "pam_start: %s", pam_strerror(pamh, e));
1271 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1272 if (e != PAM_SUCCESS) {
1273 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1274 pam_strerror(pamh, e));
1278 e = pam_authenticate(pamh, 0);
1282 * With PAM we support the concept of a "template"
1283 * user. The user enters a login name which is
1284 * authenticated by PAM, usually via a remote service
1285 * such as RADIUS or TACACS+. If authentication
1286 * succeeds, a different but related "template" name
1287 * is used for setting the credentials, shell, and
1288 * home directory. The name the user enters need only
1289 * exist on the remote authentication server, but the
1290 * template name must be present in the local password
1293 * This is supported by two various mechanisms in the
1294 * individual modules. However, from the application's
1295 * point of view, the template user is always passed
1296 * back as a changed value of the PAM_USER item.
1298 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1300 tmpl_user = (const char *) item;
1301 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1302 *ppw = getpwnam(tmpl_user);
1304 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1305 pam_strerror(pamh, e));
1310 case PAM_USER_UNKNOWN:
1316 syslog(LOG_ERR, "auth_pam: %s", pam_strerror(pamh, e));
1321 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1322 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1328 #endif /* !defined(NOPAM) */
1337 login_cap_t *lc = NULL;
1340 char *residue = NULL;
1342 if (logged_in || askpasswd == 0) {
1343 reply(503, "Login with USER first.");
1347 if (!guest) { /* "ftp" is only account allowed no password */
1349 rval = 1; /* failure below */
1353 rval = auth_pam(&pw, passwd);
1359 rval = strcmp(pw->pw_passwd,
1360 crypt(passwd, pw->pw_passwd));
1362 rval = strcmp(pw->pw_passwd,
1363 skey_crypt(passwd, pw->pw_passwd, pw, pwok));
1365 rval = strcmp(pw->pw_passwd, crypt(passwd, pw->pw_passwd));
1367 /* The strcmp does not catch null passwords! */
1368 if (*pw->pw_passwd == '\0' ||
1369 (pw->pw_expire && time(NULL) >= pw->pw_expire))
1370 rval = 1; /* failure */
1373 * If rval == 1, the user failed the authentication check
1374 * above. If rval == 0, either PAM or local authentication
1378 reply(530, "Login incorrect.");
1381 "FTP LOGIN FAILED FROM %s",
1383 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1384 "FTP LOGIN FAILED FROM %s, %s",
1385 remotehost, curname);
1388 if (login_attempts++ >= 5) {
1390 "repeated login failures from %s",
1400 login_attempts = 0; /* this time successful */
1401 if (setegid((gid_t)pw->pw_gid) < 0) {
1402 reply(550, "Can't set gid.");
1405 /* May be overridden by login.conf */
1406 (void) umask(defumask);
1408 if ((lc = login_getpwclass(pw)) != NULL) {
1409 char remote_ip[MAXHOSTNAMELEN];
1411 getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1412 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1414 remote_ip[sizeof(remote_ip) - 1] = 0;
1415 if (!auth_hostok(lc, remotehost, remote_ip)) {
1416 syslog(LOG_INFO|LOG_AUTH,
1417 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1419 reply(530, "Permission denied.\n");
1423 if (!auth_timeok(lc, time(NULL))) {
1424 reply(530, "Login not available right now.\n");
1429 setusercontext(lc, pw, (uid_t)0,
1430 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1431 LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1433 setlogin(pw->pw_name);
1434 (void) initgroups(pw->pw_name, pw->pw_gid);
1437 /* open wtmp before chroot */
1439 ftpd_logwtmp(ttyline, pw->pw_name,
1440 (struct sockaddr *)&his_addr);
1443 if (guest && stats && statfd < 0)
1444 #ifdef VIRTUAL_HOSTING
1445 if ((statfd = open(thishost->statfile, O_WRONLY|O_APPEND)) < 0)
1447 if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0)
1452 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue)
1453 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1454 || login_getcapbool(lc, "ftp-chroot", 0)
1459 * For a chrooted local user,
1460 * a) see whether ftpchroot(5) specifies a chroot directory,
1461 * b) extract the directory pathname from the line,
1462 * c) expand it to the absolute pathname if necessary.
1464 if (dochroot && residue &&
1465 (chrootdir = strtok(residue, " \t")) != NULL &&
1466 chrootdir[0] != '/') {
1467 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1468 if (chrootdir == NULL)
1469 fatalerror("Ran out of memory.");
1471 if (guest || dochroot) {
1473 * If no chroot directory set yet, use the login directory.
1474 * Copy it so it can be modified while pw->pw_dir stays intact.
1476 if (chrootdir == NULL &&
1477 (chrootdir = strdup(pw->pw_dir)) == NULL)
1478 fatalerror("Ran out of memory.");
1480 * Check for the "/chroot/./home" syntax,
1481 * separate the chroot and home directory pathnames.
1483 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1484 *(homedir++) = '\0'; /* wipe '/' */
1485 homedir++; /* skip '.' */
1486 /* so chrootdir can be freed later */
1487 if ((homedir = strdup(homedir)) == NULL)
1488 fatalerror("Ran out of memory.");
1491 * We MUST do a chdir() after the chroot. Otherwise
1492 * the old current directory will be accessible as "."
1493 * outside the new root!
1498 * Finally, do chroot()
1500 if (chroot(chrootdir) < 0) {
1501 reply(550, "Can't change root.");
1504 } else /* real user w/o chroot */
1505 homedir = pw->pw_dir;
1507 * Set euid *before* doing chdir() so
1508 * a) the user won't be carried to a directory that he couldn't reach
1509 * on his own due to no permission to upper path components,
1510 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1511 * (uid 0 has no root power over NFS if not mapped explicitly.)
1513 if (seteuid((uid_t)pw->pw_uid) < 0) {
1514 reply(550, "Can't set uid.");
1517 if (chdir(homedir) < 0) {
1518 if (guest || dochroot) {
1519 reply(550, "Can't change to base directory.");
1522 if (chdir("/") < 0) {
1523 reply(550, "Root is inaccessible.");
1526 lreply(230, "No directory! Logging in with home=/");
1531 * Display a login message, if it exists.
1532 * N.B. reply(230,) must follow the message.
1534 #ifdef VIRTUAL_HOSTING
1535 if ((fd = fopen(thishost->loginmsg, "r")) != NULL) {
1537 if ((fd = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) {
1539 char *cp, line[LINE_MAX];
1541 while (fgets(line, sizeof(line), fd) != NULL) {
1542 if ((cp = strchr(line, '\n')) != NULL)
1544 lreply(230, "%s", line);
1546 (void) fflush(stdout);
1552 ident = strdup(passwd);
1554 fatalerror("Ran out of memory.");
1556 reply(230, "Guest login ok, access restrictions apply.");
1558 #ifdef VIRTUAL_HOSTING
1559 if (thishost != firsthost)
1560 snprintf(proctitle, sizeof(proctitle),
1561 "%s: anonymous(%s)/%s", remotehost, hostname,
1565 snprintf(proctitle, sizeof(proctitle),
1566 "%s: anonymous/%s", remotehost, passwd);
1567 setproctitle("%s", proctitle);
1568 #endif /* SETPROCTITLE */
1570 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1571 remotehost, passwd);
1574 reply(230, "User %s logged in, "
1575 "access restrictions apply.", pw->pw_name);
1577 reply(230, "User %s logged in.", pw->pw_name);
1580 snprintf(proctitle, sizeof(proctitle),
1581 "%s: user/%s", remotehost, pw->pw_name);
1582 setproctitle("%s", proctitle);
1583 #endif /* SETPROCTITLE */
1585 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1586 remotehost, pw->pw_name);
1597 /* Forget all about it... */
1614 int (*closefunc) __P((FILE *));
1618 fin = fopen(name, "r"), closefunc = fclose;
1623 (void) snprintf(line, sizeof(line), cmd, name), name = line;
1624 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1626 st.st_blksize = BUFSIZ;
1630 perror_reply(550, name);
1632 LOGCMD("get", name);
1639 if (fstat(fileno(fin), &st) < 0) {
1640 perror_reply(550, name);
1643 if (!S_ISREG(st.st_mode)) {
1645 reply(550, "%s: not a plain file.", name);
1649 /* st.st_blksize is set for all descriptor types */
1652 if (restart_point) {
1653 if (type == TYPE_A) {
1660 if ((c=getc(fin)) == EOF) {
1661 perror_reply(550, name);
1667 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1668 perror_reply(550, name);
1672 dout = dataconn(name, st.st_size, "w");
1676 send_data(fin, dout, st.st_blksize, st.st_size,
1677 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1678 if (cmd == 0 && guest && stats)
1679 logxfer(name, st.st_size, start);
1680 (void) fclose(dout);
1685 LOGBYTES("get", name, byte_count);
1690 store(name, mode, unique)
1696 int (*closefunc) __P((FILE *));
1698 if (*mode == 'a') { /* APPE */
1700 /* Programming error */
1701 syslog(LOG_ERR, "Internal: unique flag to APPE");
1704 if (guest && noguestmod) {
1705 reply(550, "Appending to existing file denied");
1708 restart_point = 0; /* not affected by preceding REST */
1710 if (unique) /* STOU overrides REST */
1712 if (guest && noguestmod) {
1713 if (restart_point) { /* guest STOR w/REST */
1714 reply(550, "Modifying existing file denied");
1716 } else /* treat guest STOR as STOU */
1721 mode = "r+"; /* so ASCII manual seek can work */
1723 if ((fd = guniquefd(name, &name)) < 0)
1725 fout = fdopen(fd, mode);
1727 fout = fopen(name, mode);
1730 perror_reply(553, name);
1734 if (restart_point) {
1735 if (type == TYPE_A) {
1742 if ((c=getc(fout)) == EOF) {
1743 perror_reply(550, name);
1750 * We must do this seek to "current" position
1751 * because we are changing from reading to
1754 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1755 perror_reply(550, name);
1758 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1759 perror_reply(550, name);
1763 din = dataconn(name, (off_t)-1, "r");
1766 if (receive_data(din, fout) == 0) {
1768 reply(226, "Transfer complete (unique file name:%s).",
1771 reply(226, "Transfer complete.");
1777 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1781 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1789 int on = 1, s, t, tries;
1792 return (fdopen(data, mode));
1793 (void) seteuid((uid_t)0);
1795 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1798 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1799 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1800 /* anchor socket to avoid multi-homing problems */
1801 data_source = ctrl_addr;
1802 data_source.su_port = htons(dataport);
1803 for (tries = 1; ; tries++) {
1804 if (bind(s, (struct sockaddr *)&data_source,
1805 data_source.su_len) >= 0)
1807 if (errno != EADDRINUSE || tries > 10)
1811 (void) seteuid((uid_t)pw->pw_uid);
1813 if (data_source.su_family == AF_INET)
1815 on = IPTOS_THROUGHPUT;
1816 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1817 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1822 * Turn off push flag to keep sender TCP from sending short packets
1823 * at the boundaries of each write(). Should probably do a SO_SNDBUF
1824 * to set the send buffer size as well, but that may not be desirable
1825 * in heavy-load situations.
1828 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1829 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1833 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &on, sizeof on) < 0)
1834 syslog(LOG_WARNING, "data setsockopt (SO_SNDBUF): %m");
1837 return (fdopen(s, mode));
1839 /* Return the real value of errno (close may change it) */
1841 (void) seteuid((uid_t)pw->pw_uid);
1848 dataconn(name, size, mode)
1855 int retry = 0, tos, conerrno;
1859 if (size != (off_t) -1)
1860 (void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)", size);
1864 union sockunion from;
1866 int s, fromlen = ctrl_addr.su_len;
1867 struct timeval timeout;
1871 FD_SET(pdata, &set);
1873 timeout.tv_usec = 0;
1874 timeout.tv_sec = 120;
1877 * Granted a socket is in the blocking I/O mode,
1878 * accept() will block after a successful select()
1879 * if the selected connection dies in between.
1880 * Therefore set the non-blocking I/O flag here.
1882 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1883 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1885 if (select(pdata+1, &set, (fd_set *) 0, (fd_set *) 0, &timeout) <= 0 ||
1886 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1888 (void) close(pdata);
1891 * Unset the inherited non-blocking I/O flag
1892 * on the child socket so stdio can work on it.
1894 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1895 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1898 if (from.su_family == AF_INET)
1900 tos = IPTOS_THROUGHPUT;
1901 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1902 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1905 reply(150, "Opening %s mode data connection for '%s'%s.",
1906 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1907 return (fdopen(pdata, mode));
1909 reply(425, "Can't open data connection.");
1910 (void) close(pdata);
1915 reply(125, "Using existing data connection for '%s'%s.",
1918 return (fdopen(data, mode));
1921 data_dest = his_addr;
1924 file = getdatasock(mode);
1926 char hostbuf[BUFSIZ], portbuf[BUFSIZ];
1927 getnameinfo((struct sockaddr *)&data_source,
1928 data_source.su_len, hostbuf, sizeof(hostbuf) - 1,
1929 portbuf, sizeof(portbuf),
1930 NI_NUMERICHOST|NI_NUMERICSERV);
1931 reply(425, "Can't create data socket (%s,%s): %s.",
1932 hostbuf, portbuf, strerror(errno));
1935 data = fileno(file);
1937 if (connect(data, (struct sockaddr *)&data_dest,
1938 data_dest.su_len) == 0)
1941 (void) fclose(file);
1943 if (conerrno == EADDRINUSE) {
1944 sleep((unsigned) swaitint);
1949 } while (retry <= swaitmax);
1950 if (conerrno != 0) {
1951 perror_reply(425, "Can't build data connection");
1954 reply(150, "Opening %s mode data connection for '%s'%s.",
1955 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1960 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1961 * encapsulation of the data subject to Mode, Structure, and Type.
1963 * NB: Form isn't handled.
1966 send_data(instr, outstr, blksize, filesize, isreg)
1967 FILE *instr, *outstr;
1972 int c, filefd, netfd;
1980 while ((c = getc(instr)) != EOF) {
1987 (void) putc('\r', outstr);
1989 (void) putc(c, outstr);
1999 reply(226, "Transfer complete.");
2005 * isreg is only set if we are not doing restart and we
2006 * are sending a regular file
2008 netfd = fileno(outstr);
2009 filefd = fileno(instr);
2016 err = cnt = offset = 0;
2018 while (err != -1 && filesize > 0) {
2019 err = sendfile(filefd, netfd, offset, 0,
2020 (struct sf_hdtr *) NULL, &cnt, 0);
2022 * Calculate byte_count before OOB processing.
2023 * It can be used in myoob() later.
2040 reply(226, "Transfer complete.");
2045 if ((buf = malloc((u_int)blksize)) == NULL) {
2047 perror_reply(451, "Local resource failure: malloc");
2051 while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
2052 write(netfd, buf, cnt) == cnt)
2061 reply(226, "Transfer complete.");
2065 reply(550, "Unimplemented TYPE %d in send_data", type);
2071 perror_reply(426, "Data connection");
2076 perror_reply(551, "Error on input file");
2087 * Transfer data from peer to "outstr" using the appropriate encapulation of
2088 * the data subject to Mode, Structure, and Type.
2090 * N.B.: Form isn't handled.
2093 receive_data(instr, outstr)
2094 FILE *instr, *outstr;
2107 while ((cnt = read(fileno(instr), buf, sizeof(buf))) > 0) {
2110 if (write(fileno(outstr), buf, cnt) != cnt)
2122 reply(553, "TYPE E not implemented.");
2127 while ((c = getc(instr)) != EOF) {
2136 if ((c = getc(instr)) != '\n') {
2137 (void) putc ('\r', outstr);
2138 if (c == '\0' || c == EOF)
2142 (void) putc(c, outstr);
2155 "WARNING! %d bare linefeeds received in ASCII mode",
2157 (void)printf(" File may not have transferred correctly.\r\n");
2161 reply(550, "Unimplemented TYPE %d in receive_data", type);
2168 perror_reply(426, "Data Connection");
2173 perror_reply(452, "Error writing file");
2184 statfilecmd(filename)
2190 char line[LINE_MAX];
2192 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2193 fin = ftpd_popen(line, "r");
2194 lreply(211, "status of %s:", filename);
2196 while ((c = getc(fin)) != EOF) {
2198 if (ferror(stdout)){
2199 perror_reply(421, "control connection");
2200 (void) ftpd_pclose(fin);
2205 perror_reply(551, filename);
2206 (void) ftpd_pclose(fin);
2209 (void) putc('\r', stdout);
2212 * RFC 959 says neutral text should be prepended before
2213 * a leading 3-digit number followed by whitespace, but
2214 * many ftp clients can be confused by any leading digits,
2215 * as a matter of fact.
2217 if (atstart && isdigit(c))
2218 (void) putc(' ', stdout);
2219 (void) putc(c, stdout);
2220 atstart = (c == '\n');
2222 (void) ftpd_pclose(fin);
2223 reply(211, "End of Status");
2229 union sockunion *su;
2231 char hname[NI_MAXHOST];
2235 lreply(211, "%s FTP server status:", hostname);
2236 printf(" %s\r\n", version);
2238 lreply(211, "FTP server status:");
2239 printf(" Connected to %s", remotehost);
2240 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2241 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2242 if (strcmp(hname, remotehost) != 0)
2243 printf(" (%s)", hname);
2248 printf(" Logged in anonymously\r\n");
2250 printf(" Logged in as %s\r\n", pw->pw_name);
2251 } else if (askpasswd)
2252 printf(" Waiting for password\r\n");
2254 printf(" Waiting for user name\r\n");
2255 printf(" TYPE: %s", typenames[type]);
2256 if (type == TYPE_A || type == TYPE_E)
2257 printf(", FORM: %s", formnames[form]);
2260 printf(" %d", NBBY);
2262 printf(" %d", bytesize); /* need definition! */
2264 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2265 strunames[stru], modenames[mode]);
2267 printf(" Data connection open\r\n");
2268 else if (pdata != -1) {
2272 } else if (usedefault == 0) {
2276 #define UC(b) (((int) b) & 0xff)
2278 printf(" EPSV only mode (EPSV ALL)\r\n");
2283 if (su->su_family == AF_INET) {
2284 a = (u_char *) &su->su_sin.sin_addr;
2285 p = (u_char *) &su->su_sin.sin_port;
2286 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2287 ispassive ? "PASV" : "PORT",
2288 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2289 UC(p[0]), UC(p[1]));
2296 switch (su->su_family) {
2298 a = (u_char *) &su->su_sin.sin_addr;
2299 p = (u_char *) &su->su_sin.sin_port;
2300 alen = sizeof(su->su_sin.sin_addr);
2304 a = (u_char *) &su->su_sin6.sin6_addr;
2305 p = (u_char *) &su->su_sin6.sin6_port;
2306 alen = sizeof(su->su_sin6.sin6_addr);
2314 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2316 for (i = 0; i < alen; i++)
2317 printf("%d,", UC(a[i]));
2318 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2327 switch (su->su_family) {
2339 union sockunion tmp;
2342 if (tmp.su_family == AF_INET6)
2343 tmp.su_sin6.sin6_scope_id = 0;
2344 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2345 hname, sizeof(hname) - 1, NULL, 0,
2347 printf(" %s |%d|%s|%d|\r\n",
2348 ispassive ? "EPSV" : "EPRT",
2349 af, hname, htons(tmp.su_port));
2355 printf(" No data connection\r\n");
2356 reply(211, "End of status");
2364 reply(451, "Error in server: %s\n", s);
2365 reply(221, "Closing connection due to server error.");
2372 reply(int n, const char *fmt, ...)
2374 reply(n, fmt, va_alist)
2386 (void)printf("%d ", n);
2387 (void)vprintf(fmt, ap);
2388 (void)printf("\r\n");
2389 (void)fflush(stdout);
2391 syslog(LOG_DEBUG, "<--- %d ", n);
2392 vsyslog(LOG_DEBUG, fmt, ap);
2398 lreply(int n, const char *fmt, ...)
2400 lreply(n, fmt, va_alist)
2412 (void)printf("%d- ", n);
2413 (void)vprintf(fmt, ap);
2414 (void)printf("\r\n");
2415 (void)fflush(stdout);
2417 syslog(LOG_DEBUG, "<--- %d- ", n);
2418 vsyslog(LOG_DEBUG, fmt, ap);
2427 reply(250, "%s command successful.", s);
2435 reply(502, "%s command not implemented.", s);
2445 if ((cp = strchr(cbuf,'\n')))
2447 reply(500, "'%s': command not understood.", cbuf);
2456 LOGCMD("delete", name);
2457 if (lstat(name, &st) < 0) {
2458 perror_reply(550, name);
2461 if ((st.st_mode&S_IFMT) == S_IFDIR) {
2462 if (rmdir(name) < 0) {
2463 perror_reply(550, name);
2468 if (unlink(name) < 0) {
2469 perror_reply(550, name);
2481 if (chdir(path) < 0)
2482 perror_reply(550, path);
2493 LOGCMD("mkdir", name);
2494 if (guest && noguestmkd)
2495 reply(550, "%s: permission denied", name);
2496 else if (mkdir(name, 0777) < 0)
2497 perror_reply(550, name);
2499 if ((s = doublequote(name)) == NULL)
2500 fatalerror("Ran out of memory.");
2501 reply(257, "\"%s\" directory created.", s);
2511 LOGCMD("rmdir", name);
2512 if (rmdir(name) < 0)
2513 perror_reply(550, name);
2521 char *s, path[MAXPATHLEN + 1];
2523 if (getwd(path) == (char *)NULL)
2524 reply(550, "%s.", path);
2526 if ((s = doublequote(path)) == NULL)
2527 fatalerror("Ran out of memory.");
2528 reply(257, "\"%s\" is current directory.", s);
2539 if (lstat(name, &st) < 0) {
2540 perror_reply(550, name);
2543 reply(350, "File exists, ready for destination name");
2553 LOGCMD2("rename", from, to);
2555 if (guest && (stat(to, &st) == 0)) {
2556 reply(550, "%s: permission denied", to);
2560 if (rename(from, to) < 0)
2561 perror_reply(550, "rename");
2568 struct sockaddr *who;
2572 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2575 #ifdef VIRTUAL_HOSTING
2576 if (thishost != firsthost)
2577 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2578 remotehost, hostname);
2581 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2583 setproctitle("%s", proctitle);
2584 #endif /* SETPROCTITLE */
2587 #ifdef VIRTUAL_HOSTING
2588 if (thishost != firsthost)
2589 syslog(LOG_INFO, "connection from %s (to %s)",
2590 remotehost, hostname);
2594 char who_name[MAXHOSTNAMELEN];
2596 error = getnameinfo(who, who->sa_len,
2597 who_name, sizeof(who_name) - 1,
2598 NULL, 0, NI_NUMERICHOST);
2599 syslog(LOG_INFO, "connection from %s (%s)", remotehost,
2600 error == 0 ? who_name : "");
2606 * Record logout in wtmp file
2607 * and exit with supplied status.
2614 * Prevent reception of SIGURG from resulting in a resumption
2615 * back to the main program loop.
2619 if (logged_in && dowtmp) {
2620 (void) seteuid((uid_t)0);
2621 ftpd_logwtmp(ttyline, "", NULL);
2623 /* beware of flushing buffers after a SIGPIPE */
2640 /* only process if transfer occurring */
2644 if (getline(cp, 7, stdin) == NULL) {
2645 reply(221, "You could at least say goodbye.");
2649 if (strcmp(cp, "ABOR\r\n") == 0) {
2651 reply(426, "Transfer aborted. Data connection closed.");
2652 reply(226, "Abort successful");
2654 if (strcmp(cp, "STAT\r\n") == 0) {
2656 if (file_size != (off_t) -1)
2657 reply(213, "Status: %qd of %qd bytes transferred",
2658 byte_count, file_size);
2660 reply(213, "Status: %qd bytes transferred", byte_count);
2665 * Note: a response of 425 is not mentioned as a possible response to
2666 * the PASV command in RFC959. However, it has been blessed as
2667 * a legitimate response by Jon Postel in a telephone conversation
2668 * with Rick Adams on 25 Jan 89.
2676 if (pdata >= 0) /* close old port if one set */
2679 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2681 perror_reply(425, "Can't open passive connection");
2685 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2686 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2688 (void) seteuid((uid_t)0);
2691 if (ctrl_addr.su_family == AF_INET) {
2692 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2693 : IP_PORTRANGE_DEFAULT;
2695 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2696 &on, sizeof(on)) < 0)
2700 #ifdef IPV6_PORTRANGE
2701 if (ctrl_addr.su_family == AF_INET6) {
2702 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2703 : IPV6_PORTRANGE_DEFAULT;
2705 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2706 &on, sizeof(on)) < 0)
2711 pasv_addr = ctrl_addr;
2712 pasv_addr.su_port = 0;
2713 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2716 (void) seteuid((uid_t)pw->pw_uid);
2718 len = sizeof(pasv_addr);
2719 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2721 if (listen(pdata, 1) < 0)
2723 if (pasv_addr.su_family == AF_INET)
2724 a = (char *) &pasv_addr.su_sin.sin_addr;
2725 else if (pasv_addr.su_family == AF_INET6 &&
2726 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2727 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2731 p = (char *) &pasv_addr.su_port;
2733 #define UC(b) (((int) b) & 0xff)
2735 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2736 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2740 (void) seteuid((uid_t)pw->pw_uid);
2741 (void) close(pdata);
2743 perror_reply(425, "Can't open passive connection");
2748 * Long Passive defined in RFC 1639.
2749 * 228 Entering Long Passive Mode
2750 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2754 long_passive(cmd, pf)
2761 if (pdata >= 0) /* close old port if one set */
2764 if (pf != PF_UNSPEC) {
2765 if (ctrl_addr.su_family != pf) {
2766 switch (ctrl_addr.su_family) {
2779 * only EPRT/EPSV ready clients will understand this
2781 if (strcmp(cmd, "EPSV") == 0 && pf) {
2782 reply(522, "Network protocol mismatch, "
2785 reply(501, "Network protocol mismatch"); /*XXX*/
2791 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2793 perror_reply(425, "Can't open passive connection");
2797 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2798 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2800 (void) seteuid((uid_t)0);
2802 pasv_addr = ctrl_addr;
2803 pasv_addr.su_port = 0;
2804 len = pasv_addr.su_len;
2807 if (ctrl_addr.su_family == AF_INET) {
2808 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2809 : IP_PORTRANGE_DEFAULT;
2811 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2812 &on, sizeof(on)) < 0)
2816 #ifdef IPV6_PORTRANGE
2817 if (ctrl_addr.su_family == AF_INET6) {
2818 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2819 : IPV6_PORTRANGE_DEFAULT;
2821 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2822 &on, sizeof(on)) < 0)
2827 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2830 (void) seteuid((uid_t)pw->pw_uid);
2832 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2834 if (listen(pdata, 1) < 0)
2837 #define UC(b) (((int) b) & 0xff)
2839 if (strcmp(cmd, "LPSV") == 0) {
2840 p = (char *)&pasv_addr.su_port;
2841 switch (pasv_addr.su_family) {
2843 a = (char *) &pasv_addr.su_sin.sin_addr;
2846 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2847 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2848 2, UC(p[0]), UC(p[1]));
2851 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
2852 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2855 a = (char *) &pasv_addr.su_sin6.sin6_addr;
2857 "Entering Long Passive Mode "
2858 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2859 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2860 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2861 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2862 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2863 2, UC(p[0]), UC(p[1]));
2866 } else if (strcmp(cmd, "EPSV") == 0) {
2867 switch (pasv_addr.su_family) {
2870 reply(229, "Entering Extended Passive Mode (|||%d|)",
2871 ntohs(pasv_addr.su_port));
2875 /* more proper error code? */
2879 (void) seteuid((uid_t)pw->pw_uid);
2880 (void) close(pdata);
2882 perror_reply(425, "Can't open passive connection");
2887 * Generate unique name for file with basename "local"
2888 * and open the file in order to avoid possible races.
2889 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
2890 * Return descriptor to the file, set "name" to its name.
2892 * Generates failure reply on error.
2895 guniquefd(local, name)
2899 static char new[MAXPATHLEN];
2905 cp = strrchr(local, '/');
2908 if (stat(cp ? local : ".", &st) < 0) {
2909 perror_reply(553, cp ? local : ".");
2914 * Let not overwrite dirname with counter suffix.
2916 * In this extreme case dot won't be put in front of suffix.
2918 if (strlen(local) > sizeof(new) - 4) {
2919 reply(553, "Pathname too long");
2924 /* -4 is for the .nn<null> we put on the end below */
2925 (void) snprintf(new, sizeof(new) - 4, "%s", local);
2926 cp = new + strlen(new);
2928 * Don't generate dotfile unless requested explicitly.
2929 * This covers the case when basename gets truncated off
2932 if (cp > new && cp[-1] != '/')
2934 for (count = 0; count < 100; count++) {
2935 /* At count 0 try unmodified name */
2937 (void)sprintf(cp, "%d", count);
2938 if ((fd = open(count ? new : local,
2939 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
2940 *name = count ? new : local;
2943 if (errno != EEXIST) {
2944 perror_reply(553, count ? new : local);
2948 reply(452, "Unique file name cannot be created.");
2953 * Format and send reply containing system error number.
2956 perror_reply(code, string)
2961 reply(code, "%s: %s.", string, strerror(errno));
2964 static char *onefile[] = {
2970 send_file_list(whichf)
2977 char **dirlist, *dirname;
2982 if (strpbrk(whichf, "~{[*?") != NULL) {
2983 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
2985 memset(&gl, 0, sizeof(gl));
2986 gl.gl_matchc = MAXGLOBARGS;
2987 flags |= GLOB_LIMIT;
2989 if (glob(whichf, flags, 0, &gl)) {
2990 reply(550, "not found");
2992 } else if (gl.gl_pathc == 0) {
2994 perror_reply(550, whichf);
2997 dirlist = gl.gl_pathv;
2999 onefile[0] = whichf;
3004 while ((dirname = *dirlist++)) {
3005 if (stat(dirname, &st) < 0) {
3007 * If user typed "ls -l", etc, and the client
3008 * used NLST, do what the user meant.
3010 if (dirname[0] == '-' && *dirlist == NULL &&
3012 retrieve(_PATH_LS " %s", dirname);
3015 perror_reply(550, whichf);
3017 (void) fclose(dout);
3025 if (S_ISREG(st.st_mode)) {
3027 dout = dataconn("file list", (off_t)-1, "w");
3032 fprintf(dout, "%s%s\n", dirname,
3033 type == TYPE_A ? "\r" : "");
3034 byte_count += strlen(dirname) + 1;
3036 } else if (!S_ISDIR(st.st_mode))
3039 if ((dirp = opendir(dirname)) == NULL)
3042 while ((dir = readdir(dirp)) != NULL) {
3043 char nbuf[MAXPATHLEN];
3052 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
3054 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3058 snprintf(nbuf, sizeof(nbuf),
3059 "%s/%s", dirname, dir->d_name);
3062 * We have to do a stat to insure it's
3063 * not a directory or special file.
3065 if (simple || (stat(nbuf, &st) == 0 &&
3066 S_ISREG(st.st_mode))) {
3068 dout = dataconn("file list", (off_t)-1,
3074 if (nbuf[0] == '.' && nbuf[1] == '/')
3075 fprintf(dout, "%s%s\n", &nbuf[2],
3076 type == TYPE_A ? "\r" : "");
3078 fprintf(dout, "%s%s\n", nbuf,
3079 type == TYPE_A ? "\r" : "");
3080 byte_count += strlen(nbuf) + 1;
3083 (void) closedir(dirp);
3087 reply(550, "No files found.");
3088 else if (ferror(dout) != 0)
3089 perror_reply(550, "Data connection");
3091 reply(226, "Transfer complete.");
3095 (void) fclose(dout);
3109 while (wait3(NULL, WNOHANG, NULL) > 0);
3112 #ifdef OLD_SETPROCTITLE
3114 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.)
3115 * Warning, since this is usually started from inetd.conf, it often doesn't
3116 * have much of an environment or arglist to overwrite.
3120 setproctitle(const char *fmt, ...)
3122 setproctitle(fmt, va_alist)
3137 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
3139 /* make ps print our process name */
3144 if (i > LastArgv - p - 2) {
3145 i = LastArgv - p - 2;
3150 if (ch != '\n' && ch != '\r')
3152 while (p < LastArgv)
3155 #endif /* OLD_SETPROCTITLE */
3158 logxfer(name, size, start)
3164 char path[MAXPATHLEN + 1];
3167 if (statfd >= 0 && getwd(path) != NULL) {
3169 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s/%s!%qd!%ld\n",
3170 ctime(&now)+4, ident, remotehost,
3171 path, name, (long long)size,
3172 (long)(now - start + (now == start)));
3173 write(statfd, buf, strlen(buf));
3184 for (p = s, n = 0; *p; p++)
3188 if ((s2 = malloc(p - s + n + 1)) == NULL)
3191 for (p = s2; *s; s++, p++) {
3192 if ((*p = *s) == '"')