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
33 * @(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994 The Regents of the University of California. All rights reserved.
34 * @(#)ftpd.c 8.4 (Berkeley) 4/16/94
38 static const char rcsid[] =
39 "$FreeBSD: src/libexec/ftpd/ftpd.c,v 1.62.2.48 2003/02/14 12:42:42 yar Exp $";
40 "$DragonFly: src/libexec/ftpd/ftpd.c,v 1.7 2005/10/28 18:06:57 joerg Exp $";
46 #include <sys/param.h>
47 #include <sys/ioctl.h>
49 #include <sys/socket.h>
54 #include <netinet/in.h>
55 #include <netinet/in_systm.h>
56 #include <netinet/ip.h>
57 #include <netinet/tcp.h>
61 #include <arpa/inet.h>
62 #include <arpa/telnet.h>
83 #include <login_cap.h>
91 #include <security/pam_appl.h>
94 #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;
119 int hostinfo = 1; /* print host-specific info in messages */
124 int timeout = 900; /* timeout after 15 minutes of inactivity */
125 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
127 int restricted_data_ports = 1;
128 int paranoid = 1; /* be extra careful about security */
129 int anon_only = 0; /* Only anonymous ftp allowed */
137 int stru; /* avoid C keyword */
139 int usedefault = 1; /* for data transfers */
140 int pdata = -1; /* for passive mode */
141 int readonly=0; /* Server is in readonly mode. */
142 int noepsv=0; /* EPSV command is disabled. */
143 int noretr=0; /* RETR command is disabled. */
144 int noguestretr=0; /* RETR command is disabled for anon users. */
145 int noguestmkd=0; /* MKD command is disabled for anon users. */
146 int noguestmod=1; /* anon users may not modify existing files. */
148 static volatile sig_atomic_t recvurg;
149 sig_atomic_t transflag;
152 #if !defined(CMASK) || CMASK == 0
156 int defumask = CMASK; /* default umask value */
161 #ifdef VIRTUAL_HOSTING
164 static struct ftphost {
165 struct ftphost *next;
166 struct addrinfo *hostinfo;
172 } *thishost, *firsthost;
175 char remotehost[MAXHOSTNAMELEN];
178 static char ttyline[20];
179 char *tty = ttyline; /* for klogin */
182 static int auth_pam (struct passwd**, const char*);
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 */
217 #define LOGCMD(cmd, file) \
219 syslog(LOG_INFO,"%s %s%s", cmd, \
220 *(file) == '/' ? "" : curdir(), file);
221 #define LOGCMD2(cmd, file1, file2) \
223 syslog(LOG_INFO,"%s %s%s %s%s", cmd, \
224 *(file1) == '/' ? "" : curdir(), file1, \
225 *(file2) == '/' ? "" : curdir(), file2);
226 #define LOGBYTES(cmd, file, cnt) \
228 if (cnt == (off_t)-1) \
229 syslog(LOG_INFO,"%s %s%s", cmd, \
230 *(file) == '/' ? "" : curdir(), file); \
232 syslog(LOG_INFO, "%s %s%s = %qd bytes", \
233 cmd, (*(file) == '/') ? "" : curdir(), file, cnt); \
236 #ifdef VIRTUAL_HOSTING
237 static void inithosts (void);
238 static void selecthost (union sockunion *);
240 static void ack (char *);
241 static void sigurg (int);
242 static void myoob (void);
243 static int checkuser (char *, char *, int, char **);
244 static FILE *dataconn (char *, off_t, char *);
245 static void dolog (struct sockaddr *);
246 static char *curdir (void);
247 static void end_login (void);
248 static FILE *getdatasock (char *);
249 static int guniquefd (char *, char **);
250 static void lostconn (int);
251 static void sigquit (int);
252 static int receive_data (FILE *, FILE *);
253 static int send_data (FILE *, FILE *, off_t, off_t, int);
254 static struct passwd *
256 static char *sgetsave (char *);
257 static void reapchild (int);
258 static void logxfer (char *, off_t, time_t);
259 static char *doublequote (char *);
264 static char path[MAXPATHLEN+1+1]; /* path + '/' + '\0' */
266 if (getcwd(path, sizeof(path)-2) == NULL)
268 if (path[1] != '\0') /* special case for root dir. */
270 /* For guest account, skip / since it's chrooted */
271 return (guest ? path+1 : path);
275 main(argc, argv, envp)
280 int addrlen, ch, on = 1, tos;
281 char *cp, line[LINE_MAX];
284 char *bindname = NULL;
285 const char *bindport = "ftp";
286 int family = AF_UNSPEC;
290 tzset(); /* in case no timezone database in ~ftp */
291 sigemptyset(&sa.sa_mask);
292 sa.sa_flags = SA_RESTART;
294 #ifdef OLD_SETPROCTITLE
296 * Save start and extent of argv for setproctitle.
301 LastArgv = envp[-1] + strlen(envp[-1]);
302 #endif /* OLD_SETPROCTITLE */
305 while ((ch = getopt(argc, argv,
306 "46a:AdDEH:hlmMoOp:P:rRSt:T:u:UvW")) != -1) {
310 if (family == AF_UNSPEC)
347 logging++; /* > 1 == extra logging */
387 timeout = atoi(optarg);
388 if (maxtimeout < timeout)
389 maxtimeout = timeout;
393 maxtimeout = atoi(optarg);
394 if (timeout > maxtimeout)
395 timeout = maxtimeout;
402 val = strtol(optarg, &optarg, 8);
403 if (*optarg != '\0' || val < 0)
404 warnx("bad value for -u");
410 restricted_data_ports = 0;
422 warnx("unknown flag -%c ignored", optopt);
427 #ifdef VIRTUAL_HOSTING
430 (void) freopen(_PATH_DEVNULL, "w", stderr);
433 * LOG_NDELAY sets up the logging connection immediately,
434 * necessary for anonymous ftp's that chroot and can't do it later.
436 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
440 struct addrinfo hints, *res;
443 * Detach from parent.
445 if (daemon(1, 1) < 0) {
446 syslog(LOG_ERR, "failed to become a daemon");
449 sa.sa_handler = reapchild;
450 (void)sigaction(SIGCHLD, &sa, NULL);
452 memset(&hints, 0, sizeof(hints));
454 hints.ai_family = family == AF_UNSPEC ? AF_INET : family;
455 hints.ai_socktype = SOCK_STREAM;
456 hints.ai_protocol = 0;
457 hints.ai_flags = AI_PASSIVE;
458 error = getaddrinfo(bindname, bindport, &hints, &res);
460 if (family == AF_UNSPEC) {
461 hints.ai_family = AF_UNSPEC;
462 error = getaddrinfo(bindname, bindport, &hints,
467 syslog(LOG_ERR, "%s", gai_strerror(error));
468 if (error == EAI_SYSTEM)
469 syslog(LOG_ERR, "%s", strerror(errno));
472 if (res->ai_addr == NULL) {
473 syslog(LOG_ERR, "-a %s: getaddrinfo failed", hostname);
476 family = res->ai_addr->sa_family;
478 * Open a socket, bind it to the FTP port, and start
481 ctl_sock = socket(family, SOCK_STREAM, 0);
483 syslog(LOG_ERR, "control socket: %m");
486 if (setsockopt(ctl_sock, SOL_SOCKET, SO_REUSEADDR,
487 &on, sizeof(on)) < 0)
489 "control setsockopt (SO_REUSEADDR): %m");
490 if (family == AF_INET6 && enable_v4 == 0) {
491 if (setsockopt(ctl_sock, IPPROTO_IPV6, IPV6_V6ONLY,
492 &on, sizeof (on)) < 0)
494 "control setsockopt (IPV6_V6ONLY): %m");
496 memcpy(&server_addr, res->ai_addr, res->ai_addr->sa_len);
497 if (bind(ctl_sock, (struct sockaddr *)&server_addr,
498 server_addr.su_len) < 0) {
499 syslog(LOG_ERR, "control bind: %m");
502 if (listen(ctl_sock, 32) < 0) {
503 syslog(LOG_ERR, "control listen: %m");
507 * Atomically write process ID
514 fd = open(pid_file, O_CREAT | O_WRONLY | O_TRUNC
515 | O_NONBLOCK | O_EXLOCK, 0644);
518 errx(1, "%s: file locked", pid_file);
520 err(1, "%s", pid_file);
522 snprintf(buf, sizeof(buf),
523 "%lu\n", (unsigned long) getpid());
524 if (write(fd, buf, strlen(buf)) < 0)
525 err(1, "%s: write", pid_file);
526 /* Leave the pid file open and locked */
529 * Loop forever accepting connection requests and forking off
530 * children to handle them.
533 addrlen = server_addr.su_len;
534 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 == NULL) {
652 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
653 fatalerror("Ran out of memory.");
654 gethostname(hostname, MAXHOSTNAMELEN - 1);
655 hostname[MAXHOSTNAMELEN - 1] = '\0';
659 reply(220, "%s FTP server (%s) ready.", hostname, version);
661 reply(220, "FTP server ready.");
673 syslog(LOG_DEBUG, "lost connection");
682 syslog(LOG_ERR, "got signal %d", signo);
686 #ifdef VIRTUAL_HOSTING
688 * read in virtual host tables (if they exist)
697 char *cp, *mp, *line;
698 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
699 struct ftphost *hrp, *lhrp;
700 struct addrinfo hints, *res, *ai;
703 * Fill in the default host information
705 if (hostname == NULL) {
706 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
707 fatalerror("Ran out of memory.");
708 if (gethostname(hostname, MAXHOSTNAMELEN) < 0)
710 hostname[MAXHOSTNAMELEN - 1] = '\0';
712 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
713 fatalerror("Ran out of memory.");
714 hrp->hostname = hostname;
715 hrp->hostinfo = NULL;
717 memset(&hints, 0, sizeof(hints));
718 hints.ai_flags = AI_CANONNAME;
719 hints.ai_family = AF_UNSPEC;
720 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
722 hrp->statfile = _PATH_FTPDSTATFILE;
723 hrp->welcome = _PATH_FTPWELCOME;
724 hrp->loginmsg = _PATH_FTPLOGINMESG;
725 hrp->anonuser = "ftp";
727 thishost = firsthost = lhrp = hrp;
728 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
729 int addrsize, gothost;
733 while ((line = fgetln(fp, &len)) != NULL) {
739 if (line[len - 1] == '\n') {
740 line[len - 1] = '\0';
743 if ((mp = malloc(len + 1)) == NULL)
744 fatalerror("Ran out of memory.");
745 memcpy(mp, line, len);
749 cp = strtok(line, " \t");
750 /* skip empty lines */
757 statfile = _PATH_FTPDSTATFILE;
758 welcome = _PATH_FTPWELCOME;
759 loginmsg = _PATH_FTPLOGINMESG;
762 * Preparse the line so we can use its info
763 * for all the addresses associated with
764 * the virtual host name.
765 * Field 0, the virtual host name, is special:
766 * it's already parsed off and will be strdup'ed
767 * later, after we know its canonical form.
769 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
770 if (*cp != '-' && (cp = strdup(cp)))
772 case 1: /* anon user permissions */
775 case 2: /* statistics file */
778 case 3: /* welcome message */
781 case 4: /* login message */
784 default: /* programming error */
790 hints.ai_family = AF_UNSPEC;
791 hints.ai_flags = AI_PASSIVE;
792 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
794 for (ai = res; ai != NULL && ai->ai_addr != NULL;
798 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
801 for (hi = hrp->hostinfo; hi != NULL;
803 if (hi->ai_addrlen == ai->ai_addrlen &&
806 ai->ai_addr->sa_len) == 0) {
814 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
816 hrp->hostname = NULL;
819 if (hrp->hostinfo && hrp->hostinfo != res)
820 freeaddrinfo(hrp->hostinfo);
821 insert = 0; /* host already in the chain */
826 * determine hostname to use.
827 * force defined name if there is a valid alias
828 * otherwise fallback to primary hostname
830 /* XXX: getaddrinfo() can't do alias check */
831 switch(hrp->hostinfo->ai_family) {
833 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
834 addrsize = sizeof(struct in_addr);
837 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
838 addrsize = sizeof(struct in6_addr);
841 /* should not reach here */
842 freeaddrinfo(hrp->hostinfo);
844 free(hrp); /*not in chain, can free*/
846 hrp->hostinfo = NULL; /*mark as blank*/
850 if ((hp = getipnodebyaddr(addr, addrsize,
851 hrp->hostinfo->ai_family,
852 &hp_error)) != NULL) {
853 if (strcmp(vhost, hp->h_name) != 0) {
854 if (hp->h_aliases == NULL)
858 while (hp->h_aliases[i] &&
859 strcmp(vhost, hp->h_aliases[i]) != 0)
861 if (hp->h_aliases[i] == NULL)
867 strcmp(hrp->hostname, vhost) != 0) {
869 hrp->hostname = NULL;
871 if (hrp->hostname == NULL &&
872 (hrp->hostname = strdup(vhost)) == NULL) {
873 freeaddrinfo(hrp->hostinfo);
874 hrp->hostinfo = NULL; /* mark as blank */
879 hrp->anonuser = anonuser;
880 hrp->statfile = statfile;
881 hrp->welcome = welcome;
882 hrp->loginmsg = loginmsg;
906 struct in6_addr *mapped_in6 = NULL;
912 * XXX IPv4 mapped IPv6 addr consideraton,
913 * specified in rfc2373.
915 if (su->su_family == AF_INET6 &&
916 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
917 mapped_in6 = &su->su_sin6.sin6_addr;
920 hrp = thishost = firsthost; /* default */
923 while (hrp != NULL) {
924 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
925 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
930 /* XXX IPv4 mapped IPv6 addr consideraton */
931 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
932 (memcmp(&mapped_in6->s6_addr[12],
933 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
934 sizeof(struct in_addr)) == 0)) {
943 /* setup static variables as appropriate */
944 hostname = thishost->hostname;
945 ftpuser = thishost->anonuser;
950 * Helper function for sgetpwnam().
956 char *new = malloc((unsigned) strlen(s) + 1);
959 perror_reply(421, "Local resource failure: malloc");
963 (void) strcpy(new, s);
968 * Save the result of a getpwnam. Used for USER command, since
969 * the data returned must not be clobbered by any other command
972 static struct passwd *
976 static struct passwd save;
979 if ((p = getpwnam(name)) == NULL)
983 free(save.pw_passwd);
989 save.pw_name = sgetsave(p->pw_name);
990 save.pw_passwd = sgetsave(p->pw_passwd);
991 save.pw_gecos = sgetsave(p->pw_gecos);
992 save.pw_dir = sgetsave(p->pw_dir);
993 save.pw_shell = sgetsave(p->pw_shell);
997 static int login_attempts; /* number of failed login attempts */
998 static int askpasswd; /* had user command, ask for passwd */
999 static char curname[MAXLOGNAME]; /* current USER name */
1003 * Sets global passwd pointer pw if named account exists and is acceptable;
1004 * sets askpasswd if a PASS command is expected. If logged in previously,
1005 * need to reset state. If name is "ftp" or "anonymous", the name is not in
1006 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
1007 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
1008 * requesting login privileges. Disallow anyone who does not have a standard
1009 * shell as returned by getusershell(). Disallow anyone mentioned in the file
1010 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
1020 reply(530, "Can't change user from guest login.");
1022 } else if (dochroot) {
1023 reply(530, "Can't change user from chroot user.");
1030 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1031 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL) ||
1032 checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL))
1033 reply(530, "User %s access denied.", name);
1034 #ifdef VIRTUAL_HOSTING
1035 else if ((pw = sgetpwnam(thishost->anonuser)) != NULL) {
1037 else if ((pw = sgetpwnam("ftp")) != NULL) {
1042 "Guest login ok, send your email address as password.");
1044 reply(530, "User %s unknown.", name);
1045 if (!askpasswd && logging)
1047 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1050 if (anon_only != 0) {
1051 reply(530, "Sorry, only anonymous ftp allowed.");
1055 if ((pw = sgetpwnam(name))) {
1056 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1057 shell = _PATH_BSHELL;
1058 while ((cp = getusershell()) != NULL)
1059 if (strcmp(cp, shell) == 0)
1063 if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1, NULL)) {
1064 reply(530, "User %s access denied.", name);
1067 "FTP LOGIN REFUSED FROM %s, %s",
1069 pw = (struct passwd *) NULL;
1074 strncpy(curname, name, sizeof(curname)-1);
1076 pwok = skeyaccess(name, NULL, remotehost, remotehost);
1077 reply(331, "%s", skey_challenge(name, pw, pwok));
1079 reply(331, "Password required for %s.", name);
1083 * Delay before reading passwd after first failed
1084 * attempt to slow down passwd-guessing programs.
1087 sleep((unsigned) login_attempts);
1091 * Check if a user is in the file "fname",
1092 * return a pointer to a malloc'd string with the rest
1093 * of the matching line in "residue" if not NULL.
1096 checkuser(fname, name, pwset, residue)
1105 char *line, *mp, *p;
1107 if ((fd = fopen(fname, "r")) != NULL) {
1108 while (!found && (line = fgetln(fd, &len)) != NULL) {
1112 if (line[len - 1] == '\n') {
1113 line[len - 1] = '\0';
1116 if ((mp = malloc(len + 1)) == NULL)
1117 fatalerror("Ran out of memory.");
1118 memcpy(mp, line, len);
1122 /* avoid possible leading and trailing whitespace */
1123 p = strtok(line, " \t");
1124 /* skip empty lines */
1128 * if first chr is '@', check group membership
1134 if (p[1] == '\0') /* single @ matches anyone */
1137 if ((grp = getgrnam(p+1)) == NULL)
1140 * Check user's default group
1142 if (pwset && grp->gr_gid == pw->pw_gid)
1145 * Check supplementary groups
1147 while (!found && grp->gr_mem[i])
1148 found = strcmp(name,
1154 * Otherwise, just check for username match
1157 found = strcmp(p, name) == 0;
1159 * Save the rest of line to "residue" if matched
1161 if (found && residue) {
1162 if ((p = strtok(NULL, "")) != NULL)
1163 p += strspn(p, " \t");
1165 if ((*residue = strdup(p)) == NULL)
1166 fatalerror("Ran out of memory.");
1180 * Terminate login as previous user, if any, resetting state;
1181 * used when USER command is given or login fails.
1187 (void) seteuid((uid_t)0);
1188 if (logged_in && dowtmp)
1189 ftpd_logwtmp(ttyline, "", NULL);
1192 setusercontext(NULL, getpwuid(0), (uid_t)0,
1193 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1203 * the following code is stolen from imap-uw PAM authentication module and
1206 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1209 const char *uname; /* user name */
1210 const char *pass; /* password */
1212 typedef struct cred_t cred_t;
1215 auth_conv(int num_msg, const struct pam_message **msg,
1216 struct pam_response **resp, void *appdata)
1219 cred_t *cred = (cred_t *) appdata;
1220 struct pam_response *reply =
1221 malloc(sizeof(struct pam_response) * num_msg);
1223 for (i = 0; i < num_msg; i++) {
1224 switch (msg[i]->msg_style) {
1225 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1226 reply[i].resp_retcode = PAM_SUCCESS;
1227 reply[i].resp = COPY_STRING(cred->uname);
1228 /* PAM frees resp. */
1230 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1231 reply[i].resp_retcode = PAM_SUCCESS;
1232 reply[i].resp = COPY_STRING(cred->pass);
1233 /* PAM frees resp. */
1237 reply[i].resp_retcode = PAM_SUCCESS;
1238 reply[i].resp = NULL;
1240 default: /* unknown message style */
1242 return PAM_CONV_ERR;
1251 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1252 * authenticated, or 1 if not authenticated. If some sort of PAM system
1253 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1254 * function returns -1. This can be used as an indication that we should
1255 * fall back to a different authentication mechanism.
1258 auth_pam(struct passwd **ppw, const char *pass)
1260 pam_handle_t *pamh = NULL;
1261 const char *tmpl_user;
1265 cred_t auth_cred = { (*ppw)->pw_name, pass };
1266 struct pam_conv conv = { &auth_conv, &auth_cred };
1268 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1269 if (e != PAM_SUCCESS) {
1270 syslog(LOG_ERR, "pam_start: %s", pam_strerror(pamh, e));
1274 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1275 if (e != PAM_SUCCESS) {
1276 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1277 pam_strerror(pamh, e));
1281 e = pam_authenticate(pamh, 0);
1285 * With PAM we support the concept of a "template"
1286 * user. The user enters a login name which is
1287 * authenticated by PAM, usually via a remote service
1288 * such as RADIUS or TACACS+. If authentication
1289 * succeeds, a different but related "template" name
1290 * is used for setting the credentials, shell, and
1291 * home directory. The name the user enters need only
1292 * exist on the remote authentication server, but the
1293 * template name must be present in the local password
1296 * This is supported by two various mechanisms in the
1297 * individual modules. However, from the application's
1298 * point of view, the template user is always passed
1299 * back as a changed value of the PAM_USER item.
1301 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1303 tmpl_user = (const char *) item;
1304 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1305 *ppw = getpwnam(tmpl_user);
1307 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1308 pam_strerror(pamh, e));
1313 case PAM_USER_UNKNOWN:
1319 syslog(LOG_ERR, "auth_pam: %s", pam_strerror(pamh, e));
1324 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1325 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1331 #endif /* !defined(NOPAM) */
1340 login_cap_t *lc = NULL;
1343 char *residue = NULL;
1345 if (logged_in || askpasswd == 0) {
1346 reply(503, "Login with USER first.");
1350 if (!guest) { /* "ftp" is only account allowed no password */
1352 rval = 1; /* failure below */
1356 rval = auth_pam(&pw, passwd);
1362 rval = strcmp(pw->pw_passwd,
1363 crypt(passwd, pw->pw_passwd));
1365 rval = strcmp(pw->pw_passwd,
1366 skey_crypt(passwd, pw->pw_passwd, pw, pwok));
1368 rval = strcmp(pw->pw_passwd, crypt(passwd, pw->pw_passwd));
1370 /* The strcmp does not catch null passwords! */
1371 if (*pw->pw_passwd == '\0' ||
1372 (pw->pw_expire && time(NULL) >= pw->pw_expire))
1373 rval = 1; /* failure */
1376 * If rval == 1, the user failed the authentication check
1377 * above. If rval == 0, either PAM or local authentication
1381 reply(530, "Login incorrect.");
1384 "FTP LOGIN FAILED FROM %s",
1386 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1387 "FTP LOGIN FAILED FROM %s, %s",
1388 remotehost, curname);
1391 if (login_attempts++ >= 5) {
1393 "repeated login failures from %s",
1403 login_attempts = 0; /* this time successful */
1404 if (setegid((gid_t)pw->pw_gid) < 0) {
1405 reply(550, "Can't set gid.");
1408 /* May be overridden by login.conf */
1409 (void) umask(defumask);
1411 if ((lc = login_getpwclass(pw)) != NULL) {
1412 char remote_ip[MAXHOSTNAMELEN];
1414 getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1415 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1417 remote_ip[sizeof(remote_ip) - 1] = 0;
1418 if (!auth_hostok(lc, remotehost, remote_ip)) {
1419 syslog(LOG_INFO|LOG_AUTH,
1420 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1422 reply(530, "Permission denied.\n");
1426 if (!auth_timeok(lc, time(NULL))) {
1427 reply(530, "Login not available right now.\n");
1432 setusercontext(lc, pw, (uid_t)0,
1433 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1434 LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1436 setlogin(pw->pw_name);
1437 (void) initgroups(pw->pw_name, pw->pw_gid);
1440 /* open wtmp before chroot */
1442 ftpd_logwtmp(ttyline, pw->pw_name,
1443 (struct sockaddr *)&his_addr);
1446 if (guest && stats && statfd < 0)
1447 #ifdef VIRTUAL_HOSTING
1448 if ((statfd = open(thishost->statfile, O_WRONLY|O_APPEND)) < 0)
1450 if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0)
1455 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue)
1456 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1457 || login_getcapbool(lc, "ftp-chroot", 0)
1462 * For a chrooted local user,
1463 * a) see whether ftpchroot(5) specifies a chroot directory,
1464 * b) extract the directory pathname from the line,
1465 * c) expand it to the absolute pathname if necessary.
1467 if (dochroot && residue &&
1468 (chrootdir = strtok(residue, " \t")) != NULL &&
1469 chrootdir[0] != '/') {
1470 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1471 if (chrootdir == NULL)
1472 fatalerror("Ran out of memory.");
1474 if (guest || dochroot) {
1476 * If no chroot directory set yet, use the login directory.
1477 * Copy it so it can be modified while pw->pw_dir stays intact.
1479 if (chrootdir == NULL &&
1480 (chrootdir = strdup(pw->pw_dir)) == NULL)
1481 fatalerror("Ran out of memory.");
1483 * Check for the "/chroot/./home" syntax,
1484 * separate the chroot and home directory pathnames.
1486 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1487 *(homedir++) = '\0'; /* wipe '/' */
1488 homedir++; /* skip '.' */
1489 /* so chrootdir can be freed later */
1490 if ((homedir = strdup(homedir)) == NULL)
1491 fatalerror("Ran out of memory.");
1494 * We MUST do a chdir() after the chroot. Otherwise
1495 * the old current directory will be accessible as "."
1496 * outside the new root!
1501 * Finally, do chroot()
1503 if (chroot(chrootdir) < 0) {
1504 reply(550, "Can't change root.");
1507 } else /* real user w/o chroot */
1508 homedir = pw->pw_dir;
1510 * Set euid *before* doing chdir() so
1511 * a) the user won't be carried to a directory that he couldn't reach
1512 * on his own due to no permission to upper path components,
1513 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1514 * (uid 0 has no root power over NFS if not mapped explicitly.)
1516 if (seteuid((uid_t)pw->pw_uid) < 0) {
1517 reply(550, "Can't set uid.");
1520 if (chdir(homedir) < 0) {
1521 if (guest || dochroot) {
1522 reply(550, "Can't change to base directory.");
1525 if (chdir("/") < 0) {
1526 reply(550, "Root is inaccessible.");
1529 lreply(230, "No directory! Logging in with home=/");
1534 * Display a login message, if it exists.
1535 * N.B. reply(230,) must follow the message.
1537 #ifdef VIRTUAL_HOSTING
1538 if ((fd = fopen(thishost->loginmsg, "r")) != NULL) {
1540 if ((fd = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) {
1542 char *cp, line[LINE_MAX];
1544 while (fgets(line, sizeof(line), fd) != NULL) {
1545 if ((cp = strchr(line, '\n')) != NULL)
1547 lreply(230, "%s", line);
1549 (void) fflush(stdout);
1555 ident = strdup(passwd);
1557 fatalerror("Ran out of memory.");
1559 reply(230, "Guest login ok, access restrictions apply.");
1561 #ifdef VIRTUAL_HOSTING
1562 if (thishost != firsthost)
1563 snprintf(proctitle, sizeof(proctitle),
1564 "%s: anonymous(%s)/%s", remotehost, hostname,
1568 snprintf(proctitle, sizeof(proctitle),
1569 "%s: anonymous/%s", remotehost, passwd);
1570 setproctitle("%s", proctitle);
1571 #endif /* SETPROCTITLE */
1573 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1574 remotehost, passwd);
1577 reply(230, "User %s logged in, "
1578 "access restrictions apply.", pw->pw_name);
1580 reply(230, "User %s logged in.", pw->pw_name);
1583 snprintf(proctitle, sizeof(proctitle),
1584 "%s: user/%s", remotehost, pw->pw_name);
1585 setproctitle("%s", proctitle);
1586 #endif /* SETPROCTITLE */
1588 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1589 remotehost, pw->pw_name);
1600 /* Forget all about it... */
1617 int (*closefunc) (FILE *);
1621 fin = fopen(name, "r"), closefunc = fclose;
1626 (void) snprintf(line, sizeof(line), cmd, name), name = line;
1627 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1629 st.st_blksize = BUFSIZ;
1633 perror_reply(550, name);
1635 LOGCMD("get", name);
1642 if (fstat(fileno(fin), &st) < 0) {
1643 perror_reply(550, name);
1646 if (!S_ISREG(st.st_mode)) {
1648 reply(550, "%s: not a plain file.", name);
1652 /* st.st_blksize is set for all descriptor types */
1655 if (restart_point) {
1656 if (type == TYPE_A) {
1663 if ((c=getc(fin)) == EOF) {
1664 perror_reply(550, name);
1670 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1671 perror_reply(550, name);
1675 dout = dataconn(name, st.st_size, "w");
1679 send_data(fin, dout, st.st_blksize, st.st_size,
1680 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1681 if (cmd == 0 && guest && stats)
1682 logxfer(name, st.st_size, start);
1683 (void) fclose(dout);
1688 LOGBYTES("get", name, byte_count);
1693 store(name, mode, unique)
1699 int (*closefunc) (FILE *);
1701 if (*mode == 'a') { /* APPE */
1703 /* Programming error */
1704 syslog(LOG_ERR, "Internal: unique flag to APPE");
1707 if (guest && noguestmod) {
1708 reply(550, "Appending to existing file denied");
1711 restart_point = 0; /* not affected by preceding REST */
1713 if (unique) /* STOU overrides REST */
1715 if (guest && noguestmod) {
1716 if (restart_point) { /* guest STOR w/REST */
1717 reply(550, "Modifying existing file denied");
1719 } else /* treat guest STOR as STOU */
1724 mode = "r+"; /* so ASCII manual seek can work */
1726 if ((fd = guniquefd(name, &name)) < 0)
1728 fout = fdopen(fd, mode);
1730 fout = fopen(name, mode);
1733 perror_reply(553, name);
1737 if (restart_point) {
1738 if (type == TYPE_A) {
1745 if ((c=getc(fout)) == EOF) {
1746 perror_reply(550, name);
1753 * We must do this seek to "current" position
1754 * because we are changing from reading to
1757 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1758 perror_reply(550, name);
1761 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1762 perror_reply(550, name);
1766 din = dataconn(name, (off_t)-1, "r");
1769 if (receive_data(din, fout) == 0) {
1771 reply(226, "Transfer complete (unique file name:%s).",
1774 reply(226, "Transfer complete.");
1780 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1784 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1792 int on = 1, s, t, tries;
1795 return (fdopen(data, mode));
1797 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1800 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1801 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1802 /* anchor socket to avoid multi-homing problems */
1803 data_source = ctrl_addr;
1804 data_source.su_port = htons(dataport);
1805 (void) seteuid((uid_t)0);
1806 for (tries = 1; ; tries++) {
1807 if (bind(s, (struct sockaddr *)&data_source,
1808 data_source.su_len) >= 0)
1810 if (errno != EADDRINUSE || tries > 10)
1814 (void) seteuid((uid_t)pw->pw_uid);
1816 if (data_source.su_family == AF_INET)
1818 on = IPTOS_THROUGHPUT;
1819 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1820 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1825 * Turn off push flag to keep sender TCP from sending short packets
1826 * at the boundaries of each write(). Should probably do a SO_SNDBUF
1827 * to set the send buffer size as well, but that may not be desirable
1828 * in heavy-load situations.
1831 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1832 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1836 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &on, sizeof on) < 0)
1837 syslog(LOG_WARNING, "data setsockopt (SO_SNDBUF): %m");
1840 return (fdopen(s, mode));
1842 /* Return the real value of errno (close may change it) */
1844 (void) seteuid((uid_t)pw->pw_uid);
1851 dataconn(name, size, mode)
1858 int retry = 0, tos, conerrno;
1862 if (size != (off_t) -1)
1863 (void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)", size);
1867 union sockunion from;
1869 int s, fromlen = ctrl_addr.su_len;
1870 struct timeval timeout;
1874 FD_SET(pdata, &set);
1876 timeout.tv_usec = 0;
1877 timeout.tv_sec = 120;
1880 * Granted a socket is in the blocking I/O mode,
1881 * accept() will block after a successful select()
1882 * if the selected connection dies in between.
1883 * Therefore set the non-blocking I/O flag here.
1885 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1886 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1888 if (select(pdata+1, &set, (fd_set *) 0, (fd_set *) 0, &timeout) <= 0 ||
1889 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1891 (void) close(pdata);
1894 * Unset the inherited non-blocking I/O flag
1895 * on the child socket so stdio can work on it.
1897 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1898 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1901 if (from.su_family == AF_INET)
1903 tos = IPTOS_THROUGHPUT;
1904 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1905 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1908 reply(150, "Opening %s mode data connection for '%s'%s.",
1909 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1910 return (fdopen(pdata, mode));
1912 reply(425, "Can't open data connection.");
1913 (void) close(pdata);
1918 reply(125, "Using existing data connection for '%s'%s.",
1921 return (fdopen(data, mode));
1924 data_dest = his_addr;
1927 file = getdatasock(mode);
1929 char hostbuf[BUFSIZ], portbuf[BUFSIZ];
1930 getnameinfo((struct sockaddr *)&data_source,
1931 data_source.su_len, hostbuf, sizeof(hostbuf) - 1,
1932 portbuf, sizeof(portbuf),
1933 NI_NUMERICHOST|NI_NUMERICSERV);
1934 reply(425, "Can't create data socket (%s,%s): %s.",
1935 hostbuf, portbuf, strerror(errno));
1938 data = fileno(file);
1940 if (connect(data, (struct sockaddr *)&data_dest,
1941 data_dest.su_len) == 0)
1944 (void) fclose(file);
1946 if (conerrno == EADDRINUSE) {
1947 sleep((unsigned) swaitint);
1952 } while (retry <= swaitmax);
1953 if (conerrno != 0) {
1954 perror_reply(425, "Can't build data connection");
1957 reply(150, "Opening %s mode data connection for '%s'%s.",
1958 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1963 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1964 * encapsulation of the data subject to Mode, Structure, and Type.
1966 * NB: Form isn't handled.
1969 send_data(instr, outstr, blksize, filesize, isreg)
1970 FILE *instr, *outstr;
1975 int c, filefd, netfd;
1983 while ((c = getc(instr)) != EOF) {
1990 (void) putc('\r', outstr);
1992 (void) putc(c, outstr);
2002 reply(226, "Transfer complete.");
2008 * isreg is only set if we are not doing restart and we
2009 * are sending a regular file
2011 netfd = fileno(outstr);
2012 filefd = fileno(instr);
2019 err = cnt = offset = 0;
2021 while (err != -1 && filesize > 0) {
2022 err = sendfile(filefd, netfd, offset, 0,
2023 (struct sf_hdtr *) NULL, &cnt, 0);
2025 * Calculate byte_count before OOB processing.
2026 * It can be used in myoob() later.
2043 reply(226, "Transfer complete.");
2048 if ((buf = malloc((u_int)blksize)) == NULL) {
2050 perror_reply(451, "Local resource failure: malloc");
2054 while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
2055 write(netfd, buf, cnt) == cnt)
2064 reply(226, "Transfer complete.");
2068 reply(550, "Unimplemented TYPE %d in send_data", type);
2074 perror_reply(426, "Data connection");
2079 perror_reply(551, "Error on input file");
2090 * Transfer data from peer to "outstr" using the appropriate encapulation of
2091 * the data subject to Mode, Structure, and Type.
2093 * N.B.: Form isn't handled.
2096 receive_data(instr, outstr)
2097 FILE *instr, *outstr;
2110 while ((cnt = read(fileno(instr), buf, sizeof(buf))) > 0) {
2113 if (write(fileno(outstr), buf, cnt) != cnt)
2125 reply(553, "TYPE E not implemented.");
2130 while ((c = getc(instr)) != EOF) {
2139 if ((c = getc(instr)) != '\n') {
2140 (void) putc ('\r', outstr);
2141 if (c == '\0' || c == EOF)
2145 (void) putc(c, outstr);
2158 "WARNING! %d bare linefeeds received in ASCII mode",
2160 (void)printf(" File may not have transferred correctly.\r\n");
2164 reply(550, "Unimplemented TYPE %d in receive_data", type);
2171 perror_reply(426, "Data Connection");
2176 perror_reply(452, "Error writing file");
2187 statfilecmd(filename)
2193 char line[LINE_MAX];
2195 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2196 fin = ftpd_popen(line, "r");
2197 lreply(211, "status of %s:", filename);
2199 while ((c = getc(fin)) != EOF) {
2201 if (ferror(stdout)){
2202 perror_reply(421, "control connection");
2203 (void) ftpd_pclose(fin);
2208 perror_reply(551, filename);
2209 (void) ftpd_pclose(fin);
2212 (void) putc('\r', stdout);
2215 * RFC 959 says neutral text should be prepended before
2216 * a leading 3-digit number followed by whitespace, but
2217 * many ftp clients can be confused by any leading digits,
2218 * as a matter of fact.
2220 if (atstart && isdigit(c))
2221 (void) putc(' ', stdout);
2222 (void) putc(c, stdout);
2223 atstart = (c == '\n');
2225 (void) ftpd_pclose(fin);
2226 reply(211, "End of Status");
2232 union sockunion *su;
2234 char hname[NI_MAXHOST];
2238 lreply(211, "%s FTP server status:", hostname);
2239 printf(" %s\r\n", version);
2241 lreply(211, "FTP server status:");
2242 printf(" Connected to %s", remotehost);
2243 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2244 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2245 if (strcmp(hname, remotehost) != 0)
2246 printf(" (%s)", hname);
2251 printf(" Logged in anonymously\r\n");
2253 printf(" Logged in as %s\r\n", pw->pw_name);
2254 } else if (askpasswd)
2255 printf(" Waiting for password\r\n");
2257 printf(" Waiting for user name\r\n");
2258 printf(" TYPE: %s", typenames[type]);
2259 if (type == TYPE_A || type == TYPE_E)
2260 printf(", FORM: %s", formnames[form]);
2263 printf(" %d", NBBY);
2265 printf(" %d", bytesize); /* need definition! */
2267 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2268 strunames[stru], modenames[mode]);
2270 printf(" Data connection open\r\n");
2271 else if (pdata != -1) {
2275 } else if (usedefault == 0) {
2279 #define UC(b) (((int) b) & 0xff)
2281 printf(" EPSV only mode (EPSV ALL)\r\n");
2286 if (su->su_family == AF_INET) {
2287 a = (u_char *) &su->su_sin.sin_addr;
2288 p = (u_char *) &su->su_sin.sin_port;
2289 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2290 ispassive ? "PASV" : "PORT",
2291 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2292 UC(p[0]), UC(p[1]));
2299 switch (su->su_family) {
2301 a = (u_char *) &su->su_sin.sin_addr;
2302 p = (u_char *) &su->su_sin.sin_port;
2303 alen = sizeof(su->su_sin.sin_addr);
2307 a = (u_char *) &su->su_sin6.sin6_addr;
2308 p = (u_char *) &su->su_sin6.sin6_port;
2309 alen = sizeof(su->su_sin6.sin6_addr);
2317 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2319 for (i = 0; i < alen; i++)
2320 printf("%d,", UC(a[i]));
2321 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2330 switch (su->su_family) {
2342 union sockunion tmp;
2345 if (tmp.su_family == AF_INET6)
2346 tmp.su_sin6.sin6_scope_id = 0;
2347 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2348 hname, sizeof(hname) - 1, NULL, 0,
2350 printf(" %s |%d|%s|%d|\r\n",
2351 ispassive ? "EPSV" : "EPRT",
2352 af, hname, htons(tmp.su_port));
2358 printf(" No data connection\r\n");
2359 reply(211, "End of status");
2367 reply(451, "Error in server: %s\n", s);
2368 reply(221, "Closing connection due to server error.");
2375 reply(int n, const char *fmt, ...)
2377 reply(n, fmt, va_alist)
2389 (void)printf("%d ", n);
2390 (void)vprintf(fmt, ap);
2391 (void)printf("\r\n");
2392 (void)fflush(stdout);
2394 syslog(LOG_DEBUG, "<--- %d ", n);
2395 vsyslog(LOG_DEBUG, fmt, ap);
2401 lreply(int n, const char *fmt, ...)
2403 lreply(n, fmt, va_alist)
2415 (void)printf("%d- ", n);
2416 (void)vprintf(fmt, ap);
2417 (void)printf("\r\n");
2418 (void)fflush(stdout);
2420 syslog(LOG_DEBUG, "<--- %d- ", n);
2421 vsyslog(LOG_DEBUG, fmt, ap);
2430 reply(250, "%s command successful.", s);
2438 reply(502, "%s command not implemented.", s);
2448 if ((cp = strchr(cbuf,'\n')))
2450 reply(500, "'%s': command not understood.", cbuf);
2459 LOGCMD("delete", name);
2460 if (lstat(name, &st) < 0) {
2461 perror_reply(550, name);
2464 if ((st.st_mode&S_IFMT) == S_IFDIR) {
2465 if (rmdir(name) < 0) {
2466 perror_reply(550, name);
2471 if (unlink(name) < 0) {
2472 perror_reply(550, name);
2484 if (chdir(path) < 0)
2485 perror_reply(550, path);
2496 LOGCMD("mkdir", name);
2497 if (guest && noguestmkd)
2498 reply(550, "%s: permission denied", name);
2499 else if (mkdir(name, 0777) < 0)
2500 perror_reply(550, name);
2502 if ((s = doublequote(name)) == NULL)
2503 fatalerror("Ran out of memory.");
2504 reply(257, "\"%s\" directory created.", s);
2514 LOGCMD("rmdir", name);
2515 if (rmdir(name) < 0)
2516 perror_reply(550, name);
2524 char *s, path[MAXPATHLEN + 1];
2526 if (getwd(path) == (char *)NULL)
2527 reply(550, "%s.", path);
2529 if ((s = doublequote(path)) == NULL)
2530 fatalerror("Ran out of memory.");
2531 reply(257, "\"%s\" is current directory.", s);
2542 if (lstat(name, &st) < 0) {
2543 perror_reply(550, name);
2546 reply(350, "File exists, ready for destination name");
2556 LOGCMD2("rename", from, to);
2558 if (guest && (stat(to, &st) == 0)) {
2559 reply(550, "%s: permission denied", to);
2563 if (rename(from, to) < 0)
2564 perror_reply(550, "rename");
2571 struct sockaddr *who;
2575 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2578 #ifdef VIRTUAL_HOSTING
2579 if (thishost != firsthost)
2580 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2581 remotehost, hostname);
2584 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2586 setproctitle("%s", proctitle);
2587 #endif /* SETPROCTITLE */
2590 #ifdef VIRTUAL_HOSTING
2591 if (thishost != firsthost)
2592 syslog(LOG_INFO, "connection from %s (to %s)",
2593 remotehost, hostname);
2597 char who_name[MAXHOSTNAMELEN];
2599 error = getnameinfo(who, who->sa_len,
2600 who_name, sizeof(who_name) - 1,
2601 NULL, 0, NI_NUMERICHOST);
2602 syslog(LOG_INFO, "connection from %s (%s)", remotehost,
2603 error == 0 ? who_name : "");
2609 * Record logout in wtmp file
2610 * and exit with supplied status.
2617 * Prevent reception of SIGURG from resulting in a resumption
2618 * back to the main program loop.
2622 if (logged_in && dowtmp) {
2623 (void) seteuid((uid_t)0);
2624 ftpd_logwtmp(ttyline, "", NULL);
2626 /* beware of flushing buffers after a SIGPIPE */
2643 /* only process if transfer occurring */
2647 if (getline(cp, 7, stdin) == NULL) {
2648 reply(221, "You could at least say goodbye.");
2652 if (strcmp(cp, "ABOR\r\n") == 0) {
2654 reply(426, "Transfer aborted. Data connection closed.");
2655 reply(226, "Abort successful");
2657 if (strcmp(cp, "STAT\r\n") == 0) {
2659 if (file_size != (off_t) -1)
2660 reply(213, "Status: %qd of %qd bytes transferred",
2661 byte_count, file_size);
2663 reply(213, "Status: %qd bytes transferred", byte_count);
2668 * Note: a response of 425 is not mentioned as a possible response to
2669 * the PASV command in RFC959. However, it has been blessed as
2670 * a legitimate response by Jon Postel in a telephone conversation
2671 * with Rick Adams on 25 Jan 89.
2679 if (pdata >= 0) /* close old port if one set */
2682 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2684 perror_reply(425, "Can't open passive connection");
2688 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2689 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2691 (void) seteuid((uid_t)0);
2694 if (ctrl_addr.su_family == AF_INET) {
2695 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2696 : IP_PORTRANGE_DEFAULT;
2698 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2699 &on, sizeof(on)) < 0)
2703 #ifdef IPV6_PORTRANGE
2704 if (ctrl_addr.su_family == AF_INET6) {
2705 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2706 : IPV6_PORTRANGE_DEFAULT;
2708 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2709 &on, sizeof(on)) < 0)
2714 pasv_addr = ctrl_addr;
2715 pasv_addr.su_port = 0;
2716 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2719 (void) seteuid((uid_t)pw->pw_uid);
2721 len = sizeof(pasv_addr);
2722 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2724 if (listen(pdata, 1) < 0)
2726 if (pasv_addr.su_family == AF_INET)
2727 a = (char *) &pasv_addr.su_sin.sin_addr;
2728 else if (pasv_addr.su_family == AF_INET6 &&
2729 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2730 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2734 p = (char *) &pasv_addr.su_port;
2736 #define UC(b) (((int) b) & 0xff)
2738 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2739 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2743 (void) seteuid((uid_t)pw->pw_uid);
2744 (void) close(pdata);
2746 perror_reply(425, "Can't open passive connection");
2751 * Long Passive defined in RFC 1639.
2752 * 228 Entering Long Passive Mode
2753 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2757 long_passive(cmd, pf)
2764 if (pdata >= 0) /* close old port if one set */
2767 if (pf != PF_UNSPEC) {
2768 if (ctrl_addr.su_family != pf) {
2769 switch (ctrl_addr.su_family) {
2782 * only EPRT/EPSV ready clients will understand this
2784 if (strcmp(cmd, "EPSV") == 0 && pf) {
2785 reply(522, "Network protocol mismatch, "
2788 reply(501, "Network protocol mismatch"); /*XXX*/
2794 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2796 perror_reply(425, "Can't open passive connection");
2800 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2801 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2803 (void) seteuid((uid_t)0);
2805 pasv_addr = ctrl_addr;
2806 pasv_addr.su_port = 0;
2807 len = pasv_addr.su_len;
2810 if (ctrl_addr.su_family == AF_INET) {
2811 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2812 : IP_PORTRANGE_DEFAULT;
2814 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2815 &on, sizeof(on)) < 0)
2819 #ifdef IPV6_PORTRANGE
2820 if (ctrl_addr.su_family == AF_INET6) {
2821 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2822 : IPV6_PORTRANGE_DEFAULT;
2824 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2825 &on, sizeof(on)) < 0)
2830 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2833 (void) seteuid((uid_t)pw->pw_uid);
2835 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2837 if (listen(pdata, 1) < 0)
2840 #define UC(b) (((int) b) & 0xff)
2842 if (strcmp(cmd, "LPSV") == 0) {
2843 p = (char *)&pasv_addr.su_port;
2844 switch (pasv_addr.su_family) {
2846 a = (char *) &pasv_addr.su_sin.sin_addr;
2849 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2850 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2851 2, UC(p[0]), UC(p[1]));
2854 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
2855 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2858 a = (char *) &pasv_addr.su_sin6.sin6_addr;
2860 "Entering Long Passive Mode "
2861 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2862 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2863 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2864 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2865 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2866 2, UC(p[0]), UC(p[1]));
2869 } else if (strcmp(cmd, "EPSV") == 0) {
2870 switch (pasv_addr.su_family) {
2873 reply(229, "Entering Extended Passive Mode (|||%d|)",
2874 ntohs(pasv_addr.su_port));
2878 /* more proper error code? */
2882 (void) seteuid((uid_t)pw->pw_uid);
2883 (void) close(pdata);
2885 perror_reply(425, "Can't open passive connection");
2890 * Generate unique name for file with basename "local"
2891 * and open the file in order to avoid possible races.
2892 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
2893 * Return descriptor to the file, set "name" to its name.
2895 * Generates failure reply on error.
2898 guniquefd(local, name)
2902 static char new[MAXPATHLEN];
2908 cp = strrchr(local, '/');
2911 if (stat(cp ? local : ".", &st) < 0) {
2912 perror_reply(553, cp ? local : ".");
2917 * Let not overwrite dirname with counter suffix.
2919 * In this extreme case dot won't be put in front of suffix.
2921 if (strlen(local) > sizeof(new) - 4) {
2922 reply(553, "Pathname too long");
2927 /* -4 is for the .nn<null> we put on the end below */
2928 (void) snprintf(new, sizeof(new) - 4, "%s", local);
2929 cp = new + strlen(new);
2931 * Don't generate dotfile unless requested explicitly.
2932 * This covers the case when basename gets truncated off
2935 if (cp > new && cp[-1] != '/')
2937 for (count = 0; count < 100; count++) {
2938 /* At count 0 try unmodified name */
2940 (void)sprintf(cp, "%d", count);
2941 if ((fd = open(count ? new : local,
2942 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
2943 *name = count ? new : local;
2946 if (errno != EEXIST) {
2947 perror_reply(553, count ? new : local);
2951 reply(452, "Unique file name cannot be created.");
2956 * Format and send reply containing system error number.
2959 perror_reply(code, string)
2964 reply(code, "%s: %s.", string, strerror(errno));
2967 static char *onefile[] = {
2973 send_file_list(whichf)
2980 char **dirlist, *dirname;
2985 if (strpbrk(whichf, "~{[*?") != NULL) {
2986 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
2988 memset(&gl, 0, sizeof(gl));
2989 gl.gl_matchc = MAXGLOBARGS;
2990 flags |= GLOB_LIMIT;
2992 if (glob(whichf, flags, 0, &gl)) {
2993 reply(550, "not found");
2995 } else if (gl.gl_pathc == 0) {
2997 perror_reply(550, whichf);
3000 dirlist = gl.gl_pathv;
3002 onefile[0] = whichf;
3007 while ((dirname = *dirlist++)) {
3008 if (stat(dirname, &st) < 0) {
3010 * If user typed "ls -l", etc, and the client
3011 * used NLST, do what the user meant.
3013 if (dirname[0] == '-' && *dirlist == NULL &&
3015 retrieve(_PATH_LS " %s", dirname);
3018 perror_reply(550, whichf);
3020 (void) fclose(dout);
3028 if (S_ISREG(st.st_mode)) {
3030 dout = dataconn("file list", (off_t)-1, "w");
3035 fprintf(dout, "%s%s\n", dirname,
3036 type == TYPE_A ? "\r" : "");
3037 byte_count += strlen(dirname) + 1;
3039 } else if (!S_ISDIR(st.st_mode))
3042 if ((dirp = opendir(dirname)) == NULL)
3045 while ((dir = readdir(dirp)) != NULL) {
3046 char nbuf[MAXPATHLEN];
3055 if (strcmp(dir->d_name, ".") == 0)
3057 if (strcmp(dir->d_name, "..") == 0)
3060 snprintf(nbuf, sizeof(nbuf),
3061 "%s/%s", dirname, dir->d_name);
3064 * We have to do a stat to insure it's
3065 * not a directory or special file.
3067 if (simple || (stat(nbuf, &st) == 0 &&
3068 S_ISREG(st.st_mode))) {
3070 dout = dataconn("file list", (off_t)-1,
3076 if (nbuf[0] == '.' && nbuf[1] == '/')
3077 fprintf(dout, "%s%s\n", &nbuf[2],
3078 type == TYPE_A ? "\r" : "");
3080 fprintf(dout, "%s%s\n", nbuf,
3081 type == TYPE_A ? "\r" : "");
3082 byte_count += strlen(nbuf) + 1;
3085 (void) closedir(dirp);
3089 reply(550, "No files found.");
3090 else if (ferror(dout) != 0)
3091 perror_reply(550, "Data connection");
3093 reply(226, "Transfer complete.");
3097 (void) fclose(dout);
3111 while (wait3(NULL, WNOHANG, NULL) > 0);
3114 #ifdef OLD_SETPROCTITLE
3116 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.)
3117 * Warning, since this is usually started from inetd.conf, it often doesn't
3118 * have much of an environment or arglist to overwrite.
3122 setproctitle(const char *fmt, ...)
3124 setproctitle(fmt, va_alist)
3139 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
3141 /* make ps print our process name */
3146 if (i > LastArgv - p - 2) {
3147 i = LastArgv - p - 2;
3152 if (ch != '\n' && ch != '\r')
3154 while (p < LastArgv)
3157 #endif /* OLD_SETPROCTITLE */
3160 logxfer(name, size, start)
3166 char path[MAXPATHLEN + 1];
3169 if (statfd >= 0 && getwd(path) != NULL) {
3171 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s/%s!%qd!%ld\n",
3172 ctime(&now)+4, ident, remotehost,
3173 path, name, (long long)size,
3174 (long)(now - start + (now == start)));
3175 write(statfd, buf, strlen(buf));
3186 for (p = s, n = 0; *p; p++)
3190 if ((s2 = malloc(p - s + n + 1)) == NULL)
3193 for (p = s2; *s; s++, p++) {
3194 if ((*p = *s) == '"')