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. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 static char copyright[] =
33 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
34 The Regents of the University of California. All rights reserved.\n";
40 static char sccsid[] = "@(#)ftpd.c 8.4 (Berkeley) 4/16/94";
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
50 #include <sys/param.h>
51 #include <sys/ioctl.h>
53 #include <sys/socket.h>
58 #include <netinet/in.h>
59 #include <netinet/in_systm.h>
60 #include <netinet/ip.h>
61 #include <netinet/tcp.h>
65 #include <arpa/inet.h>
66 #include <arpa/telnet.h>
89 #include <login_cap.h>
93 #include <security/pam_appl.h>
96 #include "blacklist_client.h"
97 #include "pathnames.h"
102 static char version[] = "Version 6.00LS";
105 union sockunion ctrl_addr;
106 union sockunion data_source;
107 union sockunion data_dest;
108 union sockunion his_addr;
109 union sockunion pasv_addr;
114 int hostinfo = 1; /* print host-specific info in messages */
119 int timeout = 900; /* timeout after 15 minutes of inactivity */
120 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
122 int restricted_data_ports = 1;
123 int paranoid = 1; /* be extra careful about security */
124 int anon_only = 0; /* Only anonymous ftp allowed */
125 int assumeutf8 = 0; /* Assume that server file names are in UTF-8 */
134 int stru; /* avoid C keyword */
136 int usedefault = 1; /* for data transfers */
137 int pdata = -1; /* for passive mode */
138 int readonly = 0; /* Server is in readonly mode. */
139 int noepsv = 0; /* EPSV command is disabled. */
140 int noretr = 0; /* RETR command is disabled. */
141 int noguestretr = 0; /* RETR command is disabled for anon users. */
142 int noguestmkd = 0; /* MKD command is disabled for anon users. */
143 int noguestmod = 1; /* anon users may not modify existing files. */
144 int use_blacklist = 0;
148 #if !defined(CMASK) || CMASK == 0
152 int defumask = CMASK; /* default umask value */
157 #ifdef VIRTUAL_HOSTING
160 static struct ftphost {
161 struct ftphost *next;
162 struct addrinfo *hostinfo;
168 } *thishost, *firsthost;
171 char remotehost[NI_MAXHOST];
174 static char wtmpid[20];
177 static int auth_pam(struct passwd**, const char*);
178 pam_handle_t *pamh = NULL;
181 static struct opie opiedata;
182 static char opieprompt[OPIE_CHALLENGE_MAX+1];
185 char *pid_file = NULL; /* means default location to pidfile(3) */
188 * Limit number of pathnames that glob can return.
189 * A limit of 0 indicates the number of pathnames is unlimited.
191 #define MAXGLOBARGS 16384
195 * Timeout intervals for retrying connections
196 * to hosts that don't accept PORT cmds. This
197 * is a kludge, but given the problems with TCP...
199 #define SWAITMAX 90 /* wait at most 90 seconds */
200 #define SWAITINT 5 /* interval between retries */
202 int swaitmax = SWAITMAX;
203 int swaitint = SWAITINT;
206 #ifdef OLD_SETPROCTITLE
207 char **Argv = NULL; /* pointer to argument vector */
208 char *LastArgv = NULL; /* end of argv */
209 #endif /* OLD_SETPROCTITLE */
210 char proctitle[LINE_MAX]; /* initial part of title */
211 #endif /* SETPROCTITLE */
213 #define LOGCMD(cmd, file) logcmd((cmd), (file), NULL, -1)
214 #define LOGCMD2(cmd, file1, file2) logcmd((cmd), (file1), (file2), -1)
215 #define LOGBYTES(cmd, file, cnt) logcmd((cmd), (file), NULL, (cnt))
217 static volatile sig_atomic_t recvurg;
218 static int transflag; /* NB: for debugging only */
220 #define STARTXFER flagxfer(1)
221 #define ENDXFER flagxfer(0)
223 #define START_UNSAFE maskurg(1)
224 #define END_UNSAFE maskurg(0)
226 /* It's OK to put an `else' clause after this macro. */
227 #define CHECKOOB(action) \
236 #ifdef VIRTUAL_HOSTING
237 static void inithosts(int);
238 static void selecthost(union sockunion *);
240 static void ack(char *);
241 static void sigurg(int);
242 static void maskurg(int);
243 static void flagxfer(int);
244 static int myoob(void);
245 static int checkuser(char *, char *, int, char **, int *);
246 static FILE *dataconn(char *, off_t, char *);
247 static void dolog(struct sockaddr *);
248 static void end_login(void);
249 static FILE *getdatasock(char *);
250 static int guniquefd(char *, char **);
251 static void lostconn(int);
252 static void sigquit(int);
253 static int receive_data(FILE *, FILE *);
254 static int send_data(FILE *, FILE *, size_t, off_t, int);
255 static struct passwd *
257 static char *sgetsave(char *);
258 static void reapchild(int);
259 static void appendf(char **, char *, ...) __printflike(2, 3);
260 static void logcmd(char *, char *, char *, off_t);
261 static void logxfer(char *, off_t, time_t);
262 static char *doublequote(char *);
263 static int *socksetup(int, char *, const char *);
266 main(int argc, char *argv[], char **envp)
269 int ch, on = 1, tos, s = STDIN_FILENO;
270 char *cp, line[LINE_MAX];
272 char *bindname = NULL;
273 const char *bindport = "ftp";
274 int family = AF_UNSPEC;
277 tzset(); /* in case no timezone database in ~ftp */
278 sigemptyset(&sa.sa_mask);
279 sa.sa_flags = SA_RESTART;
281 #ifdef OLD_SETPROCTITLE
283 * Save start and extent of argv for setproctitle.
288 LastArgv = envp[-1] + strlen(envp[-1]);
289 #endif /* OLD_SETPROCTITLE */
292 * Prevent diagnostic messages from appearing on stderr.
293 * We run as a daemon or from inetd; in both cases, there's
294 * more reason in logging to syslog.
296 (void) freopen(_PATH_DEVNULL, "w", stderr);
300 * LOG_NDELAY sets up the logging connection immediately,
301 * necessary for anonymous ftp's that chroot and can't do it later.
303 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
305 while ((ch = getopt(argc, argv,
306 "468a:ABdDEhlmMoOp:P:rRSt:T:u:UvW")) != -1) {
309 family = (family == AF_INET6) ? AF_UNSPEC : AF_INET;
313 family = (family == AF_INET) ? AF_UNSPEC : AF_INET6;
332 syslog(LOG_WARNING, "not compiled with USE_BLACKLIST support");
353 logging++; /* > 1 == extra logging */
393 timeout = atoi(optarg);
394 if (maxtimeout < timeout)
395 maxtimeout = timeout;
399 maxtimeout = atoi(optarg);
400 if (timeout > maxtimeout)
401 timeout = maxtimeout;
408 val = strtol(optarg, &optarg, 8);
409 if (*optarg != '\0' || val < 0)
410 syslog(LOG_WARNING, "bad value for -u");
416 restricted_data_ports = 0;
428 syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
433 /* handle filesize limit gracefully */
434 sa.sa_handler = SIG_IGN;
435 (void)sigaction(SIGXFSZ, &sa, NULL);
438 int *ctl_sock, fd, maxfd = -1, nfds, i;
439 fd_set defreadfds, readfds;
443 if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
444 if (errno == EEXIST) {
445 syslog(LOG_ERR, "%s already running, pid %d",
446 getprogname(), (int)pid);
449 syslog(LOG_WARNING, "pidfile_open: %m");
453 * Detach from parent.
455 if (daemon(1, 1) < 0) {
456 syslog(LOG_ERR, "failed to become a daemon");
460 if (pfh != NULL && pidfile_write(pfh) == -1)
461 syslog(LOG_WARNING, "pidfile_write: %m");
463 sa.sa_handler = reapchild;
464 (void)sigaction(SIGCHLD, &sa, NULL);
466 #ifdef VIRTUAL_HOSTING
471 * Open a socket, bind it to the FTP port, and start
474 ctl_sock = socksetup(family, bindname, bindport);
475 if (ctl_sock == NULL)
478 FD_ZERO(&defreadfds);
479 for (i = 1; i <= *ctl_sock; i++) {
480 FD_SET(ctl_sock[i], &defreadfds);
481 if (listen(ctl_sock[i], 32) < 0) {
482 syslog(LOG_ERR, "control listen: %m");
485 if (maxfd < ctl_sock[i])
490 * Loop forever accepting connection requests and forking off
491 * children to handle them.
494 FD_COPY(&defreadfds, &readfds);
495 nfds = select(maxfd + 1, &readfds, NULL, NULL, 0);
497 if (nfds < 0 && errno != EINTR)
498 syslog(LOG_WARNING, "select: %m");
503 for (i = 1; i <= *ctl_sock; i++)
504 if (FD_ISSET(ctl_sock[i], &readfds)) {
505 addrlen = sizeof(his_addr);
506 fd = accept(ctl_sock[i],
507 (struct sockaddr *)&his_addr,
514 switch (pid = fork()) {
518 (void) dup2(fd, STDOUT_FILENO);
520 for (i = 1; i <= *ctl_sock; i++)
526 syslog(LOG_WARNING, "fork: %m");
534 addrlen = sizeof(his_addr);
535 if (getpeername(s, (struct sockaddr *)&his_addr, &addrlen) < 0) {
536 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
540 #ifdef VIRTUAL_HOSTING
541 if (his_addr.su_family == AF_INET6 &&
542 IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))
545 family = his_addr.su_family;
551 sa.sa_handler = SIG_DFL;
552 (void)sigaction(SIGCHLD, &sa, NULL);
554 sa.sa_handler = sigurg;
555 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
556 (void)sigaction(SIGURG, &sa, NULL);
558 sigfillset(&sa.sa_mask); /* block all signals in handler */
559 sa.sa_flags = SA_RESTART;
560 sa.sa_handler = sigquit;
561 (void)sigaction(SIGHUP, &sa, NULL);
562 (void)sigaction(SIGINT, &sa, NULL);
563 (void)sigaction(SIGQUIT, &sa, NULL);
564 (void)sigaction(SIGTERM, &sa, NULL);
566 sa.sa_handler = lostconn;
567 (void)sigaction(SIGPIPE, &sa, NULL);
569 addrlen = sizeof(ctrl_addr);
570 if (getsockname(s, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
571 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
574 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
575 #ifdef VIRTUAL_HOSTING
576 /* select our identity from virtual host table */
577 selecthost(&ctrl_addr);
580 if (ctrl_addr.su_family == AF_INET)
582 tos = IPTOS_LOWDELAY;
583 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
584 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
588 * Disable Nagle on the control channel so that we don't have to wait
589 * for peer's ACK before issuing our next reply.
591 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
592 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
594 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
596 (void)snprintf(wtmpid, sizeof(wtmpid), "%xftpd", getpid());
598 /* Try to handle urgent data inline */
600 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
601 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
605 if (fcntl(s, F_SETOWN, getpid()) == -1)
606 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
608 dolog((struct sockaddr *)&his_addr);
610 * Set up default state
619 /* If logins are disabled, print out the message. */
620 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
621 while (fgets(line, sizeof(line), fd) != NULL) {
622 if ((cp = strchr(line, '\n')) != NULL)
624 lreply(530, "%s", line);
626 (void) fflush(stdout);
628 reply(530, "System not available.");
631 #ifdef VIRTUAL_HOSTING
632 fd = fopen(thishost->welcome, "r");
634 fd = fopen(_PATH_FTPWELCOME, "r");
637 while (fgets(line, sizeof(line), fd) != NULL) {
638 if ((cp = strchr(line, '\n')) != NULL)
640 lreply(220, "%s", line);
642 (void) fflush(stdout);
644 /* reply(220,) must follow */
646 #ifndef VIRTUAL_HOSTING
647 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
648 fatalerror("Ran out of memory.");
649 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
651 hostname[MAXHOSTNAMELEN - 1] = '\0';
654 reply(220, "%s FTP server (%s) ready.", hostname, version);
656 reply(220, "FTP server ready.");
668 syslog(LOG_DEBUG, "lost connection");
676 syslog(LOG_ERR, "got signal %d", signo);
680 #ifdef VIRTUAL_HOSTING
682 * read in virtual host tables (if they exist)
686 inithosts(int family)
691 char *cp, *mp, *line;
693 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
694 struct ftphost *hrp, *lhrp;
695 struct addrinfo hints, *res, *ai;
698 * Fill in the default host information
700 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
701 fatalerror("Ran out of memory.");
702 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
704 hostname[MAXHOSTNAMELEN - 1] = '\0';
705 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
706 fatalerror("Ran out of memory.");
707 hrp->hostname = hostname;
708 hrp->hostinfo = NULL;
710 memset(&hints, 0, sizeof(hints));
711 hints.ai_flags = AI_PASSIVE;
712 hints.ai_family = family;
713 hints.ai_socktype = SOCK_STREAM;
714 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
716 hrp->statfile = _PATH_FTPDSTATFILE;
717 hrp->welcome = _PATH_FTPWELCOME;
718 hrp->loginmsg = _PATH_FTPLOGINMESG;
719 hrp->anonuser = "ftp";
721 thishost = firsthost = lhrp = hrp;
722 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
723 int addrsize, gothost;
727 while ((line = fgetln(fp, &len)) != NULL) {
733 if (line[len - 1] == '\n') {
734 line[len - 1] = '\0';
737 if ((mp = malloc(len + 1)) == NULL)
738 fatalerror("Ran out of memory.");
739 memcpy(mp, line, len);
743 cp = strtok(line, " \t");
744 /* skip empty lines */
751 statfile = _PATH_FTPDSTATFILE;
752 welcome = _PATH_FTPWELCOME;
753 loginmsg = _PATH_FTPLOGINMESG;
756 * Preparse the line so we can use its info
757 * for all the addresses associated with
758 * the virtual host name.
759 * Field 0, the virtual host name, is special:
760 * it's already parsed off and will be strdup'ed
761 * later, after we know its canonical form.
763 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
764 if (*cp != '-' && (cp = strdup(cp)))
766 case 1: /* anon user permissions */
769 case 2: /* statistics file */
772 case 3: /* welcome message */
775 case 4: /* login message */
778 default: /* programming error */
783 hints.ai_flags = AI_PASSIVE;
784 hints.ai_family = family;
785 hints.ai_socktype = SOCK_STREAM;
786 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
788 for (ai = res; ai != NULL && ai->ai_addr != NULL;
792 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
795 for (hi = hrp->hostinfo; hi != NULL;
797 if (hi->ai_addrlen == ai->ai_addrlen &&
800 ai->ai_addr->sa_len) == 0) {
808 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
810 hrp->hostname = NULL;
813 if (hrp->hostinfo && hrp->hostinfo != res)
814 freeaddrinfo(hrp->hostinfo);
815 insert = 0; /* host already in the chain */
820 * determine hostname to use.
821 * force defined name if there is a valid alias
822 * otherwise fallback to primary hostname
824 /* XXX: getaddrinfo() can't do alias check */
825 switch(hrp->hostinfo->ai_family) {
827 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
828 addrsize = sizeof(struct in_addr);
831 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
832 addrsize = sizeof(struct in6_addr);
835 /* should not reach here */
836 freeaddrinfo(hrp->hostinfo);
838 free(hrp); /*not in chain, can free*/
840 hrp->hostinfo = NULL; /*mark as blank*/
844 if ((hp = getipnodebyaddr(addr, addrsize,
845 hrp->hostinfo->ai_family,
846 &hp_error)) != NULL) {
847 if (strcmp(vhost, hp->h_name) != 0) {
848 if (hp->h_aliases == NULL)
852 while (hp->h_aliases[i] &&
853 strcmp(vhost, hp->h_aliases[i]) != 0)
855 if (hp->h_aliases[i] == NULL)
861 strcmp(hrp->hostname, vhost) != 0) {
863 hrp->hostname = NULL;
865 if (hrp->hostname == NULL &&
866 (hrp->hostname = strdup(vhost)) == NULL) {
867 freeaddrinfo(hrp->hostinfo);
868 hrp->hostinfo = NULL; /* mark as blank */
873 hrp->anonuser = anonuser;
874 hrp->statfile = statfile;
875 hrp->welcome = welcome;
876 hrp->loginmsg = loginmsg;
894 selecthost(union sockunion *su)
899 struct in6_addr *mapped_in6 = NULL;
905 * XXX IPv4 mapped IPv6 addr consideraton,
906 * specified in rfc2373.
908 if (su->su_family == AF_INET6 &&
909 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
910 mapped_in6 = &su->su_sin6.sin6_addr;
913 hrp = thishost = firsthost; /* default */
916 while (hrp != NULL) {
917 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
918 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
923 /* XXX IPv4 mapped IPv6 addr consideraton */
924 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
925 (memcmp(&mapped_in6->s6_addr[12],
926 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
927 sizeof(struct in_addr)) == 0)) {
937 /* setup static variables as appropriate */
938 hostname = thishost->hostname;
939 ftpuser = thishost->anonuser;
944 * Helper function for sgetpwnam().
949 char *new = malloc(strlen(s) + 1);
952 reply(421, "Ran out of memory.");
956 (void) strcpy(new, s);
961 * Save the result of a getpwnam. Used for USER command, since
962 * the data returned must not be clobbered by any other command
964 * NB: The data returned by sgetpwnam() will remain valid until
965 * the next call to this function. Its difference from getpwnam()
966 * is that sgetpwnam() is known to be called from ftpd code only.
968 static struct passwd *
969 sgetpwnam(char *name)
971 static struct passwd save;
974 if ((p = getpwnam(name)) == NULL)
978 free(save.pw_passwd);
985 save.pw_name = sgetsave(p->pw_name);
986 save.pw_passwd = sgetsave(p->pw_passwd);
987 save.pw_class = sgetsave(p->pw_class);
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 #ifdef VIRTUAL_HOSTING
1028 pw = sgetpwnam(thishost->anonuser);
1030 pw = sgetpwnam("ftp");
1032 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1033 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL, &ecode) ||
1034 (ecode != 0 && ecode != ENOENT))
1035 reply(530, "User %s access denied.", name);
1036 else if (checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL, &ecode) ||
1037 (ecode != 0 && ecode != ENOENT))
1038 reply(530, "User %s access denied.", name);
1039 else if (pw != NULL) {
1043 "Guest login ok, send your email address as password.");
1045 reply(530, "User %s unknown.", name);
1046 if (!askpasswd && logging)
1048 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1051 if (anon_only != 0) {
1052 reply(530, "Sorry, only anonymous ftp allowed.");
1056 if ((pw = sgetpwnam(name))) {
1057 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1058 shell = _PATH_BSHELL;
1060 while ((cp = getusershell()) != NULL)
1061 if (strcmp(cp, shell) == 0)
1066 (checkuser(_PATH_FTPUSERS, name, 1, NULL, &ecode) ||
1067 (ecode != 0 && ecode != ENOENT))) {
1068 reply(530, "User %s access denied.", name);
1071 "FTP LOGIN REFUSED FROM %s, %s",
1078 strlcpy(curname, name, sizeof(curname));
1082 /* XXX Kluge! The conversation mechanism needs to be fixed. */
1084 if (opiechallenge(&opiedata, name, opieprompt) == 0) {
1085 pwok = (pw != NULL) &&
1086 opieaccessfile(remotehost) &&
1087 opiealways(pw->pw_dir);
1088 reply(331, "Response to %s %s for %s.",
1089 opieprompt, pwok ? "requested" : "required", name);
1092 reply(331, "Password required for %s.", name);
1096 * Delay before reading passwd after first failed
1097 * attempt to slow down passwd-guessing programs.
1100 sleep(login_attempts);
1104 * Check if a user is in the file "fname",
1105 * return a pointer to a malloc'd string with the rest
1106 * of the matching line in "residue" if not NULL.
1109 checkuser(char *fname, char *name, int pwset, char **residue, int *ecode)
1114 char *line, *mp, *p;
1118 if ((fd = fopen(fname, "r")) != NULL) {
1119 while (!found && (line = fgetln(fd, &len)) != NULL) {
1123 if (line[len - 1] == '\n') {
1124 line[len - 1] = '\0';
1127 if ((mp = malloc(len + 1)) == NULL)
1128 fatalerror("Ran out of memory.");
1129 memcpy(mp, line, len);
1133 /* avoid possible leading and trailing whitespace */
1134 p = strtok(line, " \t");
1135 /* skip empty lines */
1139 * if first chr is '@', check group membership
1145 if (p[1] == '\0') /* single @ matches anyone */
1148 if ((grp = getgrnam(p+1)) == NULL)
1151 * Check user's default group
1153 if (pwset && grp->gr_gid == pw->pw_gid)
1156 * Check supplementary groups
1158 while (!found && grp->gr_mem[i])
1159 found = strcmp(name,
1165 * Otherwise, just check for username match
1168 found = strcmp(p, name) == 0;
1170 * Save the rest of line to "residue" if matched
1172 if (found && residue) {
1173 if ((p = strtok(NULL, "")) != NULL)
1174 p += strspn(p, " \t");
1176 if ((*residue = strdup(p)) == NULL)
1177 fatalerror("Ran out of memory.");
1186 } else if (ecode != NULL)
1192 * Terminate login as previous user, if any, resetting state;
1193 * used when USER command is given or login fails.
1204 setusercontext(NULL, getpwuid(0), 0, LOGIN_SETALL & ~(LOGIN_SETLOGIN |
1205 LOGIN_SETUSER | LOGIN_SETGROUP | LOGIN_SETPATH |
1208 if (logged_in && dowtmp)
1209 ftpd_logwtmp(wtmpid, NULL, NULL);
1213 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1214 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1215 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1216 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1217 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1218 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1230 * the following code is stolen from imap-uw PAM authentication module and
1233 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1236 const char *uname; /* user name */
1237 const char *pass; /* password */
1239 typedef struct cred_t cred_t;
1242 auth_conv(int num_msg, const struct pam_message **msg,
1243 struct pam_response **resp, void *appdata)
1246 cred_t *cred = (cred_t *) appdata;
1247 struct pam_response *reply;
1249 reply = calloc(num_msg, sizeof *reply);
1253 for (i = 0; i < num_msg; i++) {
1254 switch (msg[i]->msg_style) {
1255 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1256 reply[i].resp_retcode = PAM_SUCCESS;
1257 reply[i].resp = COPY_STRING(cred->uname);
1258 /* PAM frees resp. */
1260 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1261 reply[i].resp_retcode = PAM_SUCCESS;
1262 reply[i].resp = COPY_STRING(cred->pass);
1263 /* PAM frees resp. */
1267 reply[i].resp_retcode = PAM_SUCCESS;
1268 reply[i].resp = NULL;
1270 default: /* unknown message style */
1272 return PAM_CONV_ERR;
1281 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1282 * authenticated, or 1 if not authenticated. If some sort of PAM system
1283 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1284 * function returns -1. This can be used as an indication that we should
1285 * fall back to a different authentication mechanism.
1288 auth_pam(struct passwd **ppw, const char *pass)
1290 const char *tmpl_user;
1294 cred_t auth_cred = { (*ppw)->pw_name, pass };
1295 struct pam_conv conv = { &auth_conv, &auth_cred };
1297 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1298 if (e != PAM_SUCCESS) {
1300 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1301 * if context creation has failed in the first place.
1303 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
1307 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1308 if (e != PAM_SUCCESS) {
1309 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1310 pam_strerror(pamh, e));
1311 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1312 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1318 e = pam_authenticate(pamh, 0);
1322 * With PAM we support the concept of a "template"
1323 * user. The user enters a login name which is
1324 * authenticated by PAM, usually via a remote service
1325 * such as RADIUS or TACACS+. If authentication
1326 * succeeds, a different but related "template" name
1327 * is used for setting the credentials, shell, and
1328 * home directory. The name the user enters need only
1329 * exist on the remote authentication server, but the
1330 * template name must be present in the local password
1333 * This is supported by two various mechanisms in the
1334 * individual modules. However, from the application's
1335 * point of view, the template user is always passed
1336 * back as a changed value of the PAM_USER item.
1338 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1340 tmpl_user = (const char *) item;
1341 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1342 *ppw = getpwnam(tmpl_user);
1344 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1345 pam_strerror(pamh, e));
1350 case PAM_USER_UNKNOWN:
1356 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1362 e = pam_acct_mgmt(pamh, 0);
1363 if (e != PAM_SUCCESS) {
1364 syslog(LOG_ERR, "pam_acct_mgmt: %s",
1365 pam_strerror(pamh, e));
1371 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1372 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1379 #endif /* USE_PAM */
1387 login_cap_t *lc = NULL;
1392 char *residue = NULL;
1395 if (logged_in || askpasswd == 0) {
1396 reply(503, "Login with USER first.");
1400 if (!guest) { /* "ftp" is only account allowed no password */
1402 rval = 1; /* failure below */
1406 rval = auth_pam(&pw, passwd);
1412 if (opieverify(&opiedata, passwd) == 0)
1413 xpasswd = pw->pw_passwd;
1415 xpasswd = crypt(passwd, pw->pw_passwd);
1416 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1422 rval = strcmp(pw->pw_passwd, xpasswd);
1423 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1424 rval = 1; /* failure */
1427 * If rval == 1, the user failed the authentication check
1428 * above. If rval == 0, either PAM or local authentication
1432 reply(530, "Login incorrect.");
1433 BLACKLIST_NOTIFY(BLACKLIST_AUTH_FAIL, STDIN_FILENO, "Login incorrect");
1436 "FTP LOGIN FAILED FROM %s",
1438 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1439 "FTP LOGIN FAILED FROM %s, %s",
1440 remotehost, curname);
1443 if (login_attempts++ >= 5) {
1445 "repeated login failures from %s",
1451 BLACKLIST_NOTIFY(BLACKLIST_AUTH_OK, STDIN_FILENO, "Login successful");
1454 login_attempts = 0; /* this time successful */
1455 if (setegid(pw->pw_gid) < 0) {
1456 reply(550, "Can't set gid.");
1459 /* May be overridden by login.conf */
1460 (void) umask(defumask);
1462 if ((lc = login_getpwclass(pw)) != NULL) {
1463 char remote_ip[NI_MAXHOST];
1465 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1466 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1469 remote_ip[sizeof(remote_ip) - 1] = 0;
1470 if (!auth_hostok(lc, remotehost, remote_ip)) {
1471 syslog(LOG_INFO|LOG_AUTH,
1472 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1474 reply(530, "Permission denied.");
1478 if (!auth_timeok(lc, time(NULL))) {
1479 reply(530, "Login not available right now.");
1484 setusercontext(lc, pw, 0, LOGIN_SETALL &
1485 ~(LOGIN_SETRESOURCES | LOGIN_SETUSER | LOGIN_SETPATH | LOGIN_SETENV));
1487 setlogin(pw->pw_name);
1488 (void) initgroups(pw->pw_name, pw->pw_gid);
1493 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1494 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1495 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1496 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1502 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue, &ecode)
1503 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1504 || login_getcapbool(lc, "ftp-chroot", 0)
1508 * It is possible that checkuser() failed to open the chroot file.
1509 * If this is the case, report that logins are un-available, since we
1510 * have no way of checking whether or not the user should be chrooted.
1511 * We ignore ENOENT since it is not required that this file be present.
1513 if (ecode != 0 && ecode != ENOENT) {
1514 reply(530, "Login not available right now.");
1519 /* Disable wtmp logging when chrooting. */
1520 if (dochroot || guest)
1523 ftpd_logwtmp(wtmpid, pw->pw_name,
1524 (struct sockaddr *)&his_addr);
1528 setusercontext(lc, pw, 0, LOGIN_SETRESOURCES);
1531 if (guest && stats && statfd < 0)
1532 #ifdef VIRTUAL_HOSTING
1533 statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1535 statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1541 * For a chrooted local user,
1542 * a) see whether ftpchroot(5) specifies a chroot directory,
1543 * b) extract the directory pathname from the line,
1544 * c) expand it to the absolute pathname if necessary.
1546 if (dochroot && residue &&
1547 (chrootdir = strtok(residue, " \t")) != NULL) {
1548 if (chrootdir[0] != '/')
1549 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1551 chrootdir = strdup(chrootdir); /* make it permanent */
1552 if (chrootdir == NULL)
1553 fatalerror("Ran out of memory.");
1555 if (guest || dochroot) {
1557 * If no chroot directory set yet, use the login directory.
1558 * Copy it so it can be modified while pw->pw_dir stays intact.
1560 if (chrootdir == NULL &&
1561 (chrootdir = strdup(pw->pw_dir)) == NULL)
1562 fatalerror("Ran out of memory.");
1564 * Check for the "/chroot/./home" syntax,
1565 * separate the chroot and home directory pathnames.
1567 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1568 *(homedir++) = '\0'; /* wipe '/' */
1569 homedir++; /* skip '.' */
1572 * We MUST do a chdir() after the chroot. Otherwise
1573 * the old current directory will be accessible as "."
1574 * outside the new root!
1579 * Finally, do chroot()
1581 if (chroot(chrootdir) < 0) {
1582 reply(550, "Can't change root.");
1585 __FreeBSD_libc_enter_restricted_mode();
1586 } else /* real user w/o chroot */
1587 homedir = pw->pw_dir;
1589 * Set euid *before* doing chdir() so
1590 * a) the user won't be carried to a directory that he couldn't reach
1591 * on his own due to no permission to upper path components,
1592 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1593 * (uid 0 has no root power over NFS if not mapped explicitly.)
1595 if (seteuid(pw->pw_uid) < 0) {
1596 reply(550, "Can't set uid.");
1599 if (chdir(homedir) < 0) {
1600 if (guest || dochroot) {
1601 reply(550, "Can't change to base directory.");
1604 if (chdir("/") < 0) {
1605 reply(550, "Root is inaccessible.");
1608 lreply(230, "No directory! Logging in with home=/.");
1613 * Display a login message, if it exists.
1614 * N.B. reply(230,) must follow the message.
1616 #ifdef VIRTUAL_HOSTING
1617 fd = fopen(thishost->loginmsg, "r");
1619 fd = fopen(_PATH_FTPLOGINMESG, "r");
1622 char *cp, line[LINE_MAX];
1624 while (fgets(line, sizeof(line), fd) != NULL) {
1625 if ((cp = strchr(line, '\n')) != NULL)
1627 lreply(230, "%s", line);
1629 (void) fflush(stdout);
1635 ident = strdup(passwd);
1637 fatalerror("Ran out of memory.");
1639 reply(230, "Guest login ok, access restrictions apply.");
1641 #ifdef VIRTUAL_HOSTING
1642 if (thishost != firsthost)
1643 snprintf(proctitle, sizeof(proctitle),
1644 "%s: anonymous(%s)/%s", remotehost, hostname,
1648 snprintf(proctitle, sizeof(proctitle),
1649 "%s: anonymous/%s", remotehost, passwd);
1650 setproctitle("%s", proctitle);
1651 #endif /* SETPROCTITLE */
1653 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1654 remotehost, passwd);
1657 reply(230, "User %s logged in, "
1658 "access restrictions apply.", pw->pw_name);
1660 reply(230, "User %s logged in.", pw->pw_name);
1663 snprintf(proctitle, sizeof(proctitle),
1664 "%s: user/%s", remotehost, pw->pw_name);
1665 setproctitle("%s", proctitle);
1666 #endif /* SETPROCTITLE */
1668 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1669 remotehost, pw->pw_name);
1671 if (logging && (guest || dochroot))
1672 syslog(LOG_INFO, "session root changed to %s", chrootdir);
1680 /* Forget all about it... */
1690 retrieve(char *cmd, char *name)
1694 int (*closefunc)(FILE *);
1699 fin = fopen(name, "r"), closefunc = fclose;
1702 (void) snprintf(line, sizeof(line), cmd, name);
1704 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1706 st.st_blksize = BUFSIZ;
1710 perror_reply(550, name);
1712 LOGCMD("get", name);
1719 if (fstat(fileno(fin), &st) < 0) {
1720 perror_reply(550, name);
1723 if (!S_ISREG(st.st_mode)) {
1725 * Never sending a raw directory is a workaround
1726 * for buggy clients that will attempt to RETR
1727 * a directory before listing it, e.g., Mozilla.
1728 * Preventing a guest from getting irregular files
1729 * is a simple security measure.
1731 if (S_ISDIR(st.st_mode) || guest) {
1732 reply(550, "%s: not a plain file.", name);
1736 /* st.st_blksize is set for all descriptor types */
1739 if (restart_point) {
1740 if (type == TYPE_A) {
1747 if ((c=getc(fin)) == EOF) {
1748 perror_reply(550, name);
1754 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1755 perror_reply(550, name);
1759 dout = dataconn(name, st.st_size, "w");
1763 send_data(fin, dout, st.st_blksize, st.st_size,
1764 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1765 if (cmd == 0 && guest && stats && byte_count > 0)
1766 logxfer(name, byte_count, start);
1767 (void) fclose(dout);
1772 LOGBYTES("get", name, byte_count);
1777 store(char *name, char *mode, int unique)
1781 int (*closefunc)(FILE *);
1783 if (*mode == 'a') { /* APPE */
1785 /* Programming error */
1786 syslog(LOG_ERR, "Internal: unique flag to APPE");
1789 if (guest && noguestmod) {
1790 reply(550, "Appending to existing file denied.");
1793 restart_point = 0; /* not affected by preceding REST */
1795 if (unique) /* STOU overrides REST */
1797 if (guest && noguestmod) {
1798 if (restart_point) { /* guest STOR w/REST */
1799 reply(550, "Modifying existing file denied.");
1801 } else /* treat guest STOR as STOU */
1806 mode = "r+"; /* so ASCII manual seek can work */
1808 if ((fd = guniquefd(name, &name)) < 0)
1810 fout = fdopen(fd, mode);
1812 fout = fopen(name, mode);
1815 perror_reply(553, name);
1819 if (restart_point) {
1820 if (type == TYPE_A) {
1827 if ((c=getc(fout)) == EOF) {
1828 perror_reply(550, name);
1835 * We must do this seek to "current" position
1836 * because we are changing from reading to
1839 if (fseeko(fout, 0, SEEK_CUR) < 0) {
1840 perror_reply(550, name);
1843 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1844 perror_reply(550, name);
1848 din = dataconn(name, -1, "r");
1851 if (receive_data(din, fout) == 0) {
1853 reply(226, "Transfer complete (unique file name:%s).",
1856 reply(226, "Transfer complete.");
1862 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1866 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1871 getdatasock(char *mode)
1873 int on = 1, s, t, tries;
1876 return (fdopen(data, mode));
1878 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1881 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1882 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1883 /* anchor socket to avoid multi-homing problems */
1884 data_source = ctrl_addr;
1885 data_source.su_port = htons(dataport);
1887 for (tries = 1; ; tries++) {
1889 * We should loop here since it's possible that
1890 * another ftpd instance has passed this point and is
1891 * trying to open a data connection in active mode now.
1892 * Until the other connection is opened, we'll be getting
1893 * EADDRINUSE because no SOCK_STREAM sockets in the system
1894 * can share both local and remote addresses, localIP:20
1895 * and *:* in this case.
1897 if (bind(s, (struct sockaddr *)&data_source,
1898 data_source.su_len) >= 0)
1900 if (errno != EADDRINUSE || tries > 10)
1904 (void) seteuid(pw->pw_uid);
1906 if (data_source.su_family == AF_INET)
1908 on = IPTOS_THROUGHPUT;
1909 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1910 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1915 * Turn off push flag to keep sender TCP from sending short packets
1916 * at the boundaries of each write().
1919 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1920 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1922 return (fdopen(s, mode));
1924 /* Return the real value of errno (close may change it) */
1926 (void) seteuid(pw->pw_uid);
1933 dataconn(char *name, off_t size, char *mode)
1937 int retry = 0, tos, conerrno;
1942 (void) snprintf(sizebuf, sizeof(sizebuf),
1943 " (%jd bytes)", (intmax_t)size);
1947 union sockunion from;
1948 socklen_t fromlen = ctrl_addr.su_len;
1950 struct timeval timeout;
1954 FD_SET(pdata, &set);
1956 timeout.tv_usec = 0;
1957 timeout.tv_sec = 120;
1960 * Granted a socket is in the blocking I/O mode,
1961 * accept() will block after a successful select()
1962 * if the selected connection dies in between.
1963 * Therefore set the non-blocking I/O flag here.
1965 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1966 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1968 if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
1969 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1971 (void) close(pdata);
1974 * Unset the inherited non-blocking I/O flag
1975 * on the child socket so stdio can work on it.
1977 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1978 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1981 if (from.su_family == AF_INET)
1983 tos = IPTOS_THROUGHPUT;
1984 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1985 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1988 reply(150, "Opening %s mode data connection for '%s'%s.",
1989 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1990 return (fdopen(pdata, mode));
1992 reply(425, "Can't open data connection.");
1993 (void) close(pdata);
1998 reply(125, "Using existing data connection for '%s'%s.",
2001 return (fdopen(data, mode));
2004 data_dest = his_addr;
2007 file = getdatasock(mode);
2009 char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
2011 if (getnameinfo((struct sockaddr *)&data_source,
2013 hostbuf, sizeof(hostbuf) - 1,
2014 portbuf, sizeof(portbuf) - 1,
2015 NI_NUMERICHOST|NI_NUMERICSERV))
2016 *hostbuf = *portbuf = 0;
2017 hostbuf[sizeof(hostbuf) - 1] = 0;
2018 portbuf[sizeof(portbuf) - 1] = 0;
2019 reply(425, "Can't create data socket (%s,%s): %s.",
2020 hostbuf, portbuf, strerror(errno));
2023 data = fileno(file);
2025 if (connect(data, (struct sockaddr *)&data_dest,
2026 data_dest.su_len) == 0)
2029 (void) fclose(file);
2031 if (conerrno == EADDRINUSE) {
2037 } while (retry <= swaitmax);
2038 if (conerrno != 0) {
2039 reply(425, "Can't build data connection: %s.",
2040 strerror(conerrno));
2043 reply(150, "Opening %s mode data connection for '%s'%s.",
2044 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2049 * A helper macro to avoid code duplication
2050 * in send_data() and receive_data().
2052 * XXX We have to block SIGURG during putc() because BSD stdio
2053 * is unable to restart interrupted write operations and hence
2054 * the entire buffer contents will be lost as soon as a write()
2055 * call indicates EINTR to stdio.
2057 #define FTPD_PUTC(ch, file, label) \
2063 ret = putc((ch), (file)); \
2065 CHECKOOB(return (-1)) \
2066 else if (ferror(file)) \
2069 } while (ret == EOF); \
2073 * Transfer the contents of "instr" to "outstr" peer using the appropriate
2074 * encapsulation of the data subject to Mode, Structure, and Type.
2076 * NB: Form isn't handled.
2079 send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2081 int c, cp, filefd, netfd;
2092 CHECKOOB(return (-1))
2093 else if (c == EOF && ferror(instr))
2096 if (ferror(instr)) { /* resume after OOB */
2100 if (feof(instr)) /* EOF */
2102 syslog(LOG_ERR, "Internal: impossible condition"
2103 " on file after getc()");
2106 if (c == '\n' && cp != '\r') {
2107 FTPD_PUTC('\r', outstr, data_err);
2110 FTPD_PUTC(c, outstr, data_err);
2114 #ifdef notyet /* BSD stdio isn't ready for that */
2115 while (fflush(outstr) == EOF) {
2116 CHECKOOB(return (-1))
2124 if (fflush(outstr) == EOF)
2127 reply(226, "Transfer complete.");
2133 * isreg is only set if we are not doing restart and we
2134 * are sending a regular file
2136 netfd = fileno(outstr);
2137 filefd = fileno(instr);
2140 char *msg = "Transfer complete.";
2146 while (filesize > 0) {
2147 err = sendfile(filefd, netfd, offset, 0,
2150 * Calculate byte_count before OOB processing.
2151 * It can be used in myoob() later.
2156 CHECKOOB(return (-1))
2157 else if (err == -1) {
2158 if (errno != EINTR &&
2159 cnt == 0 && offset == 0)
2163 if (err == -1) /* resume after OOB */
2166 * We hit the EOF prematurely.
2167 * Perhaps the file was externally truncated.
2170 msg = "Transfer finished due to "
2171 "premature end of file.";
2176 reply(226, "%s", msg);
2181 if ((buf = malloc(blksize)) == NULL) {
2183 reply(451, "Ran out of memory.");
2191 cnt = read(filefd, buf, blksize);
2192 CHECKOOB(free(buf); return (-1))
2197 if (cnt < 0) /* resume after OOB */
2199 if (cnt == 0) /* EOF */
2201 for (len = cnt, bp = buf; len > 0;) {
2202 cnt = write(netfd, bp, len);
2203 CHECKOOB(free(buf); return (-1))
2217 reply(226, "Transfer complete.");
2221 reply(550, "Unimplemented TYPE %d in send_data.", type);
2227 perror_reply(426, "Data connection");
2232 perror_reply(551, "Error on input file");
2237 * Transfer data from peer to "outstr" using the appropriate encapulation of
2238 * the data subject to Mode, Structure, and Type.
2240 * N.B.: Form isn't handled.
2243 receive_data(FILE *instr, FILE *outstr)
2259 cnt = read(fileno(instr), buf, sizeof(buf));
2260 CHECKOOB(return (-1))
2263 if (cnt < 0) /* resume after OOB */
2265 if (cnt == 0) /* EOF */
2267 for (len = cnt, bp = buf; len > 0;) {
2268 cnt = write(fileno(outstr), bp, len);
2269 CHECKOOB(return (-1))
2284 reply(553, "TYPE E not implemented.");
2291 CHECKOOB(return (-1))
2292 else if (c == EOF && ferror(instr))
2294 if (c == EOF && ferror(instr)) { /* resume after OOB */
2301 FTPD_PUTC('\r', outstr, file_err);
2311 /* Check for EOF here in order not to lose last \r. */
2313 if (feof(instr)) /* EOF */
2315 syslog(LOG_ERR, "Internal: impossible condition"
2316 " on data stream after getc()");
2321 FTPD_PUTC(c, outstr, file_err);
2324 #ifdef notyet /* BSD stdio isn't ready for that */
2325 while (fflush(outstr) == EOF) {
2326 CHECKOOB(return (-1))
2334 if (fflush(outstr) == EOF)
2339 "WARNING! %d bare linefeeds received in ASCII mode.",
2341 (void)printf(" File may not have transferred correctly.\r\n");
2346 reply(550, "Unimplemented TYPE %d in receive_data.", type);
2352 perror_reply(426, "Data connection");
2357 perror_reply(452, "Error writing to file");
2362 statfilecmd(char *filename)
2367 char line[LINE_MAX];
2370 code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2371 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2372 fin = ftpd_popen(line, "r");
2374 perror_reply(551, filename);
2377 lreply(code, "Status of %s:", filename);
2379 while ((c = getc(fin)) != EOF) {
2381 if (ferror(stdout)){
2382 perror_reply(421, "Control connection");
2383 (void) ftpd_pclose(fin);
2388 perror_reply(551, filename);
2389 (void) ftpd_pclose(fin);
2392 (void) putc('\r', stdout);
2395 * RFC 959 says neutral text should be prepended before
2396 * a leading 3-digit number followed by whitespace, but
2397 * many ftp clients can be confused by any leading digits,
2398 * as a matter of fact.
2400 if (atstart && isdigit(c))
2401 (void) putc(' ', stdout);
2402 (void) putc(c, stdout);
2403 atstart = (c == '\n');
2405 (void) ftpd_pclose(fin);
2406 reply(code, "End of status.");
2412 union sockunion *su;
2414 char hname[NI_MAXHOST];
2418 lreply(211, "%s FTP server status:", hostname);
2419 printf(" %s\r\n", version);
2421 lreply(211, "FTP server status:");
2422 printf(" Connected to %s", remotehost);
2423 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2424 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2425 hname[sizeof(hname) - 1] = 0;
2426 if (strcmp(hname, remotehost) != 0)
2427 printf(" (%s)", hname);
2432 printf(" Logged in anonymously\r\n");
2434 printf(" Logged in as %s\r\n", pw->pw_name);
2435 } else if (askpasswd)
2436 printf(" Waiting for password\r\n");
2438 printf(" Waiting for user name\r\n");
2439 printf(" TYPE: %s", typenames[type]);
2440 if (type == TYPE_A || type == TYPE_E)
2441 printf(", FORM: %s", formnames[form]);
2444 printf(" %d", CHAR_BIT);
2446 printf(" %d", bytesize); /* need definition! */
2448 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2449 strunames[stru], modenames[mode]);
2451 printf(" Data connection open\r\n");
2452 else if (pdata != -1) {
2456 } else if (usedefault == 0) {
2460 #define UC(b) (((int) b) & 0xff)
2462 printf(" EPSV only mode (EPSV ALL)\r\n");
2467 if (su->su_family == AF_INET) {
2468 a = (u_char *) &su->su_sin.sin_addr;
2469 p = (u_char *) &su->su_sin.sin_port;
2470 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2471 ispassive ? "PASV" : "PORT",
2472 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2473 UC(p[0]), UC(p[1]));
2480 switch (su->su_family) {
2482 a = (u_char *) &su->su_sin.sin_addr;
2483 p = (u_char *) &su->su_sin.sin_port;
2484 alen = sizeof(su->su_sin.sin_addr);
2488 a = (u_char *) &su->su_sin6.sin6_addr;
2489 p = (u_char *) &su->su_sin6.sin6_port;
2490 alen = sizeof(su->su_sin6.sin6_addr);
2498 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2500 for (i = 0; i < alen; i++)
2501 printf("%d,", UC(a[i]));
2502 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2511 switch (su->su_family) {
2523 union sockunion tmp;
2526 if (tmp.su_family == AF_INET6)
2527 tmp.su_sin6.sin6_scope_id = 0;
2528 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2529 hname, sizeof(hname) - 1, NULL, 0,
2531 hname[sizeof(hname) - 1] = 0;
2532 printf(" %s |%d|%s|%d|\r\n",
2533 ispassive ? "EPSV" : "EPRT",
2534 af, hname, htons(tmp.su_port));
2540 printf(" No data connection\r\n");
2541 reply(211, "End of status.");
2548 reply(451, "Error in server: %s", s);
2549 reply(221, "Closing connection due to server error.");
2555 reply(int n, const char *fmt, ...)
2559 (void)printf("%d ", n);
2561 (void)vprintf(fmt, ap);
2563 (void)printf("\r\n");
2564 (void)fflush(stdout);
2566 syslog(LOG_DEBUG, "<--- %d ", n);
2568 vsyslog(LOG_DEBUG, fmt, ap);
2574 lreply(int n, const char *fmt, ...)
2578 (void)printf("%d- ", n);
2580 (void)vprintf(fmt, ap);
2582 (void)printf("\r\n");
2583 (void)fflush(stdout);
2585 syslog(LOG_DEBUG, "<--- %d- ", n);
2587 vsyslog(LOG_DEBUG, fmt, ap);
2596 reply(250, "%s command successful.", s);
2603 reply(502, "%s command not implemented.", s);
2612 if ((cp = strchr(cbuf,'\n')))
2614 reply(500, "%s: command not understood.", cbuf);
2622 LOGCMD("delete", name);
2623 if (lstat(name, &st) < 0) {
2624 perror_reply(550, name);
2627 if (S_ISDIR(st.st_mode)) {
2628 if (rmdir(name) < 0) {
2629 perror_reply(550, name);
2634 if (guest && noguestmod) {
2635 reply(550, "Operation not permitted.");
2638 if (unlink(name) < 0) {
2639 perror_reply(550, name);
2650 if (chdir(path) < 0)
2651 perror_reply(550, path);
2661 LOGCMD("mkdir", name);
2662 if (guest && noguestmkd)
2663 reply(550, "Operation not permitted.");
2664 else if (mkdir(name, 0777) < 0)
2665 perror_reply(550, name);
2667 if ((s = doublequote(name)) == NULL)
2668 fatalerror("Ran out of memory.");
2669 reply(257, "\"%s\" directory created.", s);
2675 removedir(char *name)
2678 LOGCMD("rmdir", name);
2679 if (rmdir(name) < 0)
2680 perror_reply(550, name);
2688 char *s, path[MAXPATHLEN + 1];
2690 if (getcwd(path, sizeof(path)) == NULL)
2691 perror_reply(550, "Get current directory");
2693 if ((s = doublequote(path)) == NULL)
2694 fatalerror("Ran out of memory.");
2695 reply(257, "\"%s\" is current directory.", s);
2701 renamefrom(char *name)
2705 if (guest && noguestmod) {
2706 reply(550, "Operation not permitted.");
2709 if (lstat(name, &st) < 0) {
2710 perror_reply(550, name);
2713 reply(350, "File exists, ready for destination name.");
2718 renamecmd(char *from, char *to)
2722 LOGCMD2("rename", from, to);
2724 if (guest && (stat(to, &st) == 0)) {
2725 reply(550, "%s: permission denied.", to);
2729 if (rename(from, to) < 0)
2730 perror_reply(550, "rename");
2736 dolog(struct sockaddr *who)
2738 char who_name[NI_MAXHOST];
2740 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2741 remotehost[sizeof(remotehost) - 1] = 0;
2742 if (getnameinfo(who, who->sa_len,
2743 who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
2745 who_name[sizeof(who_name) - 1] = 0;
2748 #ifdef VIRTUAL_HOSTING
2749 if (thishost != firsthost)
2750 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2751 remotehost, hostname);
2754 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2756 setproctitle("%s", proctitle);
2757 #endif /* SETPROCTITLE */
2760 #ifdef VIRTUAL_HOSTING
2761 if (thishost != firsthost)
2762 syslog(LOG_INFO, "connection from %s (%s) to %s",
2763 remotehost, who_name, hostname);
2766 syslog(LOG_INFO, "connection from %s (%s)",
2767 remotehost, who_name);
2772 * Record logout in wtmp file
2773 * and exit with supplied status.
2776 dologout(int status)
2779 if (logged_in && dowtmp) {
2782 setusercontext(NULL, getpwuid(0), 0, LOGIN_SETALL & ~(LOGIN_SETLOGIN |
2783 LOGIN_SETUSER | LOGIN_SETGROUP | LOGIN_SETPATH |
2786 ftpd_logwtmp(wtmpid, NULL, NULL);
2788 /* beware of flushing buffers after a SIGPIPE */
2806 syslog(LOG_ERR, "Internal: maskurg() while no transfer");
2811 sigaddset(&sset, SIGURG);
2812 sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
2822 syslog(LOG_ERR, "Internal: flagxfer(1): "
2823 "transfer already under way");
2829 syslog(LOG_ERR, "Internal: flagxfer(0): "
2830 "no active transfer");
2837 * Returns 0 if OK to resume or -1 if abort requested.
2846 syslog(LOG_ERR, "Internal: myoob() while no transfer");
2850 ret = get_line(cp, 7, stdin);
2852 reply(221, "You could at least say goodbye.");
2854 } else if (ret == -2) {
2855 /* Ignore truncated command. */
2859 if (strcmp(cp, "ABOR\r\n") == 0) {
2861 reply(426, "Transfer aborted. Data connection closed.");
2862 reply(226, "Abort successful.");
2865 if (strcmp(cp, "STAT\r\n") == 0) {
2867 if (file_size != -1)
2868 reply(213, "Status: %jd of %jd bytes transferred.",
2869 (intmax_t)byte_count, (intmax_t)file_size);
2871 reply(213, "Status: %jd bytes transferred.",
2872 (intmax_t)byte_count);
2878 * Note: a response of 425 is not mentioned as a possible response to
2879 * the PASV command in RFC959. However, it has been blessed as
2880 * a legitimate response by Jon Postel in a telephone conversation
2881 * with Rick Adams on 25 Jan 89.
2890 if (pdata >= 0) /* close old port if one set */
2893 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2895 perror_reply(425, "Can't open passive connection");
2899 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2900 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2905 if (ctrl_addr.su_family == AF_INET) {
2906 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2907 : IP_PORTRANGE_DEFAULT;
2909 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2910 &on, sizeof(on)) < 0)
2914 #ifdef IPV6_PORTRANGE
2915 if (ctrl_addr.su_family == AF_INET6) {
2916 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2917 : IPV6_PORTRANGE_DEFAULT;
2919 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2920 &on, sizeof(on)) < 0)
2925 pasv_addr = ctrl_addr;
2926 pasv_addr.su_port = 0;
2927 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2930 (void) seteuid(pw->pw_uid);
2932 len = sizeof(pasv_addr);
2933 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2935 if (listen(pdata, 1) < 0)
2937 if (pasv_addr.su_family == AF_INET)
2938 a = (char *) &pasv_addr.su_sin.sin_addr;
2939 else if (pasv_addr.su_family == AF_INET6 &&
2940 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2941 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2945 p = (char *) &pasv_addr.su_port;
2947 #define UC(b) (((int) b) & 0xff)
2949 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2950 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2954 (void) seteuid(pw->pw_uid);
2955 (void) close(pdata);
2957 perror_reply(425, "Can't open passive connection");
2962 * Long Passive defined in RFC 1639.
2963 * 228 Entering Long Passive Mode
2964 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2968 long_passive(char *cmd, int pf)
2974 if (pdata >= 0) /* close old port if one set */
2977 if (pf != PF_UNSPEC) {
2978 if (ctrl_addr.su_family != pf) {
2979 switch (ctrl_addr.su_family) {
2992 * only EPRT/EPSV ready clients will understand this
2994 if (strcmp(cmd, "EPSV") == 0 && pf) {
2995 reply(522, "Network protocol mismatch, "
2998 reply(501, "Network protocol mismatch."); /*XXX*/
3004 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
3006 perror_reply(425, "Can't open passive connection");
3010 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
3011 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
3015 pasv_addr = ctrl_addr;
3016 pasv_addr.su_port = 0;
3017 len = pasv_addr.su_len;
3020 if (ctrl_addr.su_family == AF_INET) {
3021 on = restricted_data_ports ? IP_PORTRANGE_HIGH
3022 : IP_PORTRANGE_DEFAULT;
3024 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
3025 &on, sizeof(on)) < 0)
3029 #ifdef IPV6_PORTRANGE
3030 if (ctrl_addr.su_family == AF_INET6) {
3031 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
3032 : IPV6_PORTRANGE_DEFAULT;
3034 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
3035 &on, sizeof(on)) < 0)
3040 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
3043 (void) seteuid(pw->pw_uid);
3045 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
3047 if (listen(pdata, 1) < 0)
3050 #define UC(b) (((int) b) & 0xff)
3052 if (strcmp(cmd, "LPSV") == 0) {
3053 p = (char *)&pasv_addr.su_port;
3054 switch (pasv_addr.su_family) {
3056 a = (char *) &pasv_addr.su_sin.sin_addr;
3059 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3060 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3061 2, UC(p[0]), UC(p[1]));
3064 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
3065 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
3068 a = (char *) &pasv_addr.su_sin6.sin6_addr;
3070 "Entering Long Passive Mode "
3071 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3072 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3073 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3074 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3075 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3076 2, UC(p[0]), UC(p[1]));
3079 } else if (strcmp(cmd, "EPSV") == 0) {
3080 switch (pasv_addr.su_family) {
3083 reply(229, "Entering Extended Passive Mode (|||%d|)",
3084 ntohs(pasv_addr.su_port));
3088 /* more proper error code? */
3092 (void) seteuid(pw->pw_uid);
3093 (void) close(pdata);
3095 perror_reply(425, "Can't open passive connection");
3100 * Generate unique name for file with basename "local"
3101 * and open the file in order to avoid possible races.
3102 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3103 * Return descriptor to the file, set "name" to its name.
3105 * Generates failure reply on error.
3108 guniquefd(char *local, char **name)
3110 static char new[MAXPATHLEN];
3116 cp = strrchr(local, '/');
3119 if (stat(cp ? local : ".", &st) < 0) {
3120 perror_reply(553, cp ? local : ".");
3125 * Let not overwrite dirname with counter suffix.
3127 * In this extreme case dot won't be put in front of suffix.
3129 if (strlen(local) > sizeof(new) - 4) {
3130 reply(553, "Pathname too long.");
3135 /* -4 is for the .nn<null> we put on the end below */
3136 (void) snprintf(new, sizeof(new) - 4, "%s", local);
3137 cp = new + strlen(new);
3139 * Don't generate dotfile unless requested explicitly.
3140 * This covers the case when basename gets truncated off
3143 if (cp > new && cp[-1] != '/')
3145 for (count = 0; count < 100; count++) {
3146 /* At count 0 try unmodified name */
3148 (void)sprintf(cp, "%d", count);
3149 if ((fd = open(count ? new : local,
3150 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3151 *name = count ? new : local;
3154 if (errno != EEXIST) {
3155 perror_reply(553, count ? new : local);
3159 reply(452, "Unique file name cannot be created.");
3164 * Format and send reply containing system error number.
3167 perror_reply(int code, char *string)
3170 reply(code, "%s: %s.", string, strerror(errno));
3173 static char *onefile[] = {
3179 send_file_list(char *whichf)
3185 char **dirlist, *dirname;
3190 if (strpbrk(whichf, "~{[*?") != NULL) {
3191 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3193 memset(&gl, 0, sizeof(gl));
3194 gl.gl_matchc = MAXGLOBARGS;
3195 flags |= GLOB_LIMIT;
3197 if (glob(whichf, flags, 0, &gl)) {
3198 reply(550, "No matching files found.");
3200 } else if (gl.gl_pathc == 0) {
3202 perror_reply(550, whichf);
3205 dirlist = gl.gl_pathv;
3207 onefile[0] = whichf;
3212 while ((dirname = *dirlist++)) {
3213 if (stat(dirname, &st) < 0) {
3215 * If user typed "ls -l", etc, and the client
3216 * used NLST, do what the user meant.
3218 if (dirname[0] == '-' && *dirlist == NULL &&
3220 retrieve(_PATH_LS " %s", dirname);
3222 perror_reply(550, whichf);
3226 if (S_ISREG(st.st_mode)) {
3228 dout = dataconn("file list", -1, "w");
3234 fprintf(dout, "%s%s\n", dirname,
3235 type == TYPE_A ? "\r" : "");
3239 byte_count += strlen(dirname) +
3240 (type == TYPE_A ? 2 : 1);
3241 CHECKOOB(goto abrt);
3243 } else if (!S_ISDIR(st.st_mode))
3246 if ((dirp = opendir(dirname)) == NULL)
3249 while ((dir = readdir(dirp)) != NULL) {
3250 char nbuf[MAXPATHLEN];
3252 CHECKOOB(goto abrt);
3254 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
3256 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3260 snprintf(nbuf, sizeof(nbuf),
3261 "%s/%s", dirname, dir->d_name);
3264 * We have to do a stat to insure it's
3265 * not a directory or special file.
3267 if (simple || (stat(nbuf, &st) == 0 &&
3268 S_ISREG(st.st_mode))) {
3270 dout = dataconn("file list", -1, "w");
3276 if (nbuf[0] == '.' && nbuf[1] == '/')
3277 fprintf(dout, "%s%s\n", &nbuf[2],
3278 type == TYPE_A ? "\r" : "");
3280 fprintf(dout, "%s%s\n", nbuf,
3281 type == TYPE_A ? "\r" : "");
3285 byte_count += strlen(nbuf) +
3286 (type == TYPE_A ? 2 : 1);
3287 CHECKOOB(goto abrt);
3290 (void) closedir(dirp);
3295 reply(550, "No files found.");
3296 else if (ferror(dout))
3297 data_err: perror_reply(550, "Data connection");
3299 reply(226, "Transfer complete.");
3304 (void) fclose(dout);
3309 (void) closedir(dirp);
3317 reapchild(int signo)
3319 while (waitpid(-1, NULL, WNOHANG) > 0);
3322 #ifdef OLD_SETPROCTITLE
3324 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.)
3325 * Warning, since this is usually started from inetd.conf, it often doesn't
3326 * have much of an environment or arglist to overwrite.
3329 setproctitle(const char *fmt, ...)
3337 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
3339 /* make ps print our process name */
3344 if (i > LastArgv - p - 2) {
3345 i = LastArgv - p - 2;
3350 if (ch != '\n' && ch != '\r')
3352 while (p < LastArgv)
3355 #endif /* OLD_SETPROCTITLE */
3358 appendf(char **strp, char *fmt, ...)
3364 vasprintf(&p, fmt, ap);
3367 fatalerror("Ran out of memory.");
3372 asprintf(strp, "%s%s", ostr, p);
3374 fatalerror("Ran out of memory.");
3380 logcmd(char *cmd, char *file1, char *file2, off_t cnt)
3383 char wd[MAXPATHLEN + 1];
3388 if (getcwd(wd, sizeof(wd) - 1) == NULL)
3389 strcpy(wd, strerror(errno));
3391 appendf(&msg, "%s", cmd);
3393 appendf(&msg, " %s", file1);
3395 appendf(&msg, " %s", file2);
3397 appendf(&msg, " = %jd bytes", (intmax_t)cnt);
3398 appendf(&msg, " (wd: %s", wd);
3399 if (guest || dochroot)
3400 appendf(&msg, "; chrooted");
3402 syslog(LOG_INFO, "%s", msg);
3407 logxfer(char *name, off_t size, time_t start)
3409 char buf[MAXPATHLEN + 1024];
3410 char path[MAXPATHLEN + 1];
3415 if (realpath(name, path) == NULL) {
3416 syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
3419 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n",
3420 ctime(&now)+4, ident, remotehost,
3421 path, (intmax_t)size,
3422 (long)(now - start + (now == start)));
3423 write(statfd, buf, strlen(buf));
3428 doublequote(char *s)
3433 for (p = s, n = 0; *p; p++)
3437 if ((s2 = malloc(p - s + n + 1)) == NULL)
3440 for (p = s2; *s; s++, p++) {
3441 if ((*p = *s) == '"')
3449 /* setup server socket for specified address family */
3450 /* if af is PF_UNSPEC more than one socket may be returned */
3451 /* the returned list is dynamically allocated, so caller needs to free it */
3453 socksetup(int af, char *bindname, const char *bindport)
3455 struct addrinfo hints, *res, *r;
3456 int error, maxs, *s, *socks;
3459 memset(&hints, 0, sizeof(hints));
3460 hints.ai_flags = AI_PASSIVE;
3461 hints.ai_family = af;
3462 hints.ai_socktype = SOCK_STREAM;
3463 error = getaddrinfo(bindname, bindport, &hints, &res);
3465 syslog(LOG_ERR, "%s", gai_strerror(error));
3466 if (error == EAI_SYSTEM)
3467 syslog(LOG_ERR, "%s", strerror(errno));
3471 /* Count max number of sockets we may open */
3472 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3474 socks = malloc((maxs + 1) * sizeof(int));
3477 syslog(LOG_ERR, "couldn't allocate memory for sockets");
3481 *socks = 0; /* num of sockets counter at start of array */
3483 for (r = res; r; r = r->ai_next) {
3484 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3486 syslog(LOG_DEBUG, "control socket: %m");
3489 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3490 &on, sizeof(on)) < 0)
3492 "control setsockopt (SO_REUSEADDR): %m");
3493 if (r->ai_family == AF_INET6) {
3494 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3495 &on, sizeof(on)) < 0)
3497 "control setsockopt (IPV6_V6ONLY): %m");
3499 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3500 syslog(LOG_DEBUG, "control bind: %m");
3512 syslog(LOG_ERR, "control socket: Couldn't bind to any socket");