2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 static char copyright[] =
35 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
36 The Regents of the University of California. All rights reserved.\n";
42 static char sccsid[] = "@(#)ftpd.c 8.4 (Berkeley) 4/16/94";
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
52 #include <sys/param.h>
53 #include <sys/ioctl.h>
55 #include <sys/socket.h>
60 #include <netinet/in.h>
61 #include <netinet/in_systm.h>
62 #include <netinet/ip.h>
63 #include <netinet/tcp.h>
67 #include <arpa/inet.h>
68 #include <arpa/telnet.h>
91 #include <login_cap.h>
95 #include <security/pam_appl.h>
98 #include "blacklist_client.h"
99 #include "pathnames.h"
104 static char version[] = "Version 6.00LS";
107 union sockunion ctrl_addr;
108 union sockunion data_source;
109 union sockunion data_dest;
110 union sockunion his_addr;
111 union sockunion pasv_addr;
116 int hostinfo = 1; /* print host-specific info in messages */
121 int timeout = 900; /* timeout after 15 minutes of inactivity */
122 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
124 int restricted_data_ports = 1;
125 int paranoid = 1; /* be extra careful about security */
126 int anon_only = 0; /* Only anonymous ftp allowed */
127 int assumeutf8 = 0; /* Assume that server file names are in UTF-8 */
136 int stru; /* avoid C keyword */
138 int usedefault = 1; /* for data transfers */
139 int pdata = -1; /* for passive mode */
140 int readonly = 0; /* Server is in readonly mode. */
141 int noepsv = 0; /* EPSV command is disabled. */
142 int noretr = 0; /* RETR command is disabled. */
143 int noguestretr = 0; /* RETR command is disabled for anon users. */
144 int noguestmkd = 0; /* MKD command is disabled for anon users. */
145 int noguestmod = 1; /* anon users may not modify existing files. */
146 int use_blacklist = 0;
150 #if !defined(CMASK) || CMASK == 0
154 int defumask = CMASK; /* default umask value */
159 #ifdef VIRTUAL_HOSTING
162 static struct ftphost {
163 struct ftphost *next;
164 struct addrinfo *hostinfo;
170 } *thishost, *firsthost;
173 char remotehost[NI_MAXHOST];
176 static char wtmpid[20];
179 static int auth_pam(struct passwd**, const char*);
180 pam_handle_t *pamh = NULL;
183 static struct opie opiedata;
184 static char opieprompt[OPIE_CHALLENGE_MAX+1];
187 char *pid_file = NULL; /* means default location to pidfile(3) */
190 * Limit number of pathnames that glob can return.
191 * A limit of 0 indicates the number of pathnames is unlimited.
193 #define MAXGLOBARGS 16384
197 * Timeout intervals for retrying connections
198 * to hosts that don't accept PORT cmds. This
199 * is a kludge, but given the problems with TCP...
201 #define SWAITMAX 90 /* wait at most 90 seconds */
202 #define SWAITINT 5 /* interval between retries */
204 int swaitmax = SWAITMAX;
205 int swaitint = SWAITINT;
208 #ifdef OLD_SETPROCTITLE
209 char **Argv = NULL; /* pointer to argument vector */
210 char *LastArgv = NULL; /* end of argv */
211 #endif /* OLD_SETPROCTITLE */
212 char proctitle[LINE_MAX]; /* initial part of title */
213 #endif /* SETPROCTITLE */
215 #define LOGCMD(cmd, file) logcmd((cmd), (file), NULL, -1)
216 #define LOGCMD2(cmd, file1, file2) logcmd((cmd), (file1), (file2), -1)
217 #define LOGBYTES(cmd, file, cnt) logcmd((cmd), (file), NULL, (cnt))
219 static volatile sig_atomic_t recvurg;
220 static int transflag; /* NB: for debugging only */
222 #define STARTXFER flagxfer(1)
223 #define ENDXFER flagxfer(0)
225 #define START_UNSAFE maskurg(1)
226 #define END_UNSAFE maskurg(0)
228 /* It's OK to put an `else' clause after this macro. */
229 #define CHECKOOB(action) \
238 #ifdef VIRTUAL_HOSTING
239 static void inithosts(int);
240 static void selecthost(union sockunion *);
242 static void ack(char *);
243 static void sigurg(int);
244 static void maskurg(int);
245 static void flagxfer(int);
246 static int myoob(void);
247 static int checkuser(char *, char *, int, char **, int *);
248 static FILE *dataconn(char *, off_t, char *);
249 static void dolog(struct sockaddr *);
250 static void end_login(void);
251 static FILE *getdatasock(char *);
252 static int guniquefd(char *, char **);
253 static void lostconn(int);
254 static void sigquit(int);
255 static int receive_data(FILE *, FILE *);
256 static int send_data(FILE *, FILE *, size_t, off_t, int);
257 static struct passwd *
259 static char *sgetsave(char *);
260 static void reapchild(int);
261 static void appendf(char **, char *, ...) __printflike(2, 3);
262 static void logcmd(char *, char *, char *, off_t);
263 static void logxfer(char *, off_t, time_t);
264 static char *doublequote(char *);
265 static int *socksetup(int, char *, const char *);
268 main(int argc, char *argv[], char **envp)
271 int ch, on = 1, tos, s = STDIN_FILENO;
272 char *cp, line[LINE_MAX];
274 char *bindname = NULL;
275 const char *bindport = "ftp";
276 int family = AF_UNSPEC;
279 tzset(); /* in case no timezone database in ~ftp */
280 sigemptyset(&sa.sa_mask);
281 sa.sa_flags = SA_RESTART;
283 #ifdef OLD_SETPROCTITLE
285 * Save start and extent of argv for setproctitle.
290 LastArgv = envp[-1] + strlen(envp[-1]);
291 #endif /* OLD_SETPROCTITLE */
294 * Prevent diagnostic messages from appearing on stderr.
295 * We run as a daemon or from inetd; in both cases, there's
296 * more reason in logging to syslog.
298 (void) freopen(_PATH_DEVNULL, "w", stderr);
302 * LOG_NDELAY sets up the logging connection immediately,
303 * necessary for anonymous ftp's that chroot and can't do it later.
305 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
307 while ((ch = getopt(argc, argv,
308 "468a:ABdDEhlmMoOp:P:rRSt:T:u:UvW")) != -1) {
311 family = (family == AF_INET6) ? AF_UNSPEC : AF_INET;
315 family = (family == AF_INET) ? AF_UNSPEC : AF_INET6;
334 syslog(LOG_WARNING, "not compiled with USE_BLACKLIST support");
355 logging++; /* > 1 == extra logging */
395 timeout = atoi(optarg);
396 if (maxtimeout < timeout)
397 maxtimeout = timeout;
401 maxtimeout = atoi(optarg);
402 if (timeout > maxtimeout)
403 timeout = maxtimeout;
410 val = strtol(optarg, &optarg, 8);
411 if (*optarg != '\0' || val < 0)
412 syslog(LOG_WARNING, "bad value for -u");
418 restricted_data_ports = 0;
430 syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
435 /* handle filesize limit gracefully */
436 sa.sa_handler = SIG_IGN;
437 (void)sigaction(SIGXFSZ, &sa, NULL);
440 int *ctl_sock, fd, maxfd = -1, nfds, i;
441 fd_set defreadfds, readfds;
445 if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
446 if (errno == EEXIST) {
447 syslog(LOG_ERR, "%s already running, pid %d",
448 getprogname(), (int)pid);
451 syslog(LOG_WARNING, "pidfile_open: %m");
455 * Detach from parent.
457 if (daemon(1, 1) < 0) {
458 syslog(LOG_ERR, "failed to become a daemon");
462 if (pfh != NULL && pidfile_write(pfh) == -1)
463 syslog(LOG_WARNING, "pidfile_write: %m");
465 sa.sa_handler = reapchild;
466 (void)sigaction(SIGCHLD, &sa, NULL);
468 #ifdef VIRTUAL_HOSTING
473 * Open a socket, bind it to the FTP port, and start
476 ctl_sock = socksetup(family, bindname, bindport);
477 if (ctl_sock == NULL)
480 FD_ZERO(&defreadfds);
481 for (i = 1; i <= *ctl_sock; i++) {
482 FD_SET(ctl_sock[i], &defreadfds);
483 if (listen(ctl_sock[i], 32) < 0) {
484 syslog(LOG_ERR, "control listen: %m");
487 if (maxfd < ctl_sock[i])
492 * Loop forever accepting connection requests and forking off
493 * children to handle them.
496 FD_COPY(&defreadfds, &readfds);
497 nfds = select(maxfd + 1, &readfds, NULL, NULL, 0);
499 if (nfds < 0 && errno != EINTR)
500 syslog(LOG_WARNING, "select: %m");
505 for (i = 1; i <= *ctl_sock; i++)
506 if (FD_ISSET(ctl_sock[i], &readfds)) {
507 addrlen = sizeof(his_addr);
508 fd = accept(ctl_sock[i],
509 (struct sockaddr *)&his_addr,
516 switch (pid = fork()) {
520 (void) dup2(fd, STDOUT_FILENO);
522 for (i = 1; i <= *ctl_sock; i++)
528 syslog(LOG_WARNING, "fork: %m");
536 addrlen = sizeof(his_addr);
537 if (getpeername(s, (struct sockaddr *)&his_addr, &addrlen) < 0) {
538 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
542 #ifdef VIRTUAL_HOSTING
543 if (his_addr.su_family == AF_INET6 &&
544 IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))
547 family = his_addr.su_family;
553 sa.sa_handler = SIG_DFL;
554 (void)sigaction(SIGCHLD, &sa, NULL);
556 sa.sa_handler = sigurg;
557 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
558 (void)sigaction(SIGURG, &sa, NULL);
560 sigfillset(&sa.sa_mask); /* block all signals in handler */
561 sa.sa_flags = SA_RESTART;
562 sa.sa_handler = sigquit;
563 (void)sigaction(SIGHUP, &sa, NULL);
564 (void)sigaction(SIGINT, &sa, NULL);
565 (void)sigaction(SIGQUIT, &sa, NULL);
566 (void)sigaction(SIGTERM, &sa, NULL);
568 sa.sa_handler = lostconn;
569 (void)sigaction(SIGPIPE, &sa, NULL);
571 addrlen = sizeof(ctrl_addr);
572 if (getsockname(s, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
573 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
576 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
577 #ifdef VIRTUAL_HOSTING
578 /* select our identity from virtual host table */
579 selecthost(&ctrl_addr);
582 if (ctrl_addr.su_family == AF_INET)
584 tos = IPTOS_LOWDELAY;
585 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
586 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
590 * Disable Nagle on the control channel so that we don't have to wait
591 * for peer's ACK before issuing our next reply.
593 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
594 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
596 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
598 (void)snprintf(wtmpid, sizeof(wtmpid), "%xftpd", getpid());
600 /* Try to handle urgent data inline */
602 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
603 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
607 if (fcntl(s, F_SETOWN, getpid()) == -1)
608 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
610 dolog((struct sockaddr *)&his_addr);
612 * Set up default state
621 /* If logins are disabled, print out the message. */
622 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
623 while (fgets(line, sizeof(line), fd) != NULL) {
624 if ((cp = strchr(line, '\n')) != NULL)
626 lreply(530, "%s", line);
628 (void) fflush(stdout);
630 reply(530, "System not available.");
633 #ifdef VIRTUAL_HOSTING
634 fd = fopen(thishost->welcome, "r");
636 fd = fopen(_PATH_FTPWELCOME, "r");
639 while (fgets(line, sizeof(line), fd) != NULL) {
640 if ((cp = strchr(line, '\n')) != NULL)
642 lreply(220, "%s", line);
644 (void) fflush(stdout);
646 /* reply(220,) must follow */
648 #ifndef VIRTUAL_HOSTING
649 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
650 fatalerror("Ran out of memory.");
651 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
653 hostname[MAXHOSTNAMELEN - 1] = '\0';
656 reply(220, "%s FTP server (%s) ready.", hostname, version);
658 reply(220, "FTP server ready.");
670 syslog(LOG_DEBUG, "lost connection");
678 syslog(LOG_ERR, "got signal %d", signo);
682 #ifdef VIRTUAL_HOSTING
684 * read in virtual host tables (if they exist)
688 inithosts(int family)
693 char *cp, *mp, *line;
695 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
696 struct ftphost *hrp, *lhrp;
697 struct addrinfo hints, *res, *ai;
700 * Fill in the default host information
702 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
703 fatalerror("Ran out of memory.");
704 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
706 hostname[MAXHOSTNAMELEN - 1] = '\0';
707 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
708 fatalerror("Ran out of memory.");
709 hrp->hostname = hostname;
710 hrp->hostinfo = NULL;
712 memset(&hints, 0, sizeof(hints));
713 hints.ai_flags = AI_PASSIVE;
714 hints.ai_family = family;
715 hints.ai_socktype = SOCK_STREAM;
716 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
718 hrp->statfile = _PATH_FTPDSTATFILE;
719 hrp->welcome = _PATH_FTPWELCOME;
720 hrp->loginmsg = _PATH_FTPLOGINMESG;
721 hrp->anonuser = "ftp";
723 thishost = firsthost = lhrp = hrp;
724 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
725 int addrsize, gothost;
729 while ((line = fgetln(fp, &len)) != NULL) {
735 if (line[len - 1] == '\n') {
736 line[len - 1] = '\0';
739 if ((mp = malloc(len + 1)) == NULL)
740 fatalerror("Ran out of memory.");
741 memcpy(mp, line, len);
745 cp = strtok(line, " \t");
746 /* skip empty lines */
753 statfile = _PATH_FTPDSTATFILE;
754 welcome = _PATH_FTPWELCOME;
755 loginmsg = _PATH_FTPLOGINMESG;
758 * Preparse the line so we can use its info
759 * for all the addresses associated with
760 * the virtual host name.
761 * Field 0, the virtual host name, is special:
762 * it's already parsed off and will be strdup'ed
763 * later, after we know its canonical form.
765 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
766 if (*cp != '-' && (cp = strdup(cp)))
768 case 1: /* anon user permissions */
771 case 2: /* statistics file */
774 case 3: /* welcome message */
777 case 4: /* login message */
780 default: /* programming error */
785 hints.ai_flags = AI_PASSIVE;
786 hints.ai_family = family;
787 hints.ai_socktype = SOCK_STREAM;
788 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
790 for (ai = res; ai != NULL && ai->ai_addr != NULL;
794 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
797 for (hi = hrp->hostinfo; hi != NULL;
799 if (hi->ai_addrlen == ai->ai_addrlen &&
802 ai->ai_addr->sa_len) == 0) {
810 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
812 hrp->hostname = NULL;
815 if (hrp->hostinfo && hrp->hostinfo != res)
816 freeaddrinfo(hrp->hostinfo);
817 insert = 0; /* host already in the chain */
822 * determine hostname to use.
823 * force defined name if there is a valid alias
824 * otherwise fallback to primary hostname
826 /* XXX: getaddrinfo() can't do alias check */
827 switch(hrp->hostinfo->ai_family) {
829 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
830 addrsize = sizeof(struct in_addr);
833 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
834 addrsize = sizeof(struct in6_addr);
837 /* should not reach here */
838 freeaddrinfo(hrp->hostinfo);
840 free(hrp); /*not in chain, can free*/
842 hrp->hostinfo = NULL; /*mark as blank*/
846 if ((hp = getipnodebyaddr(addr, addrsize,
847 hrp->hostinfo->ai_family,
848 &hp_error)) != NULL) {
849 if (strcmp(vhost, hp->h_name) != 0) {
850 if (hp->h_aliases == NULL)
854 while (hp->h_aliases[i] &&
855 strcmp(vhost, hp->h_aliases[i]) != 0)
857 if (hp->h_aliases[i] == NULL)
863 strcmp(hrp->hostname, vhost) != 0) {
865 hrp->hostname = NULL;
867 if (hrp->hostname == NULL &&
868 (hrp->hostname = strdup(vhost)) == NULL) {
869 freeaddrinfo(hrp->hostinfo);
870 hrp->hostinfo = NULL; /* mark as blank */
875 hrp->anonuser = anonuser;
876 hrp->statfile = statfile;
877 hrp->welcome = welcome;
878 hrp->loginmsg = loginmsg;
896 selecthost(union sockunion *su)
901 struct in6_addr *mapped_in6 = NULL;
907 * XXX IPv4 mapped IPv6 addr consideraton,
908 * specified in rfc2373.
910 if (su->su_family == AF_INET6 &&
911 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
912 mapped_in6 = &su->su_sin6.sin6_addr;
915 hrp = thishost = firsthost; /* default */
918 while (hrp != NULL) {
919 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
920 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
925 /* XXX IPv4 mapped IPv6 addr consideraton */
926 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
927 (memcmp(&mapped_in6->s6_addr[12],
928 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
929 sizeof(struct in_addr)) == 0)) {
939 /* setup static variables as appropriate */
940 hostname = thishost->hostname;
941 ftpuser = thishost->anonuser;
946 * Helper function for sgetpwnam().
951 char *new = malloc(strlen(s) + 1);
954 reply(421, "Ran out of memory.");
958 (void) strcpy(new, s);
963 * Save the result of a getpwnam. Used for USER command, since
964 * the data returned must not be clobbered by any other command
966 * NB: The data returned by sgetpwnam() will remain valid until
967 * the next call to this function. Its difference from getpwnam()
968 * is that sgetpwnam() is known to be called from ftpd code only.
970 static struct passwd *
971 sgetpwnam(char *name)
973 static struct passwd save;
976 if ((p = getpwnam(name)) == NULL)
980 free(save.pw_passwd);
987 save.pw_name = sgetsave(p->pw_name);
988 save.pw_passwd = sgetsave(p->pw_passwd);
989 save.pw_class = sgetsave(p->pw_class);
990 save.pw_gecos = sgetsave(p->pw_gecos);
991 save.pw_dir = sgetsave(p->pw_dir);
992 save.pw_shell = sgetsave(p->pw_shell);
996 static int login_attempts; /* number of failed login attempts */
997 static int askpasswd; /* had user command, ask for passwd */
998 static char curname[MAXLOGNAME]; /* current USER name */
1002 * Sets global passwd pointer pw if named account exists and is acceptable;
1003 * sets askpasswd if a PASS command is expected. If logged in previously,
1004 * need to reset state. If name is "ftp" or "anonymous", the name is not in
1005 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
1006 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
1007 * requesting login privileges. Disallow anyone who does not have a standard
1008 * shell as returned by getusershell(). Disallow anyone mentioned in the file
1009 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
1019 reply(530, "Can't change user from guest login.");
1021 } else if (dochroot) {
1022 reply(530, "Can't change user from chroot user.");
1029 #ifdef VIRTUAL_HOSTING
1030 pw = sgetpwnam(thishost->anonuser);
1032 pw = sgetpwnam("ftp");
1034 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1035 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL, &ecode) ||
1036 (ecode != 0 && ecode != ENOENT))
1037 reply(530, "User %s access denied.", name);
1038 else if (checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL, &ecode) ||
1039 (ecode != 0 && ecode != ENOENT))
1040 reply(530, "User %s access denied.", name);
1041 else if (pw != NULL) {
1045 "Guest login ok, send your email address as password.");
1047 reply(530, "User %s unknown.", name);
1048 if (!askpasswd && logging)
1050 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1053 if (anon_only != 0) {
1054 reply(530, "Sorry, only anonymous ftp allowed.");
1058 if ((pw = sgetpwnam(name))) {
1059 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1060 shell = _PATH_BSHELL;
1062 while ((cp = getusershell()) != NULL)
1063 if (strcmp(cp, shell) == 0)
1068 (checkuser(_PATH_FTPUSERS, name, 1, NULL, &ecode) ||
1069 (ecode != 0 && ecode != ENOENT))) {
1070 reply(530, "User %s access denied.", name);
1073 "FTP LOGIN REFUSED FROM %s, %s",
1080 strlcpy(curname, name, sizeof(curname));
1084 /* XXX Kluge! The conversation mechanism needs to be fixed. */
1086 if (opiechallenge(&opiedata, name, opieprompt) == 0) {
1087 pwok = (pw != NULL) &&
1088 opieaccessfile(remotehost) &&
1089 opiealways(pw->pw_dir);
1090 reply(331, "Response to %s %s for %s.",
1091 opieprompt, pwok ? "requested" : "required", name);
1094 reply(331, "Password required for %s.", name);
1098 * Delay before reading passwd after first failed
1099 * attempt to slow down passwd-guessing programs.
1102 sleep(login_attempts);
1106 * Check if a user is in the file "fname",
1107 * return a pointer to a malloc'd string with the rest
1108 * of the matching line in "residue" if not NULL.
1111 checkuser(char *fname, char *name, int pwset, char **residue, int *ecode)
1116 char *line, *mp, *p;
1120 if ((fd = fopen(fname, "r")) != NULL) {
1121 while (!found && (line = fgetln(fd, &len)) != NULL) {
1125 if (line[len - 1] == '\n') {
1126 line[len - 1] = '\0';
1129 if ((mp = malloc(len + 1)) == NULL)
1130 fatalerror("Ran out of memory.");
1131 memcpy(mp, line, len);
1135 /* avoid possible leading and trailing whitespace */
1136 p = strtok(line, " \t");
1137 /* skip empty lines */
1141 * if first chr is '@', check group membership
1147 if (p[1] == '\0') /* single @ matches anyone */
1150 if ((grp = getgrnam(p+1)) == NULL)
1153 * Check user's default group
1155 if (pwset && grp->gr_gid == pw->pw_gid)
1158 * Check supplementary groups
1160 while (!found && grp->gr_mem[i])
1161 found = strcmp(name,
1167 * Otherwise, just check for username match
1170 found = strcmp(p, name) == 0;
1172 * Save the rest of line to "residue" if matched
1174 if (found && residue) {
1175 if ((p = strtok(NULL, "")) != NULL)
1176 p += strspn(p, " \t");
1178 if ((*residue = strdup(p)) == NULL)
1179 fatalerror("Ran out of memory.");
1188 } else if (ecode != NULL)
1194 * Terminate login as previous user, if any, resetting state;
1195 * used when USER command is given or login fails.
1206 setusercontext(NULL, getpwuid(0), 0, LOGIN_SETALL & ~(LOGIN_SETLOGIN |
1207 LOGIN_SETUSER | LOGIN_SETGROUP | LOGIN_SETPATH |
1210 if (logged_in && dowtmp)
1211 ftpd_logwtmp(wtmpid, NULL, NULL);
1215 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1216 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1217 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1218 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1219 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1220 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1232 * the following code is stolen from imap-uw PAM authentication module and
1235 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1238 const char *uname; /* user name */
1239 const char *pass; /* password */
1241 typedef struct cred_t cred_t;
1244 auth_conv(int num_msg, const struct pam_message **msg,
1245 struct pam_response **resp, void *appdata)
1248 cred_t *cred = (cred_t *) appdata;
1249 struct pam_response *reply;
1251 reply = calloc(num_msg, sizeof *reply);
1255 for (i = 0; i < num_msg; i++) {
1256 switch (msg[i]->msg_style) {
1257 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1258 reply[i].resp_retcode = PAM_SUCCESS;
1259 reply[i].resp = COPY_STRING(cred->uname);
1260 /* PAM frees resp. */
1262 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1263 reply[i].resp_retcode = PAM_SUCCESS;
1264 reply[i].resp = COPY_STRING(cred->pass);
1265 /* PAM frees resp. */
1269 reply[i].resp_retcode = PAM_SUCCESS;
1270 reply[i].resp = NULL;
1272 default: /* unknown message style */
1274 return PAM_CONV_ERR;
1283 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1284 * authenticated, or 1 if not authenticated. If some sort of PAM system
1285 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1286 * function returns -1. This can be used as an indication that we should
1287 * fall back to a different authentication mechanism.
1290 auth_pam(struct passwd **ppw, const char *pass)
1292 const char *tmpl_user;
1296 cred_t auth_cred = { (*ppw)->pw_name, pass };
1297 struct pam_conv conv = { &auth_conv, &auth_cred };
1299 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1300 if (e != PAM_SUCCESS) {
1302 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1303 * if context creation has failed in the first place.
1305 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
1309 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1310 if (e != PAM_SUCCESS) {
1311 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1312 pam_strerror(pamh, e));
1313 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1314 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1320 e = pam_authenticate(pamh, 0);
1324 * With PAM we support the concept of a "template"
1325 * user. The user enters a login name which is
1326 * authenticated by PAM, usually via a remote service
1327 * such as RADIUS or TACACS+. If authentication
1328 * succeeds, a different but related "template" name
1329 * is used for setting the credentials, shell, and
1330 * home directory. The name the user enters need only
1331 * exist on the remote authentication server, but the
1332 * template name must be present in the local password
1335 * This is supported by two various mechanisms in the
1336 * individual modules. However, from the application's
1337 * point of view, the template user is always passed
1338 * back as a changed value of the PAM_USER item.
1340 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1342 tmpl_user = (const char *) item;
1343 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1344 *ppw = getpwnam(tmpl_user);
1346 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1347 pam_strerror(pamh, e));
1352 case PAM_USER_UNKNOWN:
1358 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1364 e = pam_acct_mgmt(pamh, 0);
1365 if (e != PAM_SUCCESS) {
1366 syslog(LOG_ERR, "pam_acct_mgmt: %s",
1367 pam_strerror(pamh, e));
1373 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1374 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1381 #endif /* USE_PAM */
1389 login_cap_t *lc = NULL;
1394 char *residue = NULL;
1397 if (logged_in || askpasswd == 0) {
1398 reply(503, "Login with USER first.");
1402 if (!guest) { /* "ftp" is only account allowed no password */
1404 rval = 1; /* failure below */
1408 rval = auth_pam(&pw, passwd);
1414 if (opieverify(&opiedata, passwd) == 0)
1415 xpasswd = pw->pw_passwd;
1417 xpasswd = crypt(passwd, pw->pw_passwd);
1418 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1424 rval = strcmp(pw->pw_passwd, xpasswd);
1425 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1426 rval = 1; /* failure */
1429 * If rval == 1, the user failed the authentication check
1430 * above. If rval == 0, either PAM or local authentication
1434 reply(530, "Login incorrect.");
1435 BLACKLIST_NOTIFY(BLACKLIST_AUTH_FAIL, STDIN_FILENO, "Login incorrect");
1438 "FTP LOGIN FAILED FROM %s",
1440 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1441 "FTP LOGIN FAILED FROM %s, %s",
1442 remotehost, curname);
1445 if (login_attempts++ >= 5) {
1447 "repeated login failures from %s",
1453 BLACKLIST_NOTIFY(BLACKLIST_AUTH_OK, STDIN_FILENO, "Login successful");
1456 login_attempts = 0; /* this time successful */
1457 if (setegid(pw->pw_gid) < 0) {
1458 reply(550, "Can't set gid.");
1461 /* May be overridden by login.conf */
1462 (void) umask(defumask);
1464 if ((lc = login_getpwclass(pw)) != NULL) {
1465 char remote_ip[NI_MAXHOST];
1467 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1468 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1471 remote_ip[sizeof(remote_ip) - 1] = 0;
1472 if (!auth_hostok(lc, remotehost, remote_ip)) {
1473 syslog(LOG_INFO|LOG_AUTH,
1474 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1476 reply(530, "Permission denied.");
1480 if (!auth_timeok(lc, time(NULL))) {
1481 reply(530, "Login not available right now.");
1486 setusercontext(lc, pw, 0, LOGIN_SETALL &
1487 ~(LOGIN_SETRESOURCES | LOGIN_SETUSER | LOGIN_SETPATH | LOGIN_SETENV));
1489 setlogin(pw->pw_name);
1490 (void) initgroups(pw->pw_name, pw->pw_gid);
1495 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1496 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1497 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1498 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1504 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue, &ecode)
1505 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1506 || login_getcapbool(lc, "ftp-chroot", 0)
1510 * It is possible that checkuser() failed to open the chroot file.
1511 * If this is the case, report that logins are un-available, since we
1512 * have no way of checking whether or not the user should be chrooted.
1513 * We ignore ENOENT since it is not required that this file be present.
1515 if (ecode != 0 && ecode != ENOENT) {
1516 reply(530, "Login not available right now.");
1521 /* Disable wtmp logging when chrooting. */
1522 if (dochroot || guest)
1525 ftpd_logwtmp(wtmpid, pw->pw_name,
1526 (struct sockaddr *)&his_addr);
1530 setusercontext(lc, pw, 0, LOGIN_SETRESOURCES);
1533 if (guest && stats && statfd < 0)
1534 #ifdef VIRTUAL_HOSTING
1535 statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1537 statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1543 * For a chrooted local user,
1544 * a) see whether ftpchroot(5) specifies a chroot directory,
1545 * b) extract the directory pathname from the line,
1546 * c) expand it to the absolute pathname if necessary.
1548 if (dochroot && residue &&
1549 (chrootdir = strtok(residue, " \t")) != NULL) {
1550 if (chrootdir[0] != '/')
1551 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1553 chrootdir = strdup(chrootdir); /* make it permanent */
1554 if (chrootdir == NULL)
1555 fatalerror("Ran out of memory.");
1557 if (guest || dochroot) {
1559 * If no chroot directory set yet, use the login directory.
1560 * Copy it so it can be modified while pw->pw_dir stays intact.
1562 if (chrootdir == NULL &&
1563 (chrootdir = strdup(pw->pw_dir)) == NULL)
1564 fatalerror("Ran out of memory.");
1566 * Check for the "/chroot/./home" syntax,
1567 * separate the chroot and home directory pathnames.
1569 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1570 *(homedir++) = '\0'; /* wipe '/' */
1571 homedir++; /* skip '.' */
1574 * We MUST do a chdir() after the chroot. Otherwise
1575 * the old current directory will be accessible as "."
1576 * outside the new root!
1581 * Finally, do chroot()
1583 if (chroot(chrootdir) < 0) {
1584 reply(550, "Can't change root.");
1587 __FreeBSD_libc_enter_restricted_mode();
1588 } else /* real user w/o chroot */
1589 homedir = pw->pw_dir;
1591 * Set euid *before* doing chdir() so
1592 * a) the user won't be carried to a directory that he couldn't reach
1593 * on his own due to no permission to upper path components,
1594 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1595 * (uid 0 has no root power over NFS if not mapped explicitly.)
1597 if (seteuid(pw->pw_uid) < 0) {
1598 reply(550, "Can't set uid.");
1601 if (chdir(homedir) < 0) {
1602 if (guest || dochroot) {
1603 reply(550, "Can't change to base directory.");
1606 if (chdir("/") < 0) {
1607 reply(550, "Root is inaccessible.");
1610 lreply(230, "No directory! Logging in with home=/.");
1615 * Display a login message, if it exists.
1616 * N.B. reply(230,) must follow the message.
1618 #ifdef VIRTUAL_HOSTING
1619 fd = fopen(thishost->loginmsg, "r");
1621 fd = fopen(_PATH_FTPLOGINMESG, "r");
1624 char *cp, line[LINE_MAX];
1626 while (fgets(line, sizeof(line), fd) != NULL) {
1627 if ((cp = strchr(line, '\n')) != NULL)
1629 lreply(230, "%s", line);
1631 (void) fflush(stdout);
1637 ident = strdup(passwd);
1639 fatalerror("Ran out of memory.");
1641 reply(230, "Guest login ok, access restrictions apply.");
1643 #ifdef VIRTUAL_HOSTING
1644 if (thishost != firsthost)
1645 snprintf(proctitle, sizeof(proctitle),
1646 "%s: anonymous(%s)/%s", remotehost, hostname,
1650 snprintf(proctitle, sizeof(proctitle),
1651 "%s: anonymous/%s", remotehost, passwd);
1652 setproctitle("%s", proctitle);
1653 #endif /* SETPROCTITLE */
1655 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1656 remotehost, passwd);
1659 reply(230, "User %s logged in, "
1660 "access restrictions apply.", pw->pw_name);
1662 reply(230, "User %s logged in.", pw->pw_name);
1665 snprintf(proctitle, sizeof(proctitle),
1666 "%s: user/%s", remotehost, pw->pw_name);
1667 setproctitle("%s", proctitle);
1668 #endif /* SETPROCTITLE */
1670 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1671 remotehost, pw->pw_name);
1673 if (logging && (guest || dochroot))
1674 syslog(LOG_INFO, "session root changed to %s", chrootdir);
1682 /* Forget all about it... */
1692 retrieve(char *cmd, char *name)
1696 int (*closefunc)(FILE *);
1701 fin = fopen(name, "r"), closefunc = fclose;
1704 (void) snprintf(line, sizeof(line), cmd, name);
1706 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1708 st.st_blksize = BUFSIZ;
1712 perror_reply(550, name);
1714 LOGCMD("get", name);
1721 if (fstat(fileno(fin), &st) < 0) {
1722 perror_reply(550, name);
1725 if (!S_ISREG(st.st_mode)) {
1727 * Never sending a raw directory is a workaround
1728 * for buggy clients that will attempt to RETR
1729 * a directory before listing it, e.g., Mozilla.
1730 * Preventing a guest from getting irregular files
1731 * is a simple security measure.
1733 if (S_ISDIR(st.st_mode) || guest) {
1734 reply(550, "%s: not a plain file.", name);
1738 /* st.st_blksize is set for all descriptor types */
1741 if (restart_point) {
1742 if (type == TYPE_A) {
1749 if ((c=getc(fin)) == EOF) {
1750 perror_reply(550, name);
1756 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1757 perror_reply(550, name);
1761 dout = dataconn(name, st.st_size, "w");
1765 send_data(fin, dout, st.st_blksize, st.st_size,
1766 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1767 if (cmd == 0 && guest && stats && byte_count > 0)
1768 logxfer(name, byte_count, start);
1769 (void) fclose(dout);
1774 LOGBYTES("get", name, byte_count);
1779 store(char *name, char *mode, int unique)
1783 int (*closefunc)(FILE *);
1785 if (*mode == 'a') { /* APPE */
1787 /* Programming error */
1788 syslog(LOG_ERR, "Internal: unique flag to APPE");
1791 if (guest && noguestmod) {
1792 reply(550, "Appending to existing file denied.");
1795 restart_point = 0; /* not affected by preceding REST */
1797 if (unique) /* STOU overrides REST */
1799 if (guest && noguestmod) {
1800 if (restart_point) { /* guest STOR w/REST */
1801 reply(550, "Modifying existing file denied.");
1803 } else /* treat guest STOR as STOU */
1808 mode = "r+"; /* so ASCII manual seek can work */
1810 if ((fd = guniquefd(name, &name)) < 0)
1812 fout = fdopen(fd, mode);
1814 fout = fopen(name, mode);
1817 perror_reply(553, name);
1821 if (restart_point) {
1822 if (type == TYPE_A) {
1829 if ((c=getc(fout)) == EOF) {
1830 perror_reply(550, name);
1837 * We must do this seek to "current" position
1838 * because we are changing from reading to
1841 if (fseeko(fout, 0, SEEK_CUR) < 0) {
1842 perror_reply(550, name);
1845 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1846 perror_reply(550, name);
1850 din = dataconn(name, -1, "r");
1853 if (receive_data(din, fout) == 0) {
1855 reply(226, "Transfer complete (unique file name:%s).",
1858 reply(226, "Transfer complete.");
1864 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1868 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1873 getdatasock(char *mode)
1875 int on = 1, s, t, tries;
1878 return (fdopen(data, mode));
1880 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1883 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1884 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1885 /* anchor socket to avoid multi-homing problems */
1886 data_source = ctrl_addr;
1887 data_source.su_port = htons(dataport);
1889 for (tries = 1; ; tries++) {
1891 * We should loop here since it's possible that
1892 * another ftpd instance has passed this point and is
1893 * trying to open a data connection in active mode now.
1894 * Until the other connection is opened, we'll be getting
1895 * EADDRINUSE because no SOCK_STREAM sockets in the system
1896 * can share both local and remote addresses, localIP:20
1897 * and *:* in this case.
1899 if (bind(s, (struct sockaddr *)&data_source,
1900 data_source.su_len) >= 0)
1902 if (errno != EADDRINUSE || tries > 10)
1906 (void) seteuid(pw->pw_uid);
1908 if (data_source.su_family == AF_INET)
1910 on = IPTOS_THROUGHPUT;
1911 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1912 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1917 * Turn off push flag to keep sender TCP from sending short packets
1918 * at the boundaries of each write().
1921 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1922 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1924 return (fdopen(s, mode));
1926 /* Return the real value of errno (close may change it) */
1928 (void) seteuid(pw->pw_uid);
1935 dataconn(char *name, off_t size, char *mode)
1939 int retry = 0, tos, conerrno;
1944 (void) snprintf(sizebuf, sizeof(sizebuf),
1945 " (%jd bytes)", (intmax_t)size);
1949 union sockunion from;
1950 socklen_t fromlen = ctrl_addr.su_len;
1952 struct timeval timeout;
1956 FD_SET(pdata, &set);
1958 timeout.tv_usec = 0;
1959 timeout.tv_sec = 120;
1962 * Granted a socket is in the blocking I/O mode,
1963 * accept() will block after a successful select()
1964 * if the selected connection dies in between.
1965 * Therefore set the non-blocking I/O flag here.
1967 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1968 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1970 if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
1971 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1973 (void) close(pdata);
1976 * Unset the inherited non-blocking I/O flag
1977 * on the child socket so stdio can work on it.
1979 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1980 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1983 if (from.su_family == AF_INET)
1985 tos = IPTOS_THROUGHPUT;
1986 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1987 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1990 reply(150, "Opening %s mode data connection for '%s'%s.",
1991 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1992 return (fdopen(pdata, mode));
1994 reply(425, "Can't open data connection.");
1995 (void) close(pdata);
2000 reply(125, "Using existing data connection for '%s'%s.",
2003 return (fdopen(data, mode));
2006 data_dest = his_addr;
2009 file = getdatasock(mode);
2011 char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
2013 if (getnameinfo((struct sockaddr *)&data_source,
2015 hostbuf, sizeof(hostbuf) - 1,
2016 portbuf, sizeof(portbuf) - 1,
2017 NI_NUMERICHOST|NI_NUMERICSERV))
2018 *hostbuf = *portbuf = 0;
2019 hostbuf[sizeof(hostbuf) - 1] = 0;
2020 portbuf[sizeof(portbuf) - 1] = 0;
2021 reply(425, "Can't create data socket (%s,%s): %s.",
2022 hostbuf, portbuf, strerror(errno));
2025 data = fileno(file);
2027 if (connect(data, (struct sockaddr *)&data_dest,
2028 data_dest.su_len) == 0)
2031 (void) fclose(file);
2033 if (conerrno == EADDRINUSE) {
2039 } while (retry <= swaitmax);
2040 if (conerrno != 0) {
2041 reply(425, "Can't build data connection: %s.",
2042 strerror(conerrno));
2045 reply(150, "Opening %s mode data connection for '%s'%s.",
2046 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2051 * A helper macro to avoid code duplication
2052 * in send_data() and receive_data().
2054 * XXX We have to block SIGURG during putc() because BSD stdio
2055 * is unable to restart interrupted write operations and hence
2056 * the entire buffer contents will be lost as soon as a write()
2057 * call indicates EINTR to stdio.
2059 #define FTPD_PUTC(ch, file, label) \
2065 ret = putc((ch), (file)); \
2067 CHECKOOB(return (-1)) \
2068 else if (ferror(file)) \
2071 } while (ret == EOF); \
2075 * Transfer the contents of "instr" to "outstr" peer using the appropriate
2076 * encapsulation of the data subject to Mode, Structure, and Type.
2078 * NB: Form isn't handled.
2081 send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2083 int c, cp, filefd, netfd;
2094 CHECKOOB(return (-1))
2095 else if (c == EOF && ferror(instr))
2098 if (ferror(instr)) { /* resume after OOB */
2102 if (feof(instr)) /* EOF */
2104 syslog(LOG_ERR, "Internal: impossible condition"
2105 " on file after getc()");
2108 if (c == '\n' && cp != '\r') {
2109 FTPD_PUTC('\r', outstr, data_err);
2112 FTPD_PUTC(c, outstr, data_err);
2116 #ifdef notyet /* BSD stdio isn't ready for that */
2117 while (fflush(outstr) == EOF) {
2118 CHECKOOB(return (-1))
2126 if (fflush(outstr) == EOF)
2129 reply(226, "Transfer complete.");
2135 * isreg is only set if we are not doing restart and we
2136 * are sending a regular file
2138 netfd = fileno(outstr);
2139 filefd = fileno(instr);
2142 char *msg = "Transfer complete.";
2148 while (filesize > 0) {
2149 err = sendfile(filefd, netfd, offset, 0,
2152 * Calculate byte_count before OOB processing.
2153 * It can be used in myoob() later.
2158 CHECKOOB(return (-1))
2159 else if (err == -1) {
2160 if (errno != EINTR &&
2161 cnt == 0 && offset == 0)
2165 if (err == -1) /* resume after OOB */
2168 * We hit the EOF prematurely.
2169 * Perhaps the file was externally truncated.
2172 msg = "Transfer finished due to "
2173 "premature end of file.";
2178 reply(226, "%s", msg);
2183 if ((buf = malloc(blksize)) == NULL) {
2185 reply(451, "Ran out of memory.");
2193 cnt = read(filefd, buf, blksize);
2194 CHECKOOB(free(buf); return (-1))
2199 if (cnt < 0) /* resume after OOB */
2201 if (cnt == 0) /* EOF */
2203 for (len = cnt, bp = buf; len > 0;) {
2204 cnt = write(netfd, bp, len);
2205 CHECKOOB(free(buf); return (-1))
2219 reply(226, "Transfer complete.");
2223 reply(550, "Unimplemented TYPE %d in send_data.", type);
2229 perror_reply(426, "Data connection");
2234 perror_reply(551, "Error on input file");
2239 * Transfer data from peer to "outstr" using the appropriate encapulation of
2240 * the data subject to Mode, Structure, and Type.
2242 * N.B.: Form isn't handled.
2245 receive_data(FILE *instr, FILE *outstr)
2261 cnt = read(fileno(instr), buf, sizeof(buf));
2262 CHECKOOB(return (-1))
2265 if (cnt < 0) /* resume after OOB */
2267 if (cnt == 0) /* EOF */
2269 for (len = cnt, bp = buf; len > 0;) {
2270 cnt = write(fileno(outstr), bp, len);
2271 CHECKOOB(return (-1))
2286 reply(553, "TYPE E not implemented.");
2293 CHECKOOB(return (-1))
2294 else if (c == EOF && ferror(instr))
2296 if (c == EOF && ferror(instr)) { /* resume after OOB */
2303 FTPD_PUTC('\r', outstr, file_err);
2313 /* Check for EOF here in order not to lose last \r. */
2315 if (feof(instr)) /* EOF */
2317 syslog(LOG_ERR, "Internal: impossible condition"
2318 " on data stream after getc()");
2323 FTPD_PUTC(c, outstr, file_err);
2326 #ifdef notyet /* BSD stdio isn't ready for that */
2327 while (fflush(outstr) == EOF) {
2328 CHECKOOB(return (-1))
2336 if (fflush(outstr) == EOF)
2341 "WARNING! %d bare linefeeds received in ASCII mode.",
2343 (void)printf(" File may not have transferred correctly.\r\n");
2348 reply(550, "Unimplemented TYPE %d in receive_data.", type);
2354 perror_reply(426, "Data connection");
2359 perror_reply(452, "Error writing to file");
2364 statfilecmd(char *filename)
2369 char line[LINE_MAX];
2372 code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2373 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2374 fin = ftpd_popen(line, "r");
2376 perror_reply(551, filename);
2379 lreply(code, "Status of %s:", filename);
2381 while ((c = getc(fin)) != EOF) {
2383 if (ferror(stdout)){
2384 perror_reply(421, "Control connection");
2385 (void) ftpd_pclose(fin);
2390 perror_reply(551, filename);
2391 (void) ftpd_pclose(fin);
2394 (void) putc('\r', stdout);
2397 * RFC 959 says neutral text should be prepended before
2398 * a leading 3-digit number followed by whitespace, but
2399 * many ftp clients can be confused by any leading digits,
2400 * as a matter of fact.
2402 if (atstart && isdigit(c))
2403 (void) putc(' ', stdout);
2404 (void) putc(c, stdout);
2405 atstart = (c == '\n');
2407 (void) ftpd_pclose(fin);
2408 reply(code, "End of status.");
2414 union sockunion *su;
2416 char hname[NI_MAXHOST];
2420 lreply(211, "%s FTP server status:", hostname);
2421 printf(" %s\r\n", version);
2423 lreply(211, "FTP server status:");
2424 printf(" Connected to %s", remotehost);
2425 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2426 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2427 hname[sizeof(hname) - 1] = 0;
2428 if (strcmp(hname, remotehost) != 0)
2429 printf(" (%s)", hname);
2434 printf(" Logged in anonymously\r\n");
2436 printf(" Logged in as %s\r\n", pw->pw_name);
2437 } else if (askpasswd)
2438 printf(" Waiting for password\r\n");
2440 printf(" Waiting for user name\r\n");
2441 printf(" TYPE: %s", typenames[type]);
2442 if (type == TYPE_A || type == TYPE_E)
2443 printf(", FORM: %s", formnames[form]);
2446 printf(" %d", CHAR_BIT);
2448 printf(" %d", bytesize); /* need definition! */
2450 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2451 strunames[stru], modenames[mode]);
2453 printf(" Data connection open\r\n");
2454 else if (pdata != -1) {
2458 } else if (usedefault == 0) {
2462 #define UC(b) (((int) b) & 0xff)
2464 printf(" EPSV only mode (EPSV ALL)\r\n");
2469 if (su->su_family == AF_INET) {
2470 a = (u_char *) &su->su_sin.sin_addr;
2471 p = (u_char *) &su->su_sin.sin_port;
2472 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2473 ispassive ? "PASV" : "PORT",
2474 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2475 UC(p[0]), UC(p[1]));
2482 switch (su->su_family) {
2484 a = (u_char *) &su->su_sin.sin_addr;
2485 p = (u_char *) &su->su_sin.sin_port;
2486 alen = sizeof(su->su_sin.sin_addr);
2490 a = (u_char *) &su->su_sin6.sin6_addr;
2491 p = (u_char *) &su->su_sin6.sin6_port;
2492 alen = sizeof(su->su_sin6.sin6_addr);
2500 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2502 for (i = 0; i < alen; i++)
2503 printf("%d,", UC(a[i]));
2504 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2513 switch (su->su_family) {
2525 union sockunion tmp;
2528 if (tmp.su_family == AF_INET6)
2529 tmp.su_sin6.sin6_scope_id = 0;
2530 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2531 hname, sizeof(hname) - 1, NULL, 0,
2533 hname[sizeof(hname) - 1] = 0;
2534 printf(" %s |%d|%s|%d|\r\n",
2535 ispassive ? "EPSV" : "EPRT",
2536 af, hname, htons(tmp.su_port));
2542 printf(" No data connection\r\n");
2543 reply(211, "End of status.");
2550 reply(451, "Error in server: %s", s);
2551 reply(221, "Closing connection due to server error.");
2557 reply(int n, const char *fmt, ...)
2561 (void)printf("%d ", n);
2563 (void)vprintf(fmt, ap);
2565 (void)printf("\r\n");
2566 (void)fflush(stdout);
2568 syslog(LOG_DEBUG, "<--- %d ", n);
2570 vsyslog(LOG_DEBUG, fmt, ap);
2576 lreply(int n, const char *fmt, ...)
2580 (void)printf("%d- ", n);
2582 (void)vprintf(fmt, ap);
2584 (void)printf("\r\n");
2585 (void)fflush(stdout);
2587 syslog(LOG_DEBUG, "<--- %d- ", n);
2589 vsyslog(LOG_DEBUG, fmt, ap);
2598 reply(250, "%s command successful.", s);
2605 reply(502, "%s command not implemented.", s);
2614 if ((cp = strchr(cbuf,'\n')))
2616 reply(500, "%s: command not understood.", cbuf);
2624 LOGCMD("delete", name);
2625 if (lstat(name, &st) < 0) {
2626 perror_reply(550, name);
2629 if (S_ISDIR(st.st_mode)) {
2630 if (rmdir(name) < 0) {
2631 perror_reply(550, name);
2636 if (guest && noguestmod) {
2637 reply(550, "Operation not permitted.");
2640 if (unlink(name) < 0) {
2641 perror_reply(550, name);
2652 if (chdir(path) < 0)
2653 perror_reply(550, path);
2663 LOGCMD("mkdir", name);
2664 if (guest && noguestmkd)
2665 reply(550, "Operation not permitted.");
2666 else if (mkdir(name, 0777) < 0)
2667 perror_reply(550, name);
2669 if ((s = doublequote(name)) == NULL)
2670 fatalerror("Ran out of memory.");
2671 reply(257, "\"%s\" directory created.", s);
2677 removedir(char *name)
2680 LOGCMD("rmdir", name);
2681 if (rmdir(name) < 0)
2682 perror_reply(550, name);
2690 char *s, path[MAXPATHLEN + 1];
2692 if (getcwd(path, sizeof(path)) == NULL)
2693 perror_reply(550, "Get current directory");
2695 if ((s = doublequote(path)) == NULL)
2696 fatalerror("Ran out of memory.");
2697 reply(257, "\"%s\" is current directory.", s);
2703 renamefrom(char *name)
2707 if (guest && noguestmod) {
2708 reply(550, "Operation not permitted.");
2711 if (lstat(name, &st) < 0) {
2712 perror_reply(550, name);
2715 reply(350, "File exists, ready for destination name.");
2720 renamecmd(char *from, char *to)
2724 LOGCMD2("rename", from, to);
2726 if (guest && (stat(to, &st) == 0)) {
2727 reply(550, "%s: permission denied.", to);
2731 if (rename(from, to) < 0)
2732 perror_reply(550, "rename");
2738 dolog(struct sockaddr *who)
2740 char who_name[NI_MAXHOST];
2742 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2743 remotehost[sizeof(remotehost) - 1] = 0;
2744 if (getnameinfo(who, who->sa_len,
2745 who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
2747 who_name[sizeof(who_name) - 1] = 0;
2750 #ifdef VIRTUAL_HOSTING
2751 if (thishost != firsthost)
2752 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2753 remotehost, hostname);
2756 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2758 setproctitle("%s", proctitle);
2759 #endif /* SETPROCTITLE */
2762 #ifdef VIRTUAL_HOSTING
2763 if (thishost != firsthost)
2764 syslog(LOG_INFO, "connection from %s (%s) to %s",
2765 remotehost, who_name, hostname);
2768 syslog(LOG_INFO, "connection from %s (%s)",
2769 remotehost, who_name);
2774 * Record logout in wtmp file
2775 * and exit with supplied status.
2778 dologout(int status)
2781 if (logged_in && dowtmp) {
2784 setusercontext(NULL, getpwuid(0), 0, LOGIN_SETALL & ~(LOGIN_SETLOGIN |
2785 LOGIN_SETUSER | LOGIN_SETGROUP | LOGIN_SETPATH |
2788 ftpd_logwtmp(wtmpid, NULL, NULL);
2790 /* beware of flushing buffers after a SIGPIPE */
2808 syslog(LOG_ERR, "Internal: maskurg() while no transfer");
2813 sigaddset(&sset, SIGURG);
2814 sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
2824 syslog(LOG_ERR, "Internal: flagxfer(1): "
2825 "transfer already under way");
2831 syslog(LOG_ERR, "Internal: flagxfer(0): "
2832 "no active transfer");
2839 * Returns 0 if OK to resume or -1 if abort requested.
2848 syslog(LOG_ERR, "Internal: myoob() while no transfer");
2852 ret = get_line(cp, 7, stdin);
2854 reply(221, "You could at least say goodbye.");
2856 } else if (ret == -2) {
2857 /* Ignore truncated command. */
2861 if (strcmp(cp, "ABOR\r\n") == 0) {
2863 reply(426, "Transfer aborted. Data connection closed.");
2864 reply(226, "Abort successful.");
2867 if (strcmp(cp, "STAT\r\n") == 0) {
2869 if (file_size != -1)
2870 reply(213, "Status: %jd of %jd bytes transferred.",
2871 (intmax_t)byte_count, (intmax_t)file_size);
2873 reply(213, "Status: %jd bytes transferred.",
2874 (intmax_t)byte_count);
2880 * Note: a response of 425 is not mentioned as a possible response to
2881 * the PASV command in RFC959. However, it has been blessed as
2882 * a legitimate response by Jon Postel in a telephone conversation
2883 * with Rick Adams on 25 Jan 89.
2892 if (pdata >= 0) /* close old port if one set */
2895 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2897 perror_reply(425, "Can't open passive connection");
2901 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2902 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2907 if (ctrl_addr.su_family == AF_INET) {
2908 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2909 : IP_PORTRANGE_DEFAULT;
2911 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2912 &on, sizeof(on)) < 0)
2916 #ifdef IPV6_PORTRANGE
2917 if (ctrl_addr.su_family == AF_INET6) {
2918 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2919 : IPV6_PORTRANGE_DEFAULT;
2921 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2922 &on, sizeof(on)) < 0)
2927 pasv_addr = ctrl_addr;
2928 pasv_addr.su_port = 0;
2929 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2932 (void) seteuid(pw->pw_uid);
2934 len = sizeof(pasv_addr);
2935 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2937 if (listen(pdata, 1) < 0)
2939 if (pasv_addr.su_family == AF_INET)
2940 a = (char *) &pasv_addr.su_sin.sin_addr;
2941 else if (pasv_addr.su_family == AF_INET6 &&
2942 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2943 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2947 p = (char *) &pasv_addr.su_port;
2949 #define UC(b) (((int) b) & 0xff)
2951 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2952 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2956 (void) seteuid(pw->pw_uid);
2957 (void) close(pdata);
2959 perror_reply(425, "Can't open passive connection");
2964 * Long Passive defined in RFC 1639.
2965 * 228 Entering Long Passive Mode
2966 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2970 long_passive(char *cmd, int pf)
2976 if (pdata >= 0) /* close old port if one set */
2979 if (pf != PF_UNSPEC) {
2980 if (ctrl_addr.su_family != pf) {
2981 switch (ctrl_addr.su_family) {
2994 * only EPRT/EPSV ready clients will understand this
2996 if (strcmp(cmd, "EPSV") == 0 && pf) {
2997 reply(522, "Network protocol mismatch, "
3000 reply(501, "Network protocol mismatch."); /*XXX*/
3006 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
3008 perror_reply(425, "Can't open passive connection");
3012 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
3013 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
3017 pasv_addr = ctrl_addr;
3018 pasv_addr.su_port = 0;
3019 len = pasv_addr.su_len;
3022 if (ctrl_addr.su_family == AF_INET) {
3023 on = restricted_data_ports ? IP_PORTRANGE_HIGH
3024 : IP_PORTRANGE_DEFAULT;
3026 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
3027 &on, sizeof(on)) < 0)
3031 #ifdef IPV6_PORTRANGE
3032 if (ctrl_addr.su_family == AF_INET6) {
3033 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
3034 : IPV6_PORTRANGE_DEFAULT;
3036 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
3037 &on, sizeof(on)) < 0)
3042 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
3045 (void) seteuid(pw->pw_uid);
3047 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
3049 if (listen(pdata, 1) < 0)
3052 #define UC(b) (((int) b) & 0xff)
3054 if (strcmp(cmd, "LPSV") == 0) {
3055 p = (char *)&pasv_addr.su_port;
3056 switch (pasv_addr.su_family) {
3058 a = (char *) &pasv_addr.su_sin.sin_addr;
3061 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3062 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3063 2, UC(p[0]), UC(p[1]));
3066 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
3067 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
3070 a = (char *) &pasv_addr.su_sin6.sin6_addr;
3072 "Entering Long Passive Mode "
3073 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3074 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3075 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3076 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3077 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3078 2, UC(p[0]), UC(p[1]));
3081 } else if (strcmp(cmd, "EPSV") == 0) {
3082 switch (pasv_addr.su_family) {
3085 reply(229, "Entering Extended Passive Mode (|||%d|)",
3086 ntohs(pasv_addr.su_port));
3090 /* more proper error code? */
3094 (void) seteuid(pw->pw_uid);
3095 (void) close(pdata);
3097 perror_reply(425, "Can't open passive connection");
3102 * Generate unique name for file with basename "local"
3103 * and open the file in order to avoid possible races.
3104 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3105 * Return descriptor to the file, set "name" to its name.
3107 * Generates failure reply on error.
3110 guniquefd(char *local, char **name)
3112 static char new[MAXPATHLEN];
3118 cp = strrchr(local, '/');
3121 if (stat(cp ? local : ".", &st) < 0) {
3122 perror_reply(553, cp ? local : ".");
3127 * Let not overwrite dirname with counter suffix.
3129 * In this extreme case dot won't be put in front of suffix.
3131 if (strlen(local) > sizeof(new) - 4) {
3132 reply(553, "Pathname too long.");
3137 /* -4 is for the .nn<null> we put on the end below */
3138 (void) snprintf(new, sizeof(new) - 4, "%s", local);
3139 cp = new + strlen(new);
3141 * Don't generate dotfile unless requested explicitly.
3142 * This covers the case when basename gets truncated off
3145 if (cp > new && cp[-1] != '/')
3147 for (count = 0; count < 100; count++) {
3148 /* At count 0 try unmodified name */
3150 (void)sprintf(cp, "%d", count);
3151 if ((fd = open(count ? new : local,
3152 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3153 *name = count ? new : local;
3156 if (errno != EEXIST) {
3157 perror_reply(553, count ? new : local);
3161 reply(452, "Unique file name cannot be created.");
3166 * Format and send reply containing system error number.
3169 perror_reply(int code, char *string)
3172 reply(code, "%s: %s.", string, strerror(errno));
3175 static char *onefile[] = {
3181 send_file_list(char *whichf)
3187 char **dirlist, *dirname;
3192 if (strpbrk(whichf, "~{[*?") != NULL) {
3193 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3195 memset(&gl, 0, sizeof(gl));
3196 gl.gl_matchc = MAXGLOBARGS;
3197 flags |= GLOB_LIMIT;
3199 if (glob(whichf, flags, 0, &gl)) {
3200 reply(550, "No matching files found.");
3202 } else if (gl.gl_pathc == 0) {
3204 perror_reply(550, whichf);
3207 dirlist = gl.gl_pathv;
3209 onefile[0] = whichf;
3214 while ((dirname = *dirlist++)) {
3215 if (stat(dirname, &st) < 0) {
3217 * If user typed "ls -l", etc, and the client
3218 * used NLST, do what the user meant.
3220 if (dirname[0] == '-' && *dirlist == NULL &&
3222 retrieve(_PATH_LS " %s", dirname);
3224 perror_reply(550, whichf);
3228 if (S_ISREG(st.st_mode)) {
3230 dout = dataconn("file list", -1, "w");
3236 fprintf(dout, "%s%s\n", dirname,
3237 type == TYPE_A ? "\r" : "");
3241 byte_count += strlen(dirname) +
3242 (type == TYPE_A ? 2 : 1);
3243 CHECKOOB(goto abrt);
3245 } else if (!S_ISDIR(st.st_mode))
3248 if ((dirp = opendir(dirname)) == NULL)
3251 while ((dir = readdir(dirp)) != NULL) {
3252 char nbuf[MAXPATHLEN];
3254 CHECKOOB(goto abrt);
3256 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
3258 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3262 snprintf(nbuf, sizeof(nbuf),
3263 "%s/%s", dirname, dir->d_name);
3266 * We have to do a stat to insure it's
3267 * not a directory or special file.
3269 if (simple || (stat(nbuf, &st) == 0 &&
3270 S_ISREG(st.st_mode))) {
3272 dout = dataconn("file list", -1, "w");
3278 if (nbuf[0] == '.' && nbuf[1] == '/')
3279 fprintf(dout, "%s%s\n", &nbuf[2],
3280 type == TYPE_A ? "\r" : "");
3282 fprintf(dout, "%s%s\n", nbuf,
3283 type == TYPE_A ? "\r" : "");
3287 byte_count += strlen(nbuf) +
3288 (type == TYPE_A ? 2 : 1);
3289 CHECKOOB(goto abrt);
3292 (void) closedir(dirp);
3297 reply(550, "No files found.");
3298 else if (ferror(dout))
3299 data_err: perror_reply(550, "Data connection");
3301 reply(226, "Transfer complete.");
3306 (void) fclose(dout);
3311 (void) closedir(dirp);
3319 reapchild(int signo)
3321 while (waitpid(-1, NULL, WNOHANG) > 0);
3324 #ifdef OLD_SETPROCTITLE
3326 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.)
3327 * Warning, since this is usually started from inetd.conf, it often doesn't
3328 * have much of an environment or arglist to overwrite.
3331 setproctitle(const char *fmt, ...)
3339 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
3341 /* make ps print our process name */
3346 if (i > LastArgv - p - 2) {
3347 i = LastArgv - p - 2;
3352 if (ch != '\n' && ch != '\r')
3354 while (p < LastArgv)
3357 #endif /* OLD_SETPROCTITLE */
3360 appendf(char **strp, char *fmt, ...)
3366 vasprintf(&p, fmt, ap);
3369 fatalerror("Ran out of memory.");
3374 asprintf(strp, "%s%s", ostr, p);
3376 fatalerror("Ran out of memory.");
3382 logcmd(char *cmd, char *file1, char *file2, off_t cnt)
3385 char wd[MAXPATHLEN + 1];
3390 if (getcwd(wd, sizeof(wd) - 1) == NULL)
3391 strcpy(wd, strerror(errno));
3393 appendf(&msg, "%s", cmd);
3395 appendf(&msg, " %s", file1);
3397 appendf(&msg, " %s", file2);
3399 appendf(&msg, " = %jd bytes", (intmax_t)cnt);
3400 appendf(&msg, " (wd: %s", wd);
3401 if (guest || dochroot)
3402 appendf(&msg, "; chrooted");
3404 syslog(LOG_INFO, "%s", msg);
3409 logxfer(char *name, off_t size, time_t start)
3411 char buf[MAXPATHLEN + 1024];
3412 char path[MAXPATHLEN + 1];
3417 if (realpath(name, path) == NULL) {
3418 syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
3421 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n",
3422 ctime(&now)+4, ident, remotehost,
3423 path, (intmax_t)size,
3424 (long)(now - start + (now == start)));
3425 write(statfd, buf, strlen(buf));
3430 doublequote(char *s)
3435 for (p = s, n = 0; *p; p++)
3439 if ((s2 = malloc(p - s + n + 1)) == NULL)
3442 for (p = s2; *s; s++, p++) {
3443 if ((*p = *s) == '"')
3451 /* setup server socket for specified address family */
3452 /* if af is PF_UNSPEC more than one socket may be returned */
3453 /* the returned list is dynamically allocated, so caller needs to free it */
3455 socksetup(int af, char *bindname, const char *bindport)
3457 struct addrinfo hints, *res, *r;
3458 int error, maxs, *s, *socks;
3461 memset(&hints, 0, sizeof(hints));
3462 hints.ai_flags = AI_PASSIVE;
3463 hints.ai_family = af;
3464 hints.ai_socktype = SOCK_STREAM;
3465 error = getaddrinfo(bindname, bindport, &hints, &res);
3467 syslog(LOG_ERR, "%s", gai_strerror(error));
3468 if (error == EAI_SYSTEM)
3469 syslog(LOG_ERR, "%s", strerror(errno));
3473 /* Count max number of sockets we may open */
3474 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3476 socks = malloc((maxs + 1) * sizeof(int));
3479 syslog(LOG_ERR, "couldn't allocate memory for sockets");
3483 *socks = 0; /* num of sockets counter at start of array */
3485 for (r = res; r; r = r->ai_next) {
3486 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3488 syslog(LOG_DEBUG, "control socket: %m");
3491 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3492 &on, sizeof(on)) < 0)
3494 "control setsockopt (SO_REUSEADDR): %m");
3495 if (r->ai_family == AF_INET6) {
3496 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3497 &on, sizeof(on)) < 0)
3499 "control setsockopt (IPV6_V6ONLY): %m");
3501 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3502 syslog(LOG_DEBUG, "control bind: %m");
3514 syslog(LOG_ERR, "control socket: Couldn't bind to any socket");