2 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 static char copyright[] =
37 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
38 The Regents of the University of California. All rights reserved.\n";
44 static char sccsid[] = "@(#)ftpd.c 8.4 (Berkeley) 4/16/94";
48 #include <sys/cdefs.h>
49 __FBSDID("$FreeBSD$");
54 #include <sys/param.h>
55 #include <sys/ioctl.h>
57 #include <sys/socket.h>
62 #include <netinet/in.h>
63 #include <netinet/in_systm.h>
64 #include <netinet/ip.h>
65 #include <netinet/tcp.h>
69 #include <arpa/inet.h>
70 #include <arpa/telnet.h>
93 #include <login_cap.h>
97 #include <security/pam_appl.h>
100 #include "pathnames.h"
105 static char version[] = "Version 6.00LS";
108 union sockunion ctrl_addr;
109 union sockunion data_source;
110 union sockunion data_dest;
111 union sockunion his_addr;
112 union sockunion pasv_addr;
117 int hostinfo = 1; /* print host-specific info in messages */
122 int timeout = 900; /* timeout after 15 minutes of inactivity */
123 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
125 int restricted_data_ports = 1;
126 int paranoid = 1; /* be extra careful about security */
127 int anon_only = 0; /* Only anonymous ftp allowed */
128 int assumeutf8 = 0; /* Assume that server file names are in UTF-8 */
137 int stru; /* avoid C keyword */
139 int usedefault = 1; /* for data transfers */
140 int pdata = -1; /* for passive mode */
141 int readonly = 0; /* Server is in readonly mode. */
142 int noepsv = 0; /* EPSV command is disabled. */
143 int noretr = 0; /* RETR command is disabled. */
144 int noguestretr = 0; /* RETR command is disabled for anon users. */
145 int noguestmkd = 0; /* MKD command is disabled for anon users. */
146 int noguestmod = 1; /* anon users may not modify existing files. */
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)
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:AdDEhlmMoOp:P:rRSt:T:u:UvW")) != -1) {
311 family = (family == AF_INET6) ? AF_UNSPEC : AF_INET;
315 family = (family == AF_INET) ? AF_UNSPEC : AF_INET6;
347 logging++; /* > 1 == extra logging */
387 timeout = atoi(optarg);
388 if (maxtimeout < timeout)
389 maxtimeout = timeout;
393 maxtimeout = atoi(optarg);
394 if (timeout > maxtimeout)
395 timeout = maxtimeout;
402 val = strtol(optarg, &optarg, 8);
403 if (*optarg != '\0' || val < 0)
404 syslog(LOG_WARNING, "bad value for -u");
410 restricted_data_ports = 0;
422 syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
428 int *ctl_sock, fd, maxfd = -1, nfds, i;
429 fd_set defreadfds, readfds;
433 if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
434 if (errno == EEXIST) {
435 syslog(LOG_ERR, "%s already running, pid %d",
436 getprogname(), (int)pid);
439 syslog(LOG_WARNING, "pidfile_open: %m");
443 * Detach from parent.
445 if (daemon(1, 1) < 0) {
446 syslog(LOG_ERR, "failed to become a daemon");
450 if (pfh != NULL && pidfile_write(pfh) == -1)
451 syslog(LOG_WARNING, "pidfile_write: %m");
453 sa.sa_handler = reapchild;
454 (void)sigaction(SIGCHLD, &sa, NULL);
456 #ifdef VIRTUAL_HOSTING
461 * Open a socket, bind it to the FTP port, and start
464 ctl_sock = socksetup(family, bindname, bindport);
465 if (ctl_sock == NULL)
468 FD_ZERO(&defreadfds);
469 for (i = 1; i <= *ctl_sock; i++) {
470 FD_SET(ctl_sock[i], &defreadfds);
471 if (listen(ctl_sock[i], 32) < 0) {
472 syslog(LOG_ERR, "control listen: %m");
475 if (maxfd < ctl_sock[i])
480 * Loop forever accepting connection requests and forking off
481 * children to handle them.
484 FD_COPY(&defreadfds, &readfds);
485 nfds = select(maxfd + 1, &readfds, NULL, NULL, 0);
487 if (nfds < 0 && errno != EINTR)
488 syslog(LOG_WARNING, "select: %m");
493 for (i = 1; i <= *ctl_sock; i++)
494 if (FD_ISSET(ctl_sock[i], &readfds)) {
495 addrlen = sizeof(his_addr);
496 fd = accept(ctl_sock[i],
497 (struct sockaddr *)&his_addr,
504 switch (pid = fork()) {
510 for (i = 1; i <= *ctl_sock; i++)
516 syslog(LOG_WARNING, "fork: %m");
524 addrlen = sizeof(his_addr);
525 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
526 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
530 #ifdef VIRTUAL_HOSTING
531 if (his_addr.su_family == AF_INET6 &&
532 IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))
535 family = his_addr.su_family;
541 sa.sa_handler = SIG_DFL;
542 (void)sigaction(SIGCHLD, &sa, NULL);
544 sa.sa_handler = sigurg;
545 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
546 (void)sigaction(SIGURG, &sa, NULL);
548 sigfillset(&sa.sa_mask); /* block all signals in handler */
549 sa.sa_flags = SA_RESTART;
550 sa.sa_handler = sigquit;
551 (void)sigaction(SIGHUP, &sa, NULL);
552 (void)sigaction(SIGINT, &sa, NULL);
553 (void)sigaction(SIGQUIT, &sa, NULL);
554 (void)sigaction(SIGTERM, &sa, NULL);
556 sa.sa_handler = lostconn;
557 (void)sigaction(SIGPIPE, &sa, NULL);
559 addrlen = sizeof(ctrl_addr);
560 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
561 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
564 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
565 #ifdef VIRTUAL_HOSTING
566 /* select our identity from virtual host table */
567 selecthost(&ctrl_addr);
570 if (ctrl_addr.su_family == AF_INET)
572 tos = IPTOS_LOWDELAY;
573 if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
574 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
578 * Disable Nagle on the control channel so that we don't have to wait
579 * for peer's ACK before issuing our next reply.
581 if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
582 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
584 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
586 (void)snprintf(wtmpid, sizeof(wtmpid), "%xftpd", getpid());
588 /* Try to handle urgent data inline */
590 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
591 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
595 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
596 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
598 dolog((struct sockaddr *)&his_addr);
600 * Set up default state
609 /* If logins are disabled, print out the message. */
610 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
611 while (fgets(line, sizeof(line), fd) != NULL) {
612 if ((cp = strchr(line, '\n')) != NULL)
614 lreply(530, "%s", line);
616 (void) fflush(stdout);
618 reply(530, "System not available.");
621 #ifdef VIRTUAL_HOSTING
622 fd = fopen(thishost->welcome, "r");
624 fd = fopen(_PATH_FTPWELCOME, "r");
627 while (fgets(line, sizeof(line), fd) != NULL) {
628 if ((cp = strchr(line, '\n')) != NULL)
630 lreply(220, "%s", line);
632 (void) fflush(stdout);
634 /* reply(220,) must follow */
636 #ifndef VIRTUAL_HOSTING
637 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
638 fatalerror("Ran out of memory.");
639 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
641 hostname[MAXHOSTNAMELEN - 1] = '\0';
644 reply(220, "%s FTP server (%s) ready.", hostname, version);
646 reply(220, "FTP server ready.");
657 syslog(LOG_DEBUG, "lost connection");
665 syslog(LOG_ERR, "got signal %d", signo);
669 #ifdef VIRTUAL_HOSTING
671 * read in virtual host tables (if they exist)
675 inithosts(int family)
680 char *cp, *mp, *line;
682 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
683 struct ftphost *hrp, *lhrp;
684 struct addrinfo hints, *res, *ai;
687 * Fill in the default host information
689 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
690 fatalerror("Ran out of memory.");
691 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
693 hostname[MAXHOSTNAMELEN - 1] = '\0';
694 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
695 fatalerror("Ran out of memory.");
696 hrp->hostname = hostname;
697 hrp->hostinfo = NULL;
699 memset(&hints, 0, sizeof(hints));
700 hints.ai_flags = AI_PASSIVE;
701 hints.ai_family = family;
702 hints.ai_socktype = SOCK_STREAM;
703 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
705 hrp->statfile = _PATH_FTPDSTATFILE;
706 hrp->welcome = _PATH_FTPWELCOME;
707 hrp->loginmsg = _PATH_FTPLOGINMESG;
708 hrp->anonuser = "ftp";
710 thishost = firsthost = lhrp = hrp;
711 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
712 int addrsize, gothost;
716 while ((line = fgetln(fp, &len)) != NULL) {
722 if (line[len - 1] == '\n') {
723 line[len - 1] = '\0';
726 if ((mp = malloc(len + 1)) == NULL)
727 fatalerror("Ran out of memory.");
728 memcpy(mp, line, len);
732 cp = strtok(line, " \t");
733 /* skip empty lines */
740 statfile = _PATH_FTPDSTATFILE;
741 welcome = _PATH_FTPWELCOME;
742 loginmsg = _PATH_FTPLOGINMESG;
745 * Preparse the line so we can use its info
746 * for all the addresses associated with
747 * the virtual host name.
748 * Field 0, the virtual host name, is special:
749 * it's already parsed off and will be strdup'ed
750 * later, after we know its canonical form.
752 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
753 if (*cp != '-' && (cp = strdup(cp)))
755 case 1: /* anon user permissions */
758 case 2: /* statistics file */
761 case 3: /* welcome message */
764 case 4: /* login message */
767 default: /* programming error */
772 hints.ai_flags = AI_PASSIVE;
773 hints.ai_family = family;
774 hints.ai_socktype = SOCK_STREAM;
775 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
777 for (ai = res; ai != NULL && ai->ai_addr != NULL;
781 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
784 for (hi = hrp->hostinfo; hi != NULL;
786 if (hi->ai_addrlen == ai->ai_addrlen &&
789 ai->ai_addr->sa_len) == 0) {
797 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
799 hrp->hostname = NULL;
802 if (hrp->hostinfo && hrp->hostinfo != res)
803 freeaddrinfo(hrp->hostinfo);
804 insert = 0; /* host already in the chain */
809 * determine hostname to use.
810 * force defined name if there is a valid alias
811 * otherwise fallback to primary hostname
813 /* XXX: getaddrinfo() can't do alias check */
814 switch(hrp->hostinfo->ai_family) {
816 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
817 addrsize = sizeof(struct in_addr);
820 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
821 addrsize = sizeof(struct in6_addr);
824 /* should not reach here */
825 freeaddrinfo(hrp->hostinfo);
827 free(hrp); /*not in chain, can free*/
829 hrp->hostinfo = NULL; /*mark as blank*/
833 if ((hp = getipnodebyaddr(addr, addrsize,
834 hrp->hostinfo->ai_family,
835 &hp_error)) != NULL) {
836 if (strcmp(vhost, hp->h_name) != 0) {
837 if (hp->h_aliases == NULL)
841 while (hp->h_aliases[i] &&
842 strcmp(vhost, hp->h_aliases[i]) != 0)
844 if (hp->h_aliases[i] == NULL)
850 strcmp(hrp->hostname, vhost) != 0) {
852 hrp->hostname = NULL;
854 if (hrp->hostname == NULL &&
855 (hrp->hostname = strdup(vhost)) == NULL) {
856 freeaddrinfo(hrp->hostinfo);
857 hrp->hostinfo = NULL; /* mark as blank */
862 hrp->anonuser = anonuser;
863 hrp->statfile = statfile;
864 hrp->welcome = welcome;
865 hrp->loginmsg = loginmsg;
883 selecthost(union sockunion *su)
888 struct in6_addr *mapped_in6 = NULL;
894 * XXX IPv4 mapped IPv6 addr consideraton,
895 * specified in rfc2373.
897 if (su->su_family == AF_INET6 &&
898 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
899 mapped_in6 = &su->su_sin6.sin6_addr;
902 hrp = thishost = firsthost; /* default */
905 while (hrp != NULL) {
906 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
907 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
912 /* XXX IPv4 mapped IPv6 addr consideraton */
913 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
914 (memcmp(&mapped_in6->s6_addr[12],
915 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
916 sizeof(struct in_addr)) == 0)) {
926 /* setup static variables as appropriate */
927 hostname = thishost->hostname;
928 ftpuser = thishost->anonuser;
933 * Helper function for sgetpwnam().
938 char *new = malloc(strlen(s) + 1);
941 reply(421, "Ran out of memory.");
945 (void) strcpy(new, s);
950 * Save the result of a getpwnam. Used for USER command, since
951 * the data returned must not be clobbered by any other command
953 * NB: The data returned by sgetpwnam() will remain valid until
954 * the next call to this function. Its difference from getpwnam()
955 * is that sgetpwnam() is known to be called from ftpd code only.
957 static struct passwd *
958 sgetpwnam(char *name)
960 static struct passwd save;
963 if ((p = getpwnam(name)) == NULL)
967 free(save.pw_passwd);
973 save.pw_name = sgetsave(p->pw_name);
974 save.pw_passwd = sgetsave(p->pw_passwd);
975 save.pw_gecos = sgetsave(p->pw_gecos);
976 save.pw_dir = sgetsave(p->pw_dir);
977 save.pw_shell = sgetsave(p->pw_shell);
981 static int login_attempts; /* number of failed login attempts */
982 static int askpasswd; /* had user command, ask for passwd */
983 static char curname[MAXLOGNAME]; /* current USER name */
987 * Sets global passwd pointer pw if named account exists and is acceptable;
988 * sets askpasswd if a PASS command is expected. If logged in previously,
989 * need to reset state. If name is "ftp" or "anonymous", the name is not in
990 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
991 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
992 * requesting login privileges. Disallow anyone who does not have a standard
993 * shell as returned by getusershell(). Disallow anyone mentioned in the file
994 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
1004 reply(530, "Can't change user from guest login.");
1006 } else if (dochroot) {
1007 reply(530, "Can't change user from chroot user.");
1014 #ifdef VIRTUAL_HOSTING
1015 pw = sgetpwnam(thishost->anonuser);
1017 pw = sgetpwnam("ftp");
1019 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1020 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL, &ecode) ||
1021 (ecode != 0 && ecode != ENOENT))
1022 reply(530, "User %s access denied.", name);
1023 else if (checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL, &ecode) ||
1024 (ecode != 0 && ecode != ENOENT))
1025 reply(530, "User %s access denied.", name);
1026 else if (pw != NULL) {
1030 "Guest login ok, send your email address as password.");
1032 reply(530, "User %s unknown.", name);
1033 if (!askpasswd && logging)
1035 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1038 if (anon_only != 0) {
1039 reply(530, "Sorry, only anonymous ftp allowed.");
1043 if ((pw = sgetpwnam(name))) {
1044 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1045 shell = _PATH_BSHELL;
1047 while ((cp = getusershell()) != NULL)
1048 if (strcmp(cp, shell) == 0)
1053 (checkuser(_PATH_FTPUSERS, name, 1, NULL, &ecode) ||
1054 (ecode != 0 && ecode != ENOENT))) {
1055 reply(530, "User %s access denied.", name);
1058 "FTP LOGIN REFUSED FROM %s, %s",
1065 strncpy(curname, name, sizeof(curname)-1);
1069 /* XXX Kluge! The conversation mechanism needs to be fixed. */
1071 if (opiechallenge(&opiedata, name, opieprompt) == 0) {
1072 pwok = (pw != NULL) &&
1073 opieaccessfile(remotehost) &&
1074 opiealways(pw->pw_dir);
1075 reply(331, "Response to %s %s for %s.",
1076 opieprompt, pwok ? "requested" : "required", name);
1079 reply(331, "Password required for %s.", name);
1083 * Delay before reading passwd after first failed
1084 * attempt to slow down passwd-guessing programs.
1087 sleep(login_attempts);
1091 * Check if a user is in the file "fname",
1092 * return a pointer to a malloc'd string with the rest
1093 * of the matching line in "residue" if not NULL.
1096 checkuser(char *fname, char *name, int pwset, char **residue, int *ecode)
1101 char *line, *mp, *p;
1105 if ((fd = fopen(fname, "r")) != NULL) {
1106 while (!found && (line = fgetln(fd, &len)) != NULL) {
1110 if (line[len - 1] == '\n') {
1111 line[len - 1] = '\0';
1114 if ((mp = malloc(len + 1)) == NULL)
1115 fatalerror("Ran out of memory.");
1116 memcpy(mp, line, len);
1120 /* avoid possible leading and trailing whitespace */
1121 p = strtok(line, " \t");
1122 /* skip empty lines */
1126 * if first chr is '@', check group membership
1132 if (p[1] == '\0') /* single @ matches anyone */
1135 if ((grp = getgrnam(p+1)) == NULL)
1138 * Check user's default group
1140 if (pwset && grp->gr_gid == pw->pw_gid)
1143 * Check supplementary groups
1145 while (!found && grp->gr_mem[i])
1146 found = strcmp(name,
1152 * Otherwise, just check for username match
1155 found = strcmp(p, name) == 0;
1157 * Save the rest of line to "residue" if matched
1159 if (found && residue) {
1160 if ((p = strtok(NULL, "")) != NULL)
1161 p += strspn(p, " \t");
1163 if ((*residue = strdup(p)) == NULL)
1164 fatalerror("Ran out of memory.");
1173 } else if (ecode != NULL)
1179 * Terminate login as previous user, if any, resetting state;
1180 * used when USER command is given or login fails.
1190 if (logged_in && dowtmp)
1191 ftpd_logwtmp(wtmpid, NULL, NULL);
1194 setusercontext(NULL, getpwuid(0), 0, LOGIN_SETALL & ~(LOGIN_SETLOGIN |
1195 LOGIN_SETUSER | LOGIN_SETGROUP | LOGIN_SETPATH |
1200 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1201 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1202 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1203 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1204 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1205 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1217 * the following code is stolen from imap-uw PAM authentication module and
1220 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1223 const char *uname; /* user name */
1224 const char *pass; /* password */
1226 typedef struct cred_t cred_t;
1229 auth_conv(int num_msg, const struct pam_message **msg,
1230 struct pam_response **resp, void *appdata)
1233 cred_t *cred = (cred_t *) appdata;
1234 struct pam_response *reply;
1236 reply = calloc(num_msg, sizeof *reply);
1240 for (i = 0; i < num_msg; i++) {
1241 switch (msg[i]->msg_style) {
1242 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1243 reply[i].resp_retcode = PAM_SUCCESS;
1244 reply[i].resp = COPY_STRING(cred->uname);
1245 /* PAM frees resp. */
1247 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1248 reply[i].resp_retcode = PAM_SUCCESS;
1249 reply[i].resp = COPY_STRING(cred->pass);
1250 /* PAM frees resp. */
1254 reply[i].resp_retcode = PAM_SUCCESS;
1255 reply[i].resp = NULL;
1257 default: /* unknown message style */
1259 return PAM_CONV_ERR;
1268 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1269 * authenticated, or 1 if not authenticated. If some sort of PAM system
1270 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1271 * function returns -1. This can be used as an indication that we should
1272 * fall back to a different authentication mechanism.
1275 auth_pam(struct passwd **ppw, const char *pass)
1277 const char *tmpl_user;
1281 cred_t auth_cred = { (*ppw)->pw_name, pass };
1282 struct pam_conv conv = { &auth_conv, &auth_cred };
1284 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1285 if (e != PAM_SUCCESS) {
1287 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1288 * if context creation has failed in the first place.
1290 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
1294 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1295 if (e != PAM_SUCCESS) {
1296 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1297 pam_strerror(pamh, e));
1298 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1299 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1305 e = pam_authenticate(pamh, 0);
1309 * With PAM we support the concept of a "template"
1310 * user. The user enters a login name which is
1311 * authenticated by PAM, usually via a remote service
1312 * such as RADIUS or TACACS+. If authentication
1313 * succeeds, a different but related "template" name
1314 * is used for setting the credentials, shell, and
1315 * home directory. The name the user enters need only
1316 * exist on the remote authentication server, but the
1317 * template name must be present in the local password
1320 * This is supported by two various mechanisms in the
1321 * individual modules. However, from the application's
1322 * point of view, the template user is always passed
1323 * back as a changed value of the PAM_USER item.
1325 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1327 tmpl_user = (const char *) item;
1328 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1329 *ppw = getpwnam(tmpl_user);
1331 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1332 pam_strerror(pamh, e));
1337 case PAM_USER_UNKNOWN:
1343 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1349 e = pam_acct_mgmt(pamh, 0);
1350 if (e != PAM_SUCCESS) {
1351 syslog(LOG_ERR, "pam_acct_mgmt: %s",
1352 pam_strerror(pamh, e));
1358 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1359 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1366 #endif /* USE_PAM */
1374 login_cap_t *lc = NULL;
1379 char *residue = NULL;
1382 if (logged_in || askpasswd == 0) {
1383 reply(503, "Login with USER first.");
1387 if (!guest) { /* "ftp" is only account allowed no password */
1389 rval = 1; /* failure below */
1393 rval = auth_pam(&pw, passwd);
1399 if (opieverify(&opiedata, passwd) == 0)
1400 xpasswd = pw->pw_passwd;
1402 xpasswd = crypt(passwd, pw->pw_passwd);
1403 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1409 rval = strcmp(pw->pw_passwd, xpasswd);
1410 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1411 rval = 1; /* failure */
1414 * If rval == 1, the user failed the authentication check
1415 * above. If rval == 0, either PAM or local authentication
1419 reply(530, "Login incorrect.");
1422 "FTP LOGIN FAILED FROM %s",
1424 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1425 "FTP LOGIN FAILED FROM %s, %s",
1426 remotehost, curname);
1429 if (login_attempts++ >= 5) {
1431 "repeated login failures from %s",
1438 login_attempts = 0; /* this time successful */
1439 if (setegid(pw->pw_gid) < 0) {
1440 reply(550, "Can't set gid.");
1443 /* May be overridden by login.conf */
1444 (void) umask(defumask);
1446 if ((lc = login_getpwclass(pw)) != NULL) {
1447 char remote_ip[NI_MAXHOST];
1449 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1450 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1453 remote_ip[sizeof(remote_ip) - 1] = 0;
1454 if (!auth_hostok(lc, remotehost, remote_ip)) {
1455 syslog(LOG_INFO|LOG_AUTH,
1456 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1458 reply(530, "Permission denied.");
1462 if (!auth_timeok(lc, time(NULL))) {
1463 reply(530, "Login not available right now.");
1468 setusercontext(lc, pw, 0, LOGIN_SETALL &
1469 ~(LOGIN_SETUSER | LOGIN_SETPATH | LOGIN_SETENV));
1471 setlogin(pw->pw_name);
1472 (void) initgroups(pw->pw_name, pw->pw_gid);
1477 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1478 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1479 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1480 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1486 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue, &ecode)
1487 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1488 || login_getcapbool(lc, "ftp-chroot", 0)
1492 * It is possible that checkuser() failed to open the chroot file.
1493 * If this is the case, report that logins are un-available, since we
1494 * have no way of checking whether or not the user should be chrooted.
1495 * We ignore ENOENT since it is not required that this file be present.
1497 if (ecode != 0 && ecode != ENOENT) {
1498 reply(530, "Login not available right now.");
1503 /* Disable wtmp logging when chrooting. */
1504 if (dochroot || guest)
1507 ftpd_logwtmp(wtmpid, pw->pw_name,
1508 (struct sockaddr *)&his_addr);
1511 if (guest && stats && statfd < 0)
1512 #ifdef VIRTUAL_HOSTING
1513 statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1515 statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1521 * For a chrooted local user,
1522 * a) see whether ftpchroot(5) specifies a chroot directory,
1523 * b) extract the directory pathname from the line,
1524 * c) expand it to the absolute pathname if necessary.
1526 if (dochroot && residue &&
1527 (chrootdir = strtok(residue, " \t")) != NULL) {
1528 if (chrootdir[0] != '/')
1529 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1531 chrootdir = strdup(chrootdir); /* make it permanent */
1532 if (chrootdir == NULL)
1533 fatalerror("Ran out of memory.");
1535 if (guest || dochroot) {
1537 * If no chroot directory set yet, use the login directory.
1538 * Copy it so it can be modified while pw->pw_dir stays intact.
1540 if (chrootdir == NULL &&
1541 (chrootdir = strdup(pw->pw_dir)) == NULL)
1542 fatalerror("Ran out of memory.");
1544 * Check for the "/chroot/./home" syntax,
1545 * separate the chroot and home directory pathnames.
1547 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1548 *(homedir++) = '\0'; /* wipe '/' */
1549 homedir++; /* skip '.' */
1552 * We MUST do a chdir() after the chroot. Otherwise
1553 * the old current directory will be accessible as "."
1554 * outside the new root!
1559 * Finally, do chroot()
1561 if (chroot(chrootdir) < 0) {
1562 reply(550, "Can't change root.");
1565 } else /* real user w/o chroot */
1566 homedir = pw->pw_dir;
1568 * Set euid *before* doing chdir() so
1569 * a) the user won't be carried to a directory that he couldn't reach
1570 * on his own due to no permission to upper path components,
1571 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1572 * (uid 0 has no root power over NFS if not mapped explicitly.)
1574 if (seteuid(pw->pw_uid) < 0) {
1575 reply(550, "Can't set uid.");
1578 if (chdir(homedir) < 0) {
1579 if (guest || dochroot) {
1580 reply(550, "Can't change to base directory.");
1583 if (chdir("/") < 0) {
1584 reply(550, "Root is inaccessible.");
1587 lreply(230, "No directory! Logging in with home=/.");
1592 * Display a login message, if it exists.
1593 * N.B. reply(230,) must follow the message.
1595 #ifdef VIRTUAL_HOSTING
1596 fd = fopen(thishost->loginmsg, "r");
1598 fd = fopen(_PATH_FTPLOGINMESG, "r");
1601 char *cp, line[LINE_MAX];
1603 while (fgets(line, sizeof(line), fd) != NULL) {
1604 if ((cp = strchr(line, '\n')) != NULL)
1606 lreply(230, "%s", line);
1608 (void) fflush(stdout);
1614 ident = strdup(passwd);
1616 fatalerror("Ran out of memory.");
1618 reply(230, "Guest login ok, access restrictions apply.");
1620 #ifdef VIRTUAL_HOSTING
1621 if (thishost != firsthost)
1622 snprintf(proctitle, sizeof(proctitle),
1623 "%s: anonymous(%s)/%s", remotehost, hostname,
1627 snprintf(proctitle, sizeof(proctitle),
1628 "%s: anonymous/%s", remotehost, passwd);
1629 setproctitle("%s", proctitle);
1630 #endif /* SETPROCTITLE */
1632 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1633 remotehost, passwd);
1636 reply(230, "User %s logged in, "
1637 "access restrictions apply.", pw->pw_name);
1639 reply(230, "User %s logged in.", pw->pw_name);
1642 snprintf(proctitle, sizeof(proctitle),
1643 "%s: user/%s", remotehost, pw->pw_name);
1644 setproctitle("%s", proctitle);
1645 #endif /* SETPROCTITLE */
1647 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1648 remotehost, pw->pw_name);
1650 if (logging && (guest || dochroot))
1651 syslog(LOG_INFO, "session root changed to %s", chrootdir);
1659 /* Forget all about it... */
1669 retrieve(char *cmd, char *name)
1673 int (*closefunc)(FILE *);
1677 fin = fopen(name, "r"), closefunc = fclose;
1682 (void) snprintf(line, sizeof(line), cmd, name), name = line;
1683 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1685 st.st_blksize = BUFSIZ;
1689 perror_reply(550, name);
1691 LOGCMD("get", name);
1698 if (fstat(fileno(fin), &st) < 0) {
1699 perror_reply(550, name);
1702 if (!S_ISREG(st.st_mode)) {
1704 * Never sending a raw directory is a workaround
1705 * for buggy clients that will attempt to RETR
1706 * a directory before listing it, e.g., Mozilla.
1707 * Preventing a guest from getting irregular files
1708 * is a simple security measure.
1710 if (S_ISDIR(st.st_mode) || guest) {
1711 reply(550, "%s: not a plain file.", name);
1715 /* st.st_blksize is set for all descriptor types */
1718 if (restart_point) {
1719 if (type == TYPE_A) {
1726 if ((c=getc(fin)) == EOF) {
1727 perror_reply(550, name);
1733 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1734 perror_reply(550, name);
1738 dout = dataconn(name, st.st_size, "w");
1742 send_data(fin, dout, st.st_blksize, st.st_size,
1743 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1744 if (cmd == 0 && guest && stats && byte_count > 0)
1745 logxfer(name, byte_count, start);
1746 (void) fclose(dout);
1751 LOGBYTES("get", name, byte_count);
1756 store(char *name, char *mode, int unique)
1760 int (*closefunc)(FILE *);
1762 if (*mode == 'a') { /* APPE */
1764 /* Programming error */
1765 syslog(LOG_ERR, "Internal: unique flag to APPE");
1768 if (guest && noguestmod) {
1769 reply(550, "Appending to existing file denied.");
1772 restart_point = 0; /* not affected by preceding REST */
1774 if (unique) /* STOU overrides REST */
1776 if (guest && noguestmod) {
1777 if (restart_point) { /* guest STOR w/REST */
1778 reply(550, "Modifying existing file denied.");
1780 } else /* treat guest STOR as STOU */
1785 mode = "r+"; /* so ASCII manual seek can work */
1787 if ((fd = guniquefd(name, &name)) < 0)
1789 fout = fdopen(fd, mode);
1791 fout = fopen(name, mode);
1794 perror_reply(553, name);
1798 if (restart_point) {
1799 if (type == TYPE_A) {
1806 if ((c=getc(fout)) == EOF) {
1807 perror_reply(550, name);
1814 * We must do this seek to "current" position
1815 * because we are changing from reading to
1818 if (fseeko(fout, 0, SEEK_CUR) < 0) {
1819 perror_reply(550, name);
1822 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1823 perror_reply(550, name);
1827 din = dataconn(name, -1, "r");
1830 if (receive_data(din, fout) == 0) {
1832 reply(226, "Transfer complete (unique file name:%s).",
1835 reply(226, "Transfer complete.");
1841 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1845 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1850 getdatasock(char *mode)
1852 int on = 1, s, t, tries;
1855 return (fdopen(data, mode));
1857 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1860 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1861 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1862 /* anchor socket to avoid multi-homing problems */
1863 data_source = ctrl_addr;
1864 data_source.su_port = htons(dataport);
1866 for (tries = 1; ; tries++) {
1868 * We should loop here since it's possible that
1869 * another ftpd instance has passed this point and is
1870 * trying to open a data connection in active mode now.
1871 * Until the other connection is opened, we'll be getting
1872 * EADDRINUSE because no SOCK_STREAM sockets in the system
1873 * can share both local and remote addresses, localIP:20
1874 * and *:* in this case.
1876 if (bind(s, (struct sockaddr *)&data_source,
1877 data_source.su_len) >= 0)
1879 if (errno != EADDRINUSE || tries > 10)
1883 (void) seteuid(pw->pw_uid);
1885 if (data_source.su_family == AF_INET)
1887 on = IPTOS_THROUGHPUT;
1888 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1889 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1894 * Turn off push flag to keep sender TCP from sending short packets
1895 * at the boundaries of each write().
1898 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1899 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1901 return (fdopen(s, mode));
1903 /* Return the real value of errno (close may change it) */
1905 (void) seteuid(pw->pw_uid);
1912 dataconn(char *name, off_t size, char *mode)
1916 int retry = 0, tos, conerrno;
1921 (void) snprintf(sizebuf, sizeof(sizebuf),
1922 " (%jd bytes)", (intmax_t)size);
1926 union sockunion from;
1927 socklen_t fromlen = ctrl_addr.su_len;
1929 struct timeval timeout;
1933 FD_SET(pdata, &set);
1935 timeout.tv_usec = 0;
1936 timeout.tv_sec = 120;
1939 * Granted a socket is in the blocking I/O mode,
1940 * accept() will block after a successful select()
1941 * if the selected connection dies in between.
1942 * Therefore set the non-blocking I/O flag here.
1944 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1945 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1947 if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
1948 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1950 (void) close(pdata);
1953 * Unset the inherited non-blocking I/O flag
1954 * on the child socket so stdio can work on it.
1956 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1957 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1960 if (from.su_family == AF_INET)
1962 tos = IPTOS_THROUGHPUT;
1963 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1964 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1967 reply(150, "Opening %s mode data connection for '%s'%s.",
1968 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1969 return (fdopen(pdata, mode));
1971 reply(425, "Can't open data connection.");
1972 (void) close(pdata);
1977 reply(125, "Using existing data connection for '%s'%s.",
1980 return (fdopen(data, mode));
1983 data_dest = his_addr;
1986 file = getdatasock(mode);
1988 char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
1990 if (getnameinfo((struct sockaddr *)&data_source,
1992 hostbuf, sizeof(hostbuf) - 1,
1993 portbuf, sizeof(portbuf) - 1,
1994 NI_NUMERICHOST|NI_NUMERICSERV))
1995 *hostbuf = *portbuf = 0;
1996 hostbuf[sizeof(hostbuf) - 1] = 0;
1997 portbuf[sizeof(portbuf) - 1] = 0;
1998 reply(425, "Can't create data socket (%s,%s): %s.",
1999 hostbuf, portbuf, strerror(errno));
2002 data = fileno(file);
2004 if (connect(data, (struct sockaddr *)&data_dest,
2005 data_dest.su_len) == 0)
2008 (void) fclose(file);
2010 if (conerrno == EADDRINUSE) {
2016 } while (retry <= swaitmax);
2017 if (conerrno != 0) {
2018 reply(425, "Can't build data connection: %s.",
2019 strerror(conerrno));
2022 reply(150, "Opening %s mode data connection for '%s'%s.",
2023 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2028 * A helper macro to avoid code duplication
2029 * in send_data() and receive_data().
2031 * XXX We have to block SIGURG during putc() because BSD stdio
2032 * is unable to restart interrupted write operations and hence
2033 * the entire buffer contents will be lost as soon as a write()
2034 * call indicates EINTR to stdio.
2036 #define FTPD_PUTC(ch, file, label) \
2042 ret = putc((ch), (file)); \
2044 CHECKOOB(return (-1)) \
2045 else if (ferror(file)) \
2048 } while (ret == EOF); \
2052 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
2053 * encapsulation of the data subject to Mode, Structure, and Type.
2055 * NB: Form isn't handled.
2058 send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2060 int c, cp, filefd, netfd;
2071 CHECKOOB(return (-1))
2072 else if (c == EOF && ferror(instr))
2075 if (ferror(instr)) { /* resume after OOB */
2079 if (feof(instr)) /* EOF */
2081 syslog(LOG_ERR, "Internal: impossible condition"
2082 " on file after getc()");
2085 if (c == '\n' && cp != '\r') {
2086 FTPD_PUTC('\r', outstr, data_err);
2089 FTPD_PUTC(c, outstr, data_err);
2093 #ifdef notyet /* BSD stdio isn't ready for that */
2094 while (fflush(outstr) == EOF) {
2095 CHECKOOB(return (-1))
2103 if (fflush(outstr) == EOF)
2106 reply(226, "Transfer complete.");
2112 * isreg is only set if we are not doing restart and we
2113 * are sending a regular file
2115 netfd = fileno(outstr);
2116 filefd = fileno(instr);
2119 char *msg = "Transfer complete.";
2125 while (filesize > 0) {
2126 err = sendfile(filefd, netfd, offset, 0,
2129 * Calculate byte_count before OOB processing.
2130 * It can be used in myoob() later.
2135 CHECKOOB(return (-1))
2136 else if (err == -1) {
2137 if (errno != EINTR &&
2138 cnt == 0 && offset == 0)
2142 if (err == -1) /* resume after OOB */
2145 * We hit the EOF prematurely.
2146 * Perhaps the file was externally truncated.
2149 msg = "Transfer finished due to "
2150 "premature end of file.";
2155 reply(226, "%s", msg);
2160 if ((buf = malloc(blksize)) == NULL) {
2162 reply(451, "Ran out of memory.");
2170 cnt = read(filefd, buf, blksize);
2171 CHECKOOB(free(buf); return (-1))
2176 if (cnt < 0) /* resume after OOB */
2178 if (cnt == 0) /* EOF */
2180 for (len = cnt, bp = buf; len > 0;) {
2181 cnt = write(netfd, bp, len);
2182 CHECKOOB(free(buf); return (-1))
2196 reply(226, "Transfer complete.");
2200 reply(550, "Unimplemented TYPE %d in send_data.", type);
2206 perror_reply(426, "Data connection");
2211 perror_reply(551, "Error on input file");
2216 * Transfer data from peer to "outstr" using the appropriate encapulation of
2217 * the data subject to Mode, Structure, and Type.
2219 * N.B.: Form isn't handled.
2222 receive_data(FILE *instr, FILE *outstr)
2238 cnt = read(fileno(instr), buf, sizeof(buf));
2239 CHECKOOB(return (-1))
2242 if (cnt < 0) /* resume after OOB */
2244 if (cnt == 0) /* EOF */
2246 for (len = cnt, bp = buf; len > 0;) {
2247 cnt = write(fileno(outstr), bp, len);
2248 CHECKOOB(return (-1))
2263 reply(553, "TYPE E not implemented.");
2270 CHECKOOB(return (-1))
2271 else if (c == EOF && ferror(instr))
2273 if (c == EOF && ferror(instr)) { /* resume after OOB */
2280 FTPD_PUTC('\r', outstr, file_err);
2290 /* Check for EOF here in order not to lose last \r. */
2292 if (feof(instr)) /* EOF */
2294 syslog(LOG_ERR, "Internal: impossible condition"
2295 " on data stream after getc()");
2300 FTPD_PUTC(c, outstr, file_err);
2303 #ifdef notyet /* BSD stdio isn't ready for that */
2304 while (fflush(outstr) == EOF) {
2305 CHECKOOB(return (-1))
2313 if (fflush(outstr) == EOF)
2318 "WARNING! %d bare linefeeds received in ASCII mode.",
2320 (void)printf(" File may not have transferred correctly.\r\n");
2325 reply(550, "Unimplemented TYPE %d in receive_data.", type);
2331 perror_reply(426, "Data connection");
2336 perror_reply(452, "Error writing to file");
2341 statfilecmd(char *filename)
2346 char line[LINE_MAX];
2349 code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2350 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2351 fin = ftpd_popen(line, "r");
2353 perror_reply(551, filename);
2356 lreply(code, "Status of %s:", filename);
2358 while ((c = getc(fin)) != EOF) {
2360 if (ferror(stdout)){
2361 perror_reply(421, "Control connection");
2362 (void) ftpd_pclose(fin);
2367 perror_reply(551, filename);
2368 (void) ftpd_pclose(fin);
2371 (void) putc('\r', stdout);
2374 * RFC 959 says neutral text should be prepended before
2375 * a leading 3-digit number followed by whitespace, but
2376 * many ftp clients can be confused by any leading digits,
2377 * as a matter of fact.
2379 if (atstart && isdigit(c))
2380 (void) putc(' ', stdout);
2381 (void) putc(c, stdout);
2382 atstart = (c == '\n');
2384 (void) ftpd_pclose(fin);
2385 reply(code, "End of status.");
2391 union sockunion *su;
2393 char hname[NI_MAXHOST];
2397 lreply(211, "%s FTP server status:", hostname);
2398 printf(" %s\r\n", version);
2400 lreply(211, "FTP server status:");
2401 printf(" Connected to %s", remotehost);
2402 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2403 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2404 hname[sizeof(hname) - 1] = 0;
2405 if (strcmp(hname, remotehost) != 0)
2406 printf(" (%s)", hname);
2411 printf(" Logged in anonymously\r\n");
2413 printf(" Logged in as %s\r\n", pw->pw_name);
2414 } else if (askpasswd)
2415 printf(" Waiting for password\r\n");
2417 printf(" Waiting for user name\r\n");
2418 printf(" TYPE: %s", typenames[type]);
2419 if (type == TYPE_A || type == TYPE_E)
2420 printf(", FORM: %s", formnames[form]);
2423 printf(" %d", CHAR_BIT);
2425 printf(" %d", bytesize); /* need definition! */
2427 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2428 strunames[stru], modenames[mode]);
2430 printf(" Data connection open\r\n");
2431 else if (pdata != -1) {
2435 } else if (usedefault == 0) {
2439 #define UC(b) (((int) b) & 0xff)
2441 printf(" EPSV only mode (EPSV ALL)\r\n");
2446 if (su->su_family == AF_INET) {
2447 a = (u_char *) &su->su_sin.sin_addr;
2448 p = (u_char *) &su->su_sin.sin_port;
2449 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2450 ispassive ? "PASV" : "PORT",
2451 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2452 UC(p[0]), UC(p[1]));
2459 switch (su->su_family) {
2461 a = (u_char *) &su->su_sin.sin_addr;
2462 p = (u_char *) &su->su_sin.sin_port;
2463 alen = sizeof(su->su_sin.sin_addr);
2467 a = (u_char *) &su->su_sin6.sin6_addr;
2468 p = (u_char *) &su->su_sin6.sin6_port;
2469 alen = sizeof(su->su_sin6.sin6_addr);
2477 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2479 for (i = 0; i < alen; i++)
2480 printf("%d,", UC(a[i]));
2481 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2490 switch (su->su_family) {
2502 union sockunion tmp;
2505 if (tmp.su_family == AF_INET6)
2506 tmp.su_sin6.sin6_scope_id = 0;
2507 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2508 hname, sizeof(hname) - 1, NULL, 0,
2510 hname[sizeof(hname) - 1] = 0;
2511 printf(" %s |%d|%s|%d|\r\n",
2512 ispassive ? "EPSV" : "EPRT",
2513 af, hname, htons(tmp.su_port));
2519 printf(" No data connection\r\n");
2520 reply(211, "End of status.");
2527 reply(451, "Error in server: %s", s);
2528 reply(221, "Closing connection due to server error.");
2534 reply(int n, const char *fmt, ...)
2538 (void)printf("%d ", n);
2540 (void)vprintf(fmt, ap);
2542 (void)printf("\r\n");
2543 (void)fflush(stdout);
2545 syslog(LOG_DEBUG, "<--- %d ", n);
2547 vsyslog(LOG_DEBUG, fmt, ap);
2553 lreply(int n, const char *fmt, ...)
2557 (void)printf("%d- ", n);
2559 (void)vprintf(fmt, ap);
2561 (void)printf("\r\n");
2562 (void)fflush(stdout);
2564 syslog(LOG_DEBUG, "<--- %d- ", n);
2566 vsyslog(LOG_DEBUG, fmt, ap);
2575 reply(250, "%s command successful.", s);
2582 reply(502, "%s command not implemented.", s);
2591 if ((cp = strchr(cbuf,'\n')))
2593 reply(500, "%s: command not understood.", cbuf);
2601 LOGCMD("delete", name);
2602 if (lstat(name, &st) < 0) {
2603 perror_reply(550, name);
2606 if (S_ISDIR(st.st_mode)) {
2607 if (rmdir(name) < 0) {
2608 perror_reply(550, name);
2613 if (guest && noguestmod) {
2614 reply(550, "Operation not permitted.");
2617 if (unlink(name) < 0) {
2618 perror_reply(550, name);
2629 if (chdir(path) < 0)
2630 perror_reply(550, path);
2640 LOGCMD("mkdir", name);
2641 if (guest && noguestmkd)
2642 reply(550, "Operation not permitted.");
2643 else if (mkdir(name, 0777) < 0)
2644 perror_reply(550, name);
2646 if ((s = doublequote(name)) == NULL)
2647 fatalerror("Ran out of memory.");
2648 reply(257, "\"%s\" directory created.", s);
2654 removedir(char *name)
2657 LOGCMD("rmdir", name);
2658 if (rmdir(name) < 0)
2659 perror_reply(550, name);
2667 char *s, path[MAXPATHLEN + 1];
2669 if (getcwd(path, sizeof(path)) == NULL)
2670 perror_reply(550, "Get current directory");
2672 if ((s = doublequote(path)) == NULL)
2673 fatalerror("Ran out of memory.");
2674 reply(257, "\"%s\" is current directory.", s);
2680 renamefrom(char *name)
2684 if (guest && noguestmod) {
2685 reply(550, "Operation not permitted.");
2688 if (lstat(name, &st) < 0) {
2689 perror_reply(550, name);
2692 reply(350, "File exists, ready for destination name.");
2697 renamecmd(char *from, char *to)
2701 LOGCMD2("rename", from, to);
2703 if (guest && (stat(to, &st) == 0)) {
2704 reply(550, "%s: permission denied.", to);
2708 if (rename(from, to) < 0)
2709 perror_reply(550, "rename");
2715 dolog(struct sockaddr *who)
2717 char who_name[NI_MAXHOST];
2719 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2720 remotehost[sizeof(remotehost) - 1] = 0;
2721 if (getnameinfo(who, who->sa_len,
2722 who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
2724 who_name[sizeof(who_name) - 1] = 0;
2727 #ifdef VIRTUAL_HOSTING
2728 if (thishost != firsthost)
2729 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2730 remotehost, hostname);
2733 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2735 setproctitle("%s", proctitle);
2736 #endif /* SETPROCTITLE */
2739 #ifdef VIRTUAL_HOSTING
2740 if (thishost != firsthost)
2741 syslog(LOG_INFO, "connection from %s (%s) to %s",
2742 remotehost, who_name, hostname);
2745 syslog(LOG_INFO, "connection from %s (%s)",
2746 remotehost, who_name);
2751 * Record logout in wtmp file
2752 * and exit with supplied status.
2755 dologout(int status)
2758 if (logged_in && dowtmp) {
2760 ftpd_logwtmp(wtmpid, NULL, NULL);
2762 /* beware of flushing buffers after a SIGPIPE */
2780 syslog(LOG_ERR, "Internal: maskurg() while no transfer");
2785 sigaddset(&sset, SIGURG);
2786 sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
2796 syslog(LOG_ERR, "Internal: flagxfer(1): "
2797 "transfer already under way");
2803 syslog(LOG_ERR, "Internal: flagxfer(0): "
2804 "no active transfer");
2811 * Returns 0 if OK to resume or -1 if abort requested.
2820 syslog(LOG_ERR, "Internal: myoob() while no transfer");
2824 ret = getline(cp, 7, stdin);
2826 reply(221, "You could at least say goodbye.");
2828 } else if (ret == -2) {
2829 /* Ignore truncated command. */
2833 if (strcmp(cp, "ABOR\r\n") == 0) {
2835 reply(426, "Transfer aborted. Data connection closed.");
2836 reply(226, "Abort successful.");
2839 if (strcmp(cp, "STAT\r\n") == 0) {
2841 if (file_size != -1)
2842 reply(213, "Status: %jd of %jd bytes transferred.",
2843 (intmax_t)byte_count, (intmax_t)file_size);
2845 reply(213, "Status: %jd bytes transferred.",
2846 (intmax_t)byte_count);
2852 * Note: a response of 425 is not mentioned as a possible response to
2853 * the PASV command in RFC959. However, it has been blessed as
2854 * a legitimate response by Jon Postel in a telephone conversation
2855 * with Rick Adams on 25 Jan 89.
2864 if (pdata >= 0) /* close old port if one set */
2867 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2869 perror_reply(425, "Can't open passive connection");
2873 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2874 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2879 if (ctrl_addr.su_family == AF_INET) {
2880 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2881 : IP_PORTRANGE_DEFAULT;
2883 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2884 &on, sizeof(on)) < 0)
2888 #ifdef IPV6_PORTRANGE
2889 if (ctrl_addr.su_family == AF_INET6) {
2890 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2891 : IPV6_PORTRANGE_DEFAULT;
2893 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2894 &on, sizeof(on)) < 0)
2899 pasv_addr = ctrl_addr;
2900 pasv_addr.su_port = 0;
2901 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2904 (void) seteuid(pw->pw_uid);
2906 len = sizeof(pasv_addr);
2907 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2909 if (listen(pdata, 1) < 0)
2911 if (pasv_addr.su_family == AF_INET)
2912 a = (char *) &pasv_addr.su_sin.sin_addr;
2913 else if (pasv_addr.su_family == AF_INET6 &&
2914 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2915 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2919 p = (char *) &pasv_addr.su_port;
2921 #define UC(b) (((int) b) & 0xff)
2923 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2924 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2928 (void) seteuid(pw->pw_uid);
2929 (void) close(pdata);
2931 perror_reply(425, "Can't open passive connection");
2936 * Long Passive defined in RFC 1639.
2937 * 228 Entering Long Passive Mode
2938 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2942 long_passive(char *cmd, int pf)
2948 if (pdata >= 0) /* close old port if one set */
2951 if (pf != PF_UNSPEC) {
2952 if (ctrl_addr.su_family != pf) {
2953 switch (ctrl_addr.su_family) {
2966 * only EPRT/EPSV ready clients will understand this
2968 if (strcmp(cmd, "EPSV") == 0 && pf) {
2969 reply(522, "Network protocol mismatch, "
2972 reply(501, "Network protocol mismatch."); /*XXX*/
2978 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2980 perror_reply(425, "Can't open passive connection");
2984 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2985 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2989 pasv_addr = ctrl_addr;
2990 pasv_addr.su_port = 0;
2991 len = pasv_addr.su_len;
2994 if (ctrl_addr.su_family == AF_INET) {
2995 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2996 : IP_PORTRANGE_DEFAULT;
2998 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2999 &on, sizeof(on)) < 0)
3003 #ifdef IPV6_PORTRANGE
3004 if (ctrl_addr.su_family == AF_INET6) {
3005 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
3006 : IPV6_PORTRANGE_DEFAULT;
3008 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
3009 &on, sizeof(on)) < 0)
3014 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
3017 (void) seteuid(pw->pw_uid);
3019 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
3021 if (listen(pdata, 1) < 0)
3024 #define UC(b) (((int) b) & 0xff)
3026 if (strcmp(cmd, "LPSV") == 0) {
3027 p = (char *)&pasv_addr.su_port;
3028 switch (pasv_addr.su_family) {
3030 a = (char *) &pasv_addr.su_sin.sin_addr;
3033 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3034 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3035 2, UC(p[0]), UC(p[1]));
3038 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
3039 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
3042 a = (char *) &pasv_addr.su_sin6.sin6_addr;
3044 "Entering Long Passive Mode "
3045 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3046 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3047 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3048 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3049 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3050 2, UC(p[0]), UC(p[1]));
3053 } else if (strcmp(cmd, "EPSV") == 0) {
3054 switch (pasv_addr.su_family) {
3057 reply(229, "Entering Extended Passive Mode (|||%d|)",
3058 ntohs(pasv_addr.su_port));
3062 /* more proper error code? */
3066 (void) seteuid(pw->pw_uid);
3067 (void) close(pdata);
3069 perror_reply(425, "Can't open passive connection");
3074 * Generate unique name for file with basename "local"
3075 * and open the file in order to avoid possible races.
3076 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3077 * Return descriptor to the file, set "name" to its name.
3079 * Generates failure reply on error.
3082 guniquefd(char *local, char **name)
3084 static char new[MAXPATHLEN];
3090 cp = strrchr(local, '/');
3093 if (stat(cp ? local : ".", &st) < 0) {
3094 perror_reply(553, cp ? local : ".");
3099 * Let not overwrite dirname with counter suffix.
3101 * In this extreme case dot won't be put in front of suffix.
3103 if (strlen(local) > sizeof(new) - 4) {
3104 reply(553, "Pathname too long.");
3109 /* -4 is for the .nn<null> we put on the end below */
3110 (void) snprintf(new, sizeof(new) - 4, "%s", local);
3111 cp = new + strlen(new);
3113 * Don't generate dotfile unless requested explicitly.
3114 * This covers the case when basename gets truncated off
3117 if (cp > new && cp[-1] != '/')
3119 for (count = 0; count < 100; count++) {
3120 /* At count 0 try unmodified name */
3122 (void)sprintf(cp, "%d", count);
3123 if ((fd = open(count ? new : local,
3124 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3125 *name = count ? new : local;
3128 if (errno != EEXIST) {
3129 perror_reply(553, count ? new : local);
3133 reply(452, "Unique file name cannot be created.");
3138 * Format and send reply containing system error number.
3141 perror_reply(int code, char *string)
3144 reply(code, "%s: %s.", string, strerror(errno));
3147 static char *onefile[] = {
3153 send_file_list(char *whichf)
3159 char **dirlist, *dirname;
3164 if (strpbrk(whichf, "~{[*?") != NULL) {
3165 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3167 memset(&gl, 0, sizeof(gl));
3168 gl.gl_matchc = MAXGLOBARGS;
3169 flags |= GLOB_LIMIT;
3171 if (glob(whichf, flags, 0, &gl)) {
3172 reply(550, "No matching files found.");
3174 } else if (gl.gl_pathc == 0) {
3176 perror_reply(550, whichf);
3179 dirlist = gl.gl_pathv;
3181 onefile[0] = whichf;
3186 while ((dirname = *dirlist++)) {
3187 if (stat(dirname, &st) < 0) {
3189 * If user typed "ls -l", etc, and the client
3190 * used NLST, do what the user meant.
3192 if (dirname[0] == '-' && *dirlist == NULL &&
3194 retrieve(_PATH_LS " %s", dirname);
3196 perror_reply(550, whichf);
3200 if (S_ISREG(st.st_mode)) {
3202 dout = dataconn("file list", -1, "w");
3208 fprintf(dout, "%s%s\n", dirname,
3209 type == TYPE_A ? "\r" : "");
3213 byte_count += strlen(dirname) +
3214 (type == TYPE_A ? 2 : 1);
3215 CHECKOOB(goto abrt);
3217 } else if (!S_ISDIR(st.st_mode))
3220 if ((dirp = opendir(dirname)) == NULL)
3223 while ((dir = readdir(dirp)) != NULL) {
3224 char nbuf[MAXPATHLEN];
3226 CHECKOOB(goto abrt);
3228 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
3230 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3234 snprintf(nbuf, sizeof(nbuf),
3235 "%s/%s", dirname, dir->d_name);
3238 * We have to do a stat to insure it's
3239 * not a directory or special file.
3241 if (simple || (stat(nbuf, &st) == 0 &&
3242 S_ISREG(st.st_mode))) {
3244 dout = dataconn("file list", -1, "w");
3250 if (nbuf[0] == '.' && nbuf[1] == '/')
3251 fprintf(dout, "%s%s\n", &nbuf[2],
3252 type == TYPE_A ? "\r" : "");
3254 fprintf(dout, "%s%s\n", nbuf,
3255 type == TYPE_A ? "\r" : "");
3259 byte_count += strlen(nbuf) +
3260 (type == TYPE_A ? 2 : 1);
3261 CHECKOOB(goto abrt);
3264 (void) closedir(dirp);
3269 reply(550, "No files found.");
3270 else if (ferror(dout))
3271 data_err: perror_reply(550, "Data connection");
3273 reply(226, "Transfer complete.");
3278 (void) fclose(dout);
3283 (void) closedir(dirp);
3291 reapchild(int signo)
3293 while (waitpid(-1, NULL, WNOHANG) > 0);
3296 #ifdef OLD_SETPROCTITLE
3298 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.)
3299 * Warning, since this is usually started from inetd.conf, it often doesn't
3300 * have much of an environment or arglist to overwrite.
3303 setproctitle(const char *fmt, ...)
3311 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
3313 /* make ps print our process name */
3318 if (i > LastArgv - p - 2) {
3319 i = LastArgv - p - 2;
3324 if (ch != '\n' && ch != '\r')
3326 while (p < LastArgv)
3329 #endif /* OLD_SETPROCTITLE */
3332 appendf(char **strp, char *fmt, ...)
3338 vasprintf(&p, fmt, ap);
3341 fatalerror("Ran out of memory.");
3346 asprintf(strp, "%s%s", ostr, p);
3348 fatalerror("Ran out of memory.");
3354 logcmd(char *cmd, char *file1, char *file2, off_t cnt)
3357 char wd[MAXPATHLEN + 1];
3362 if (getcwd(wd, sizeof(wd) - 1) == NULL)
3363 strcpy(wd, strerror(errno));
3365 appendf(&msg, "%s", cmd);
3367 appendf(&msg, " %s", file1);
3369 appendf(&msg, " %s", file2);
3371 appendf(&msg, " = %jd bytes", (intmax_t)cnt);
3372 appendf(&msg, " (wd: %s", wd);
3373 if (guest || dochroot)
3374 appendf(&msg, "; chrooted");
3376 syslog(LOG_INFO, "%s", msg);
3381 logxfer(char *name, off_t size, time_t start)
3383 char buf[MAXPATHLEN + 1024];
3384 char path[MAXPATHLEN + 1];
3389 if (realpath(name, path) == NULL) {
3390 syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
3393 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n",
3394 ctime(&now)+4, ident, remotehost,
3395 path, (intmax_t)size,
3396 (long)(now - start + (now == start)));
3397 write(statfd, buf, strlen(buf));
3402 doublequote(char *s)
3407 for (p = s, n = 0; *p; p++)
3411 if ((s2 = malloc(p - s + n + 1)) == NULL)
3414 for (p = s2; *s; s++, p++) {
3415 if ((*p = *s) == '"')
3423 /* setup server socket for specified address family */
3424 /* if af is PF_UNSPEC more than one socket may be returned */
3425 /* the returned list is dynamically allocated, so caller needs to free it */
3427 socksetup(int af, char *bindname, const char *bindport)
3429 struct addrinfo hints, *res, *r;
3430 int error, maxs, *s, *socks;
3433 memset(&hints, 0, sizeof(hints));
3434 hints.ai_flags = AI_PASSIVE;
3435 hints.ai_family = af;
3436 hints.ai_socktype = SOCK_STREAM;
3437 error = getaddrinfo(bindname, bindport, &hints, &res);
3439 syslog(LOG_ERR, "%s", gai_strerror(error));
3440 if (error == EAI_SYSTEM)
3441 syslog(LOG_ERR, "%s", strerror(errno));
3445 /* Count max number of sockets we may open */
3446 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3448 socks = malloc((maxs + 1) * sizeof(int));
3451 syslog(LOG_ERR, "couldn't allocate memory for sockets");
3455 *socks = 0; /* num of sockets counter at start of array */
3457 for (r = res; r; r = r->ai_next) {
3458 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3460 syslog(LOG_DEBUG, "control socket: %m");
3463 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3464 &on, sizeof(on)) < 0)
3466 "control setsockopt (SO_REUSEADDR): %m");
3467 if (r->ai_family == AF_INET6) {
3468 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3469 &on, sizeof(on)) < 0)
3471 "control setsockopt (IPV6_V6ONLY): %m");
3473 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3474 syslog(LOG_DEBUG, "control bind: %m");
3486 syslog(LOG_ERR, "control socket: Couldn't bind to any socket");