2 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 static char copyright[] =
33 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
34 The Regents of the University of California. All rights reserved.\n";
40 static char sccsid[] = "@(#)ftpd.c 8.4 (Berkeley) 4/16/94";
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
50 #include <sys/param.h>
51 #include <sys/ioctl.h>
53 #include <sys/socket.h>
58 #include <netinet/in.h>
59 #include <netinet/in_systm.h>
60 #include <netinet/ip.h>
61 #include <netinet/tcp.h>
65 #include <arpa/inet.h>
66 #include <arpa/telnet.h>
89 #include <login_cap.h>
93 #include <security/pam_appl.h>
96 #include "pathnames.h"
101 static char version[] = "Version 6.00LS";
104 union sockunion ctrl_addr;
105 union sockunion data_source;
106 union sockunion data_dest;
107 union sockunion his_addr;
108 union sockunion pasv_addr;
113 int hostinfo = 1; /* print host-specific info in messages */
118 int timeout = 900; /* timeout after 15 minutes of inactivity */
119 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
121 int restricted_data_ports = 1;
122 int paranoid = 1; /* be extra careful about security */
123 int anon_only = 0; /* Only anonymous ftp allowed */
124 int assumeutf8 = 0; /* Assume that server file names are in UTF-8 */
133 int stru; /* avoid C keyword */
135 int usedefault = 1; /* for data transfers */
136 int pdata = -1; /* for passive mode */
137 int readonly = 0; /* Server is in readonly mode. */
138 int noepsv = 0; /* EPSV command is disabled. */
139 int noretr = 0; /* RETR command is disabled. */
140 int noguestretr = 0; /* RETR command is disabled for anon users. */
141 int noguestmkd = 0; /* MKD command is disabled for anon users. */
142 int noguestmod = 1; /* anon users may not modify existing files. */
146 #if !defined(CMASK) || CMASK == 0
150 int defumask = CMASK; /* default umask value */
155 #ifdef VIRTUAL_HOSTING
158 static struct ftphost {
159 struct ftphost *next;
160 struct addrinfo *hostinfo;
166 } *thishost, *firsthost;
169 char remotehost[NI_MAXHOST];
172 static char wtmpid[20];
175 static int auth_pam(struct passwd**, const char*);
176 pam_handle_t *pamh = NULL;
179 static struct opie opiedata;
180 static char opieprompt[OPIE_CHALLENGE_MAX+1];
183 char *pid_file = NULL; /* means default location to pidfile(3) */
186 * Limit number of pathnames that glob can return.
187 * A limit of 0 indicates the number of pathnames is unlimited.
189 #define MAXGLOBARGS 16384
193 * Timeout intervals for retrying connections
194 * to hosts that don't accept PORT cmds. This
195 * is a kludge, but given the problems with TCP...
197 #define SWAITMAX 90 /* wait at most 90 seconds */
198 #define SWAITINT 5 /* interval between retries */
200 int swaitmax = SWAITMAX;
201 int swaitint = SWAITINT;
204 #ifdef OLD_SETPROCTITLE
205 char **Argv = NULL; /* pointer to argument vector */
206 char *LastArgv = NULL; /* end of argv */
207 #endif /* OLD_SETPROCTITLE */
208 char proctitle[LINE_MAX]; /* initial part of title */
209 #endif /* SETPROCTITLE */
211 #define LOGCMD(cmd, file) logcmd((cmd), (file), NULL, -1)
212 #define LOGCMD2(cmd, file1, file2) logcmd((cmd), (file1), (file2), -1)
213 #define LOGBYTES(cmd, file, cnt) logcmd((cmd), (file), NULL, (cnt))
215 static volatile sig_atomic_t recvurg;
216 static int transflag; /* NB: for debugging only */
218 #define STARTXFER flagxfer(1)
219 #define ENDXFER flagxfer(0)
221 #define START_UNSAFE maskurg(1)
222 #define END_UNSAFE maskurg(0)
224 /* It's OK to put an `else' clause after this macro. */
225 #define CHECKOOB(action) \
234 #ifdef VIRTUAL_HOSTING
235 static void inithosts(int);
236 static void selecthost(union sockunion *);
238 static void ack(char *);
239 static void sigurg(int);
240 static void maskurg(int);
241 static void flagxfer(int);
242 static int myoob(void);
243 static int checkuser(char *, char *, int, char **, int *);
244 static FILE *dataconn(char *, off_t, char *);
245 static void dolog(struct sockaddr *);
246 static void end_login(void);
247 static FILE *getdatasock(char *);
248 static int guniquefd(char *, char **);
249 static void lostconn(int);
250 static void sigquit(int);
251 static int receive_data(FILE *, FILE *);
252 static int send_data(FILE *, FILE *, size_t, off_t, int);
253 static struct passwd *
255 static char *sgetsave(char *);
256 static void reapchild(int);
257 static void appendf(char **, char *, ...) __printflike(2, 3);
258 static void logcmd(char *, char *, char *, off_t);
259 static void logxfer(char *, off_t, time_t);
260 static char *doublequote(char *);
261 static int *socksetup(int, char *, const char *);
264 main(int argc, char *argv[], char **envp)
268 char *cp, line[LINE_MAX];
270 char *bindname = NULL;
271 const char *bindport = "ftp";
272 int family = AF_UNSPEC;
275 tzset(); /* in case no timezone database in ~ftp */
276 sigemptyset(&sa.sa_mask);
277 sa.sa_flags = SA_RESTART;
279 #ifdef OLD_SETPROCTITLE
281 * Save start and extent of argv for setproctitle.
286 LastArgv = envp[-1] + strlen(envp[-1]);
287 #endif /* OLD_SETPROCTITLE */
290 * Prevent diagnostic messages from appearing on stderr.
291 * We run as a daemon or from inetd; in both cases, there's
292 * more reason in logging to syslog.
294 (void) freopen(_PATH_DEVNULL, "w", stderr);
298 * LOG_NDELAY sets up the logging connection immediately,
299 * necessary for anonymous ftp's that chroot and can't do it later.
301 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
303 while ((ch = getopt(argc, argv,
304 "468a:AdDEhlmMoOp:P:rRSt:T:u:UvW")) != -1) {
307 family = (family == AF_INET6) ? AF_UNSPEC : AF_INET;
311 family = (family == AF_INET) ? AF_UNSPEC : AF_INET6;
343 logging++; /* > 1 == extra logging */
383 timeout = atoi(optarg);
384 if (maxtimeout < timeout)
385 maxtimeout = timeout;
389 maxtimeout = atoi(optarg);
390 if (timeout > maxtimeout)
391 timeout = maxtimeout;
398 val = strtol(optarg, &optarg, 8);
399 if (*optarg != '\0' || val < 0)
400 syslog(LOG_WARNING, "bad value for -u");
406 restricted_data_ports = 0;
418 syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
424 int *ctl_sock, fd, maxfd = -1, nfds, i;
425 fd_set defreadfds, readfds;
429 if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
430 if (errno == EEXIST) {
431 syslog(LOG_ERR, "%s already running, pid %d",
432 getprogname(), (int)pid);
435 syslog(LOG_WARNING, "pidfile_open: %m");
439 * Detach from parent.
441 if (daemon(1, 1) < 0) {
442 syslog(LOG_ERR, "failed to become a daemon");
446 if (pfh != NULL && pidfile_write(pfh) == -1)
447 syslog(LOG_WARNING, "pidfile_write: %m");
449 sa.sa_handler = reapchild;
450 (void)sigaction(SIGCHLD, &sa, NULL);
452 #ifdef VIRTUAL_HOSTING
457 * Open a socket, bind it to the FTP port, and start
460 ctl_sock = socksetup(family, bindname, bindport);
461 if (ctl_sock == NULL)
464 FD_ZERO(&defreadfds);
465 for (i = 1; i <= *ctl_sock; i++) {
466 FD_SET(ctl_sock[i], &defreadfds);
467 if (listen(ctl_sock[i], 32) < 0) {
468 syslog(LOG_ERR, "control listen: %m");
471 if (maxfd < ctl_sock[i])
476 * Loop forever accepting connection requests and forking off
477 * children to handle them.
480 FD_COPY(&defreadfds, &readfds);
481 nfds = select(maxfd + 1, &readfds, NULL, NULL, 0);
483 if (nfds < 0 && errno != EINTR)
484 syslog(LOG_WARNING, "select: %m");
489 for (i = 1; i <= *ctl_sock; i++)
490 if (FD_ISSET(ctl_sock[i], &readfds)) {
491 addrlen = sizeof(his_addr);
492 fd = accept(ctl_sock[i],
493 (struct sockaddr *)&his_addr,
500 switch (pid = fork()) {
506 for (i = 1; i <= *ctl_sock; i++)
512 syslog(LOG_WARNING, "fork: %m");
520 addrlen = sizeof(his_addr);
521 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
522 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
526 #ifdef VIRTUAL_HOSTING
527 if (his_addr.su_family == AF_INET6 &&
528 IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))
531 family = his_addr.su_family;
537 sa.sa_handler = SIG_DFL;
538 (void)sigaction(SIGCHLD, &sa, NULL);
540 sa.sa_handler = sigurg;
541 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
542 (void)sigaction(SIGURG, &sa, NULL);
544 sigfillset(&sa.sa_mask); /* block all signals in handler */
545 sa.sa_flags = SA_RESTART;
546 sa.sa_handler = sigquit;
547 (void)sigaction(SIGHUP, &sa, NULL);
548 (void)sigaction(SIGINT, &sa, NULL);
549 (void)sigaction(SIGQUIT, &sa, NULL);
550 (void)sigaction(SIGTERM, &sa, NULL);
552 sa.sa_handler = lostconn;
553 (void)sigaction(SIGPIPE, &sa, NULL);
555 addrlen = sizeof(ctrl_addr);
556 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
557 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
560 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
561 #ifdef VIRTUAL_HOSTING
562 /* select our identity from virtual host table */
563 selecthost(&ctrl_addr);
566 if (ctrl_addr.su_family == AF_INET)
568 tos = IPTOS_LOWDELAY;
569 if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
570 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
574 * Disable Nagle on the control channel so that we don't have to wait
575 * for peer's ACK before issuing our next reply.
577 if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
578 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
580 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
582 (void)snprintf(wtmpid, sizeof(wtmpid), "%xftpd", getpid());
584 /* Try to handle urgent data inline */
586 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
587 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
591 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
592 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
594 dolog((struct sockaddr *)&his_addr);
596 * Set up default state
605 /* If logins are disabled, print out the message. */
606 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
607 while (fgets(line, sizeof(line), fd) != NULL) {
608 if ((cp = strchr(line, '\n')) != NULL)
610 lreply(530, "%s", line);
612 (void) fflush(stdout);
614 reply(530, "System not available.");
617 #ifdef VIRTUAL_HOSTING
618 fd = fopen(thishost->welcome, "r");
620 fd = fopen(_PATH_FTPWELCOME, "r");
623 while (fgets(line, sizeof(line), fd) != NULL) {
624 if ((cp = strchr(line, '\n')) != NULL)
626 lreply(220, "%s", line);
628 (void) fflush(stdout);
630 /* reply(220,) must follow */
632 #ifndef VIRTUAL_HOSTING
633 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
634 fatalerror("Ran out of memory.");
635 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
637 hostname[MAXHOSTNAMELEN - 1] = '\0';
640 reply(220, "%s FTP server (%s) ready.", hostname, version);
642 reply(220, "FTP server ready.");
653 syslog(LOG_DEBUG, "lost connection");
661 syslog(LOG_ERR, "got signal %d", signo);
665 #ifdef VIRTUAL_HOSTING
667 * read in virtual host tables (if they exist)
671 inithosts(int family)
676 char *cp, *mp, *line;
678 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
679 struct ftphost *hrp, *lhrp;
680 struct addrinfo hints, *res, *ai;
683 * Fill in the default host information
685 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
686 fatalerror("Ran out of memory.");
687 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
689 hostname[MAXHOSTNAMELEN - 1] = '\0';
690 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
691 fatalerror("Ran out of memory.");
692 hrp->hostname = hostname;
693 hrp->hostinfo = NULL;
695 memset(&hints, 0, sizeof(hints));
696 hints.ai_flags = AI_PASSIVE;
697 hints.ai_family = family;
698 hints.ai_socktype = SOCK_STREAM;
699 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
701 hrp->statfile = _PATH_FTPDSTATFILE;
702 hrp->welcome = _PATH_FTPWELCOME;
703 hrp->loginmsg = _PATH_FTPLOGINMESG;
704 hrp->anonuser = "ftp";
706 thishost = firsthost = lhrp = hrp;
707 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
708 int addrsize, gothost;
712 while ((line = fgetln(fp, &len)) != NULL) {
718 if (line[len - 1] == '\n') {
719 line[len - 1] = '\0';
722 if ((mp = malloc(len + 1)) == NULL)
723 fatalerror("Ran out of memory.");
724 memcpy(mp, line, len);
728 cp = strtok(line, " \t");
729 /* skip empty lines */
736 statfile = _PATH_FTPDSTATFILE;
737 welcome = _PATH_FTPWELCOME;
738 loginmsg = _PATH_FTPLOGINMESG;
741 * Preparse the line so we can use its info
742 * for all the addresses associated with
743 * the virtual host name.
744 * Field 0, the virtual host name, is special:
745 * it's already parsed off and will be strdup'ed
746 * later, after we know its canonical form.
748 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
749 if (*cp != '-' && (cp = strdup(cp)))
751 case 1: /* anon user permissions */
754 case 2: /* statistics file */
757 case 3: /* welcome message */
760 case 4: /* login message */
763 default: /* programming error */
768 hints.ai_flags = AI_PASSIVE;
769 hints.ai_family = family;
770 hints.ai_socktype = SOCK_STREAM;
771 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
773 for (ai = res; ai != NULL && ai->ai_addr != NULL;
777 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
780 for (hi = hrp->hostinfo; hi != NULL;
782 if (hi->ai_addrlen == ai->ai_addrlen &&
785 ai->ai_addr->sa_len) == 0) {
793 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
795 hrp->hostname = NULL;
798 if (hrp->hostinfo && hrp->hostinfo != res)
799 freeaddrinfo(hrp->hostinfo);
800 insert = 0; /* host already in the chain */
805 * determine hostname to use.
806 * force defined name if there is a valid alias
807 * otherwise fallback to primary hostname
809 /* XXX: getaddrinfo() can't do alias check */
810 switch(hrp->hostinfo->ai_family) {
812 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
813 addrsize = sizeof(struct in_addr);
816 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
817 addrsize = sizeof(struct in6_addr);
820 /* should not reach here */
821 freeaddrinfo(hrp->hostinfo);
823 free(hrp); /*not in chain, can free*/
825 hrp->hostinfo = NULL; /*mark as blank*/
829 if ((hp = getipnodebyaddr(addr, addrsize,
830 hrp->hostinfo->ai_family,
831 &hp_error)) != NULL) {
832 if (strcmp(vhost, hp->h_name) != 0) {
833 if (hp->h_aliases == NULL)
837 while (hp->h_aliases[i] &&
838 strcmp(vhost, hp->h_aliases[i]) != 0)
840 if (hp->h_aliases[i] == NULL)
846 strcmp(hrp->hostname, vhost) != 0) {
848 hrp->hostname = NULL;
850 if (hrp->hostname == NULL &&
851 (hrp->hostname = strdup(vhost)) == NULL) {
852 freeaddrinfo(hrp->hostinfo);
853 hrp->hostinfo = NULL; /* mark as blank */
858 hrp->anonuser = anonuser;
859 hrp->statfile = statfile;
860 hrp->welcome = welcome;
861 hrp->loginmsg = loginmsg;
879 selecthost(union sockunion *su)
884 struct in6_addr *mapped_in6 = NULL;
890 * XXX IPv4 mapped IPv6 addr consideraton,
891 * specified in rfc2373.
893 if (su->su_family == AF_INET6 &&
894 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
895 mapped_in6 = &su->su_sin6.sin6_addr;
898 hrp = thishost = firsthost; /* default */
901 while (hrp != NULL) {
902 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
903 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
908 /* XXX IPv4 mapped IPv6 addr consideraton */
909 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
910 (memcmp(&mapped_in6->s6_addr[12],
911 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
912 sizeof(struct in_addr)) == 0)) {
922 /* setup static variables as appropriate */
923 hostname = thishost->hostname;
924 ftpuser = thishost->anonuser;
929 * Helper function for sgetpwnam().
934 char *new = malloc(strlen(s) + 1);
937 reply(421, "Ran out of memory.");
941 (void) strcpy(new, s);
946 * Save the result of a getpwnam. Used for USER command, since
947 * the data returned must not be clobbered by any other command
949 * NB: The data returned by sgetpwnam() will remain valid until
950 * the next call to this function. Its difference from getpwnam()
951 * is that sgetpwnam() is known to be called from ftpd code only.
953 static struct passwd *
954 sgetpwnam(char *name)
956 static struct passwd save;
959 if ((p = getpwnam(name)) == NULL)
963 free(save.pw_passwd);
970 save.pw_name = sgetsave(p->pw_name);
971 save.pw_passwd = sgetsave(p->pw_passwd);
972 save.pw_class = sgetsave(p->pw_class);
973 save.pw_gecos = sgetsave(p->pw_gecos);
974 save.pw_dir = sgetsave(p->pw_dir);
975 save.pw_shell = sgetsave(p->pw_shell);
979 static int login_attempts; /* number of failed login attempts */
980 static int askpasswd; /* had user command, ask for passwd */
981 static char curname[MAXLOGNAME]; /* current USER name */
985 * Sets global passwd pointer pw if named account exists and is acceptable;
986 * sets askpasswd if a PASS command is expected. If logged in previously,
987 * need to reset state. If name is "ftp" or "anonymous", the name is not in
988 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
989 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
990 * requesting login privileges. Disallow anyone who does not have a standard
991 * shell as returned by getusershell(). Disallow anyone mentioned in the file
992 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
1002 reply(530, "Can't change user from guest login.");
1004 } else if (dochroot) {
1005 reply(530, "Can't change user from chroot user.");
1012 #ifdef VIRTUAL_HOSTING
1013 pw = sgetpwnam(thishost->anonuser);
1015 pw = sgetpwnam("ftp");
1017 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1018 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL, &ecode) ||
1019 (ecode != 0 && ecode != ENOENT))
1020 reply(530, "User %s access denied.", name);
1021 else if (checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL, &ecode) ||
1022 (ecode != 0 && ecode != ENOENT))
1023 reply(530, "User %s access denied.", name);
1024 else if (pw != NULL) {
1028 "Guest login ok, send your email address as password.");
1030 reply(530, "User %s unknown.", name);
1031 if (!askpasswd && logging)
1033 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1036 if (anon_only != 0) {
1037 reply(530, "Sorry, only anonymous ftp allowed.");
1041 if ((pw = sgetpwnam(name))) {
1042 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1043 shell = _PATH_BSHELL;
1045 while ((cp = getusershell()) != NULL)
1046 if (strcmp(cp, shell) == 0)
1051 (checkuser(_PATH_FTPUSERS, name, 1, NULL, &ecode) ||
1052 (ecode != 0 && ecode != ENOENT))) {
1053 reply(530, "User %s access denied.", name);
1056 "FTP LOGIN REFUSED FROM %s, %s",
1063 strncpy(curname, name, sizeof(curname)-1);
1067 /* XXX Kluge! The conversation mechanism needs to be fixed. */
1069 if (opiechallenge(&opiedata, name, opieprompt) == 0) {
1070 pwok = (pw != NULL) &&
1071 opieaccessfile(remotehost) &&
1072 opiealways(pw->pw_dir);
1073 reply(331, "Response to %s %s for %s.",
1074 opieprompt, pwok ? "requested" : "required", name);
1077 reply(331, "Password required for %s.", name);
1081 * Delay before reading passwd after first failed
1082 * attempt to slow down passwd-guessing programs.
1085 sleep(login_attempts);
1089 * Check if a user is in the file "fname",
1090 * return a pointer to a malloc'd string with the rest
1091 * of the matching line in "residue" if not NULL.
1094 checkuser(char *fname, char *name, int pwset, char **residue, int *ecode)
1099 char *line, *mp, *p;
1103 if ((fd = fopen(fname, "r")) != NULL) {
1104 while (!found && (line = fgetln(fd, &len)) != NULL) {
1108 if (line[len - 1] == '\n') {
1109 line[len - 1] = '\0';
1112 if ((mp = malloc(len + 1)) == NULL)
1113 fatalerror("Ran out of memory.");
1114 memcpy(mp, line, len);
1118 /* avoid possible leading and trailing whitespace */
1119 p = strtok(line, " \t");
1120 /* skip empty lines */
1124 * if first chr is '@', check group membership
1130 if (p[1] == '\0') /* single @ matches anyone */
1133 if ((grp = getgrnam(p+1)) == NULL)
1136 * Check user's default group
1138 if (pwset && grp->gr_gid == pw->pw_gid)
1141 * Check supplementary groups
1143 while (!found && grp->gr_mem[i])
1144 found = strcmp(name,
1150 * Otherwise, just check for username match
1153 found = strcmp(p, name) == 0;
1155 * Save the rest of line to "residue" if matched
1157 if (found && residue) {
1158 if ((p = strtok(NULL, "")) != NULL)
1159 p += strspn(p, " \t");
1161 if ((*residue = strdup(p)) == NULL)
1162 fatalerror("Ran out of memory.");
1171 } else if (ecode != NULL)
1177 * Terminate login as previous user, if any, resetting state;
1178 * used when USER command is given or login fails.
1188 if (logged_in && dowtmp)
1189 ftpd_logwtmp(wtmpid, NULL, NULL);
1192 setusercontext(NULL, getpwuid(0), 0, LOGIN_SETALL & ~(LOGIN_SETLOGIN |
1193 LOGIN_SETUSER | LOGIN_SETGROUP | LOGIN_SETPATH |
1198 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1199 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1200 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1201 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1202 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1203 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1215 * the following code is stolen from imap-uw PAM authentication module and
1218 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1221 const char *uname; /* user name */
1222 const char *pass; /* password */
1224 typedef struct cred_t cred_t;
1227 auth_conv(int num_msg, const struct pam_message **msg,
1228 struct pam_response **resp, void *appdata)
1231 cred_t *cred = (cred_t *) appdata;
1232 struct pam_response *reply;
1234 reply = calloc(num_msg, sizeof *reply);
1238 for (i = 0; i < num_msg; i++) {
1239 switch (msg[i]->msg_style) {
1240 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1241 reply[i].resp_retcode = PAM_SUCCESS;
1242 reply[i].resp = COPY_STRING(cred->uname);
1243 /* PAM frees resp. */
1245 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1246 reply[i].resp_retcode = PAM_SUCCESS;
1247 reply[i].resp = COPY_STRING(cred->pass);
1248 /* PAM frees resp. */
1252 reply[i].resp_retcode = PAM_SUCCESS;
1253 reply[i].resp = NULL;
1255 default: /* unknown message style */
1257 return PAM_CONV_ERR;
1266 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1267 * authenticated, or 1 if not authenticated. If some sort of PAM system
1268 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1269 * function returns -1. This can be used as an indication that we should
1270 * fall back to a different authentication mechanism.
1273 auth_pam(struct passwd **ppw, const char *pass)
1275 const char *tmpl_user;
1279 cred_t auth_cred = { (*ppw)->pw_name, pass };
1280 struct pam_conv conv = { &auth_conv, &auth_cred };
1282 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1283 if (e != PAM_SUCCESS) {
1285 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1286 * if context creation has failed in the first place.
1288 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
1292 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1293 if (e != PAM_SUCCESS) {
1294 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1295 pam_strerror(pamh, e));
1296 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1297 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1303 e = pam_authenticate(pamh, 0);
1307 * With PAM we support the concept of a "template"
1308 * user. The user enters a login name which is
1309 * authenticated by PAM, usually via a remote service
1310 * such as RADIUS or TACACS+. If authentication
1311 * succeeds, a different but related "template" name
1312 * is used for setting the credentials, shell, and
1313 * home directory. The name the user enters need only
1314 * exist on the remote authentication server, but the
1315 * template name must be present in the local password
1318 * This is supported by two various mechanisms in the
1319 * individual modules. However, from the application's
1320 * point of view, the template user is always passed
1321 * back as a changed value of the PAM_USER item.
1323 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1325 tmpl_user = (const char *) item;
1326 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1327 *ppw = getpwnam(tmpl_user);
1329 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1330 pam_strerror(pamh, e));
1335 case PAM_USER_UNKNOWN:
1341 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1347 e = pam_acct_mgmt(pamh, 0);
1348 if (e != PAM_SUCCESS) {
1349 syslog(LOG_ERR, "pam_acct_mgmt: %s",
1350 pam_strerror(pamh, e));
1356 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1357 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1364 #endif /* USE_PAM */
1372 login_cap_t *lc = NULL;
1377 char *residue = NULL;
1380 if (logged_in || askpasswd == 0) {
1381 reply(503, "Login with USER first.");
1385 if (!guest) { /* "ftp" is only account allowed no password */
1387 rval = 1; /* failure below */
1391 rval = auth_pam(&pw, passwd);
1397 if (opieverify(&opiedata, passwd) == 0)
1398 xpasswd = pw->pw_passwd;
1400 xpasswd = crypt(passwd, pw->pw_passwd);
1401 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1407 rval = strcmp(pw->pw_passwd, xpasswd);
1408 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1409 rval = 1; /* failure */
1412 * If rval == 1, the user failed the authentication check
1413 * above. If rval == 0, either PAM or local authentication
1417 reply(530, "Login incorrect.");
1420 "FTP LOGIN FAILED FROM %s",
1422 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1423 "FTP LOGIN FAILED FROM %s, %s",
1424 remotehost, curname);
1427 if (login_attempts++ >= 5) {
1429 "repeated login failures from %s",
1436 login_attempts = 0; /* this time successful */
1437 if (setegid(pw->pw_gid) < 0) {
1438 reply(550, "Can't set gid.");
1441 /* May be overridden by login.conf */
1442 (void) umask(defumask);
1444 if ((lc = login_getpwclass(pw)) != NULL) {
1445 char remote_ip[NI_MAXHOST];
1447 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1448 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1451 remote_ip[sizeof(remote_ip) - 1] = 0;
1452 if (!auth_hostok(lc, remotehost, remote_ip)) {
1453 syslog(LOG_INFO|LOG_AUTH,
1454 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1456 reply(530, "Permission denied.");
1460 if (!auth_timeok(lc, time(NULL))) {
1461 reply(530, "Login not available right now.");
1466 setusercontext(lc, pw, 0, LOGIN_SETALL &
1467 ~(LOGIN_SETUSER | LOGIN_SETPATH | LOGIN_SETENV));
1469 setlogin(pw->pw_name);
1470 (void) initgroups(pw->pw_name, pw->pw_gid);
1475 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1476 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1477 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1478 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1484 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue, &ecode)
1485 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1486 || login_getcapbool(lc, "ftp-chroot", 0)
1490 * It is possible that checkuser() failed to open the chroot file.
1491 * If this is the case, report that logins are un-available, since we
1492 * have no way of checking whether or not the user should be chrooted.
1493 * We ignore ENOENT since it is not required that this file be present.
1495 if (ecode != 0 && ecode != ENOENT) {
1496 reply(530, "Login not available right now.");
1501 /* Disable wtmp logging when chrooting. */
1502 if (dochroot || guest)
1505 ftpd_logwtmp(wtmpid, pw->pw_name,
1506 (struct sockaddr *)&his_addr);
1509 if (guest && stats && statfd < 0)
1510 #ifdef VIRTUAL_HOSTING
1511 statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1513 statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1519 * For a chrooted local user,
1520 * a) see whether ftpchroot(5) specifies a chroot directory,
1521 * b) extract the directory pathname from the line,
1522 * c) expand it to the absolute pathname if necessary.
1524 if (dochroot && residue &&
1525 (chrootdir = strtok(residue, " \t")) != NULL) {
1526 if (chrootdir[0] != '/')
1527 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1529 chrootdir = strdup(chrootdir); /* make it permanent */
1530 if (chrootdir == NULL)
1531 fatalerror("Ran out of memory.");
1533 if (guest || dochroot) {
1535 * If no chroot directory set yet, use the login directory.
1536 * Copy it so it can be modified while pw->pw_dir stays intact.
1538 if (chrootdir == NULL &&
1539 (chrootdir = strdup(pw->pw_dir)) == NULL)
1540 fatalerror("Ran out of memory.");
1542 * Check for the "/chroot/./home" syntax,
1543 * separate the chroot and home directory pathnames.
1545 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1546 *(homedir++) = '\0'; /* wipe '/' */
1547 homedir++; /* skip '.' */
1550 * We MUST do a chdir() after the chroot. Otherwise
1551 * the old current directory will be accessible as "."
1552 * outside the new root!
1557 * Finally, do chroot()
1559 if (chroot(chrootdir) < 0) {
1560 reply(550, "Can't change root.");
1563 __FreeBSD_libc_enter_restricted_mode();
1564 } else /* real user w/o chroot */
1565 homedir = pw->pw_dir;
1567 * Set euid *before* doing chdir() so
1568 * a) the user won't be carried to a directory that he couldn't reach
1569 * on his own due to no permission to upper path components,
1570 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1571 * (uid 0 has no root power over NFS if not mapped explicitly.)
1573 if (seteuid(pw->pw_uid) < 0) {
1574 reply(550, "Can't set uid.");
1577 if (chdir(homedir) < 0) {
1578 if (guest || dochroot) {
1579 reply(550, "Can't change to base directory.");
1582 if (chdir("/") < 0) {
1583 reply(550, "Root is inaccessible.");
1586 lreply(230, "No directory! Logging in with home=/.");
1591 * Display a login message, if it exists.
1592 * N.B. reply(230,) must follow the message.
1594 #ifdef VIRTUAL_HOSTING
1595 fd = fopen(thishost->loginmsg, "r");
1597 fd = fopen(_PATH_FTPLOGINMESG, "r");
1600 char *cp, line[LINE_MAX];
1602 while (fgets(line, sizeof(line), fd) != NULL) {
1603 if ((cp = strchr(line, '\n')) != NULL)
1605 lreply(230, "%s", line);
1607 (void) fflush(stdout);
1613 ident = strdup(passwd);
1615 fatalerror("Ran out of memory.");
1617 reply(230, "Guest login ok, access restrictions apply.");
1619 #ifdef VIRTUAL_HOSTING
1620 if (thishost != firsthost)
1621 snprintf(proctitle, sizeof(proctitle),
1622 "%s: anonymous(%s)/%s", remotehost, hostname,
1626 snprintf(proctitle, sizeof(proctitle),
1627 "%s: anonymous/%s", remotehost, passwd);
1628 setproctitle("%s", proctitle);
1629 #endif /* SETPROCTITLE */
1631 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1632 remotehost, passwd);
1635 reply(230, "User %s logged in, "
1636 "access restrictions apply.", pw->pw_name);
1638 reply(230, "User %s logged in.", pw->pw_name);
1641 snprintf(proctitle, sizeof(proctitle),
1642 "%s: user/%s", remotehost, pw->pw_name);
1643 setproctitle("%s", proctitle);
1644 #endif /* SETPROCTITLE */
1646 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1647 remotehost, pw->pw_name);
1649 if (logging && (guest || dochroot))
1650 syslog(LOG_INFO, "session root changed to %s", chrootdir);
1658 /* Forget all about it... */
1668 retrieve(char *cmd, char *name)
1672 int (*closefunc)(FILE *);
1676 fin = fopen(name, "r"), closefunc = fclose;
1681 (void) snprintf(line, sizeof(line), cmd, name), name = line;
1682 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1684 st.st_blksize = BUFSIZ;
1688 perror_reply(550, name);
1690 LOGCMD("get", name);
1697 if (fstat(fileno(fin), &st) < 0) {
1698 perror_reply(550, name);
1701 if (!S_ISREG(st.st_mode)) {
1703 * Never sending a raw directory is a workaround
1704 * for buggy clients that will attempt to RETR
1705 * a directory before listing it, e.g., Mozilla.
1706 * Preventing a guest from getting irregular files
1707 * is a simple security measure.
1709 if (S_ISDIR(st.st_mode) || guest) {
1710 reply(550, "%s: not a plain file.", name);
1714 /* st.st_blksize is set for all descriptor types */
1717 if (restart_point) {
1718 if (type == TYPE_A) {
1725 if ((c=getc(fin)) == EOF) {
1726 perror_reply(550, name);
1732 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1733 perror_reply(550, name);
1737 dout = dataconn(name, st.st_size, "w");
1741 send_data(fin, dout, st.st_blksize, st.st_size,
1742 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1743 if (cmd == 0 && guest && stats && byte_count > 0)
1744 logxfer(name, byte_count, start);
1745 (void) fclose(dout);
1750 LOGBYTES("get", name, byte_count);
1755 store(char *name, char *mode, int unique)
1759 int (*closefunc)(FILE *);
1761 if (*mode == 'a') { /* APPE */
1763 /* Programming error */
1764 syslog(LOG_ERR, "Internal: unique flag to APPE");
1767 if (guest && noguestmod) {
1768 reply(550, "Appending to existing file denied.");
1771 restart_point = 0; /* not affected by preceding REST */
1773 if (unique) /* STOU overrides REST */
1775 if (guest && noguestmod) {
1776 if (restart_point) { /* guest STOR w/REST */
1777 reply(550, "Modifying existing file denied.");
1779 } else /* treat guest STOR as STOU */
1784 mode = "r+"; /* so ASCII manual seek can work */
1786 if ((fd = guniquefd(name, &name)) < 0)
1788 fout = fdopen(fd, mode);
1790 fout = fopen(name, mode);
1793 perror_reply(553, name);
1797 if (restart_point) {
1798 if (type == TYPE_A) {
1805 if ((c=getc(fout)) == EOF) {
1806 perror_reply(550, name);
1813 * We must do this seek to "current" position
1814 * because we are changing from reading to
1817 if (fseeko(fout, 0, SEEK_CUR) < 0) {
1818 perror_reply(550, name);
1821 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1822 perror_reply(550, name);
1826 din = dataconn(name, -1, "r");
1829 if (receive_data(din, fout) == 0) {
1831 reply(226, "Transfer complete (unique file name:%s).",
1834 reply(226, "Transfer complete.");
1840 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1844 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1849 getdatasock(char *mode)
1851 int on = 1, s, t, tries;
1854 return (fdopen(data, mode));
1856 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1859 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1860 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1861 /* anchor socket to avoid multi-homing problems */
1862 data_source = ctrl_addr;
1863 data_source.su_port = htons(dataport);
1865 for (tries = 1; ; tries++) {
1867 * We should loop here since it's possible that
1868 * another ftpd instance has passed this point and is
1869 * trying to open a data connection in active mode now.
1870 * Until the other connection is opened, we'll be getting
1871 * EADDRINUSE because no SOCK_STREAM sockets in the system
1872 * can share both local and remote addresses, localIP:20
1873 * and *:* in this case.
1875 if (bind(s, (struct sockaddr *)&data_source,
1876 data_source.su_len) >= 0)
1878 if (errno != EADDRINUSE || tries > 10)
1882 (void) seteuid(pw->pw_uid);
1884 if (data_source.su_family == AF_INET)
1886 on = IPTOS_THROUGHPUT;
1887 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1888 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1893 * Turn off push flag to keep sender TCP from sending short packets
1894 * at the boundaries of each write().
1897 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1898 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1900 return (fdopen(s, mode));
1902 /* Return the real value of errno (close may change it) */
1904 (void) seteuid(pw->pw_uid);
1911 dataconn(char *name, off_t size, char *mode)
1915 int retry = 0, tos, conerrno;
1920 (void) snprintf(sizebuf, sizeof(sizebuf),
1921 " (%jd bytes)", (intmax_t)size);
1925 union sockunion from;
1926 socklen_t fromlen = ctrl_addr.su_len;
1928 struct timeval timeout;
1932 FD_SET(pdata, &set);
1934 timeout.tv_usec = 0;
1935 timeout.tv_sec = 120;
1938 * Granted a socket is in the blocking I/O mode,
1939 * accept() will block after a successful select()
1940 * if the selected connection dies in between.
1941 * Therefore set the non-blocking I/O flag here.
1943 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1944 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1946 if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
1947 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1949 (void) close(pdata);
1952 * Unset the inherited non-blocking I/O flag
1953 * on the child socket so stdio can work on it.
1955 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1956 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1959 if (from.su_family == AF_INET)
1961 tos = IPTOS_THROUGHPUT;
1962 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1963 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1966 reply(150, "Opening %s mode data connection for '%s'%s.",
1967 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1968 return (fdopen(pdata, mode));
1970 reply(425, "Can't open data connection.");
1971 (void) close(pdata);
1976 reply(125, "Using existing data connection for '%s'%s.",
1979 return (fdopen(data, mode));
1982 data_dest = his_addr;
1985 file = getdatasock(mode);
1987 char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
1989 if (getnameinfo((struct sockaddr *)&data_source,
1991 hostbuf, sizeof(hostbuf) - 1,
1992 portbuf, sizeof(portbuf) - 1,
1993 NI_NUMERICHOST|NI_NUMERICSERV))
1994 *hostbuf = *portbuf = 0;
1995 hostbuf[sizeof(hostbuf) - 1] = 0;
1996 portbuf[sizeof(portbuf) - 1] = 0;
1997 reply(425, "Can't create data socket (%s,%s): %s.",
1998 hostbuf, portbuf, strerror(errno));
2001 data = fileno(file);
2003 if (connect(data, (struct sockaddr *)&data_dest,
2004 data_dest.su_len) == 0)
2007 (void) fclose(file);
2009 if (conerrno == EADDRINUSE) {
2015 } while (retry <= swaitmax);
2016 if (conerrno != 0) {
2017 reply(425, "Can't build data connection: %s.",
2018 strerror(conerrno));
2021 reply(150, "Opening %s mode data connection for '%s'%s.",
2022 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2027 * A helper macro to avoid code duplication
2028 * in send_data() and receive_data().
2030 * XXX We have to block SIGURG during putc() because BSD stdio
2031 * is unable to restart interrupted write operations and hence
2032 * the entire buffer contents will be lost as soon as a write()
2033 * call indicates EINTR to stdio.
2035 #define FTPD_PUTC(ch, file, label) \
2041 ret = putc((ch), (file)); \
2043 CHECKOOB(return (-1)) \
2044 else if (ferror(file)) \
2047 } while (ret == EOF); \
2051 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
2052 * encapsulation of the data subject to Mode, Structure, and Type.
2054 * NB: Form isn't handled.
2057 send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2059 int c, cp, filefd, netfd;
2070 CHECKOOB(return (-1))
2071 else if (c == EOF && ferror(instr))
2074 if (ferror(instr)) { /* resume after OOB */
2078 if (feof(instr)) /* EOF */
2080 syslog(LOG_ERR, "Internal: impossible condition"
2081 " on file after getc()");
2084 if (c == '\n' && cp != '\r') {
2085 FTPD_PUTC('\r', outstr, data_err);
2088 FTPD_PUTC(c, outstr, data_err);
2092 #ifdef notyet /* BSD stdio isn't ready for that */
2093 while (fflush(outstr) == EOF) {
2094 CHECKOOB(return (-1))
2102 if (fflush(outstr) == EOF)
2105 reply(226, "Transfer complete.");
2111 * isreg is only set if we are not doing restart and we
2112 * are sending a regular file
2114 netfd = fileno(outstr);
2115 filefd = fileno(instr);
2118 char *msg = "Transfer complete.";
2124 while (filesize > 0) {
2125 err = sendfile(filefd, netfd, offset, 0,
2128 * Calculate byte_count before OOB processing.
2129 * It can be used in myoob() later.
2134 CHECKOOB(return (-1))
2135 else if (err == -1) {
2136 if (errno != EINTR &&
2137 cnt == 0 && offset == 0)
2141 if (err == -1) /* resume after OOB */
2144 * We hit the EOF prematurely.
2145 * Perhaps the file was externally truncated.
2148 msg = "Transfer finished due to "
2149 "premature end of file.";
2154 reply(226, "%s", msg);
2159 if ((buf = malloc(blksize)) == NULL) {
2161 reply(451, "Ran out of memory.");
2169 cnt = read(filefd, buf, blksize);
2170 CHECKOOB(free(buf); return (-1))
2175 if (cnt < 0) /* resume after OOB */
2177 if (cnt == 0) /* EOF */
2179 for (len = cnt, bp = buf; len > 0;) {
2180 cnt = write(netfd, bp, len);
2181 CHECKOOB(free(buf); return (-1))
2195 reply(226, "Transfer complete.");
2199 reply(550, "Unimplemented TYPE %d in send_data.", type);
2205 perror_reply(426, "Data connection");
2210 perror_reply(551, "Error on input file");
2215 * Transfer data from peer to "outstr" using the appropriate encapulation of
2216 * the data subject to Mode, Structure, and Type.
2218 * N.B.: Form isn't handled.
2221 receive_data(FILE *instr, FILE *outstr)
2237 cnt = read(fileno(instr), buf, sizeof(buf));
2238 CHECKOOB(return (-1))
2241 if (cnt < 0) /* resume after OOB */
2243 if (cnt == 0) /* EOF */
2245 for (len = cnt, bp = buf; len > 0;) {
2246 cnt = write(fileno(outstr), bp, len);
2247 CHECKOOB(return (-1))
2262 reply(553, "TYPE E not implemented.");
2269 CHECKOOB(return (-1))
2270 else if (c == EOF && ferror(instr))
2272 if (c == EOF && ferror(instr)) { /* resume after OOB */
2279 FTPD_PUTC('\r', outstr, file_err);
2289 /* Check for EOF here in order not to lose last \r. */
2291 if (feof(instr)) /* EOF */
2293 syslog(LOG_ERR, "Internal: impossible condition"
2294 " on data stream after getc()");
2299 FTPD_PUTC(c, outstr, file_err);
2302 #ifdef notyet /* BSD stdio isn't ready for that */
2303 while (fflush(outstr) == EOF) {
2304 CHECKOOB(return (-1))
2312 if (fflush(outstr) == EOF)
2317 "WARNING! %d bare linefeeds received in ASCII mode.",
2319 (void)printf(" File may not have transferred correctly.\r\n");
2324 reply(550, "Unimplemented TYPE %d in receive_data.", type);
2330 perror_reply(426, "Data connection");
2335 perror_reply(452, "Error writing to file");
2340 statfilecmd(char *filename)
2345 char line[LINE_MAX];
2348 code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2349 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2350 fin = ftpd_popen(line, "r");
2352 perror_reply(551, filename);
2355 lreply(code, "Status of %s:", filename);
2357 while ((c = getc(fin)) != EOF) {
2359 if (ferror(stdout)){
2360 perror_reply(421, "Control connection");
2361 (void) ftpd_pclose(fin);
2366 perror_reply(551, filename);
2367 (void) ftpd_pclose(fin);
2370 (void) putc('\r', stdout);
2373 * RFC 959 says neutral text should be prepended before
2374 * a leading 3-digit number followed by whitespace, but
2375 * many ftp clients can be confused by any leading digits,
2376 * as a matter of fact.
2378 if (atstart && isdigit(c))
2379 (void) putc(' ', stdout);
2380 (void) putc(c, stdout);
2381 atstart = (c == '\n');
2383 (void) ftpd_pclose(fin);
2384 reply(code, "End of status.");
2390 union sockunion *su;
2392 char hname[NI_MAXHOST];
2396 lreply(211, "%s FTP server status:", hostname);
2397 printf(" %s\r\n", version);
2399 lreply(211, "FTP server status:");
2400 printf(" Connected to %s", remotehost);
2401 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2402 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2403 hname[sizeof(hname) - 1] = 0;
2404 if (strcmp(hname, remotehost) != 0)
2405 printf(" (%s)", hname);
2410 printf(" Logged in anonymously\r\n");
2412 printf(" Logged in as %s\r\n", pw->pw_name);
2413 } else if (askpasswd)
2414 printf(" Waiting for password\r\n");
2416 printf(" Waiting for user name\r\n");
2417 printf(" TYPE: %s", typenames[type]);
2418 if (type == TYPE_A || type == TYPE_E)
2419 printf(", FORM: %s", formnames[form]);
2422 printf(" %d", CHAR_BIT);
2424 printf(" %d", bytesize); /* need definition! */
2426 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2427 strunames[stru], modenames[mode]);
2429 printf(" Data connection open\r\n");
2430 else if (pdata != -1) {
2434 } else if (usedefault == 0) {
2438 #define UC(b) (((int) b) & 0xff)
2440 printf(" EPSV only mode (EPSV ALL)\r\n");
2445 if (su->su_family == AF_INET) {
2446 a = (u_char *) &su->su_sin.sin_addr;
2447 p = (u_char *) &su->su_sin.sin_port;
2448 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2449 ispassive ? "PASV" : "PORT",
2450 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2451 UC(p[0]), UC(p[1]));
2458 switch (su->su_family) {
2460 a = (u_char *) &su->su_sin.sin_addr;
2461 p = (u_char *) &su->su_sin.sin_port;
2462 alen = sizeof(su->su_sin.sin_addr);
2466 a = (u_char *) &su->su_sin6.sin6_addr;
2467 p = (u_char *) &su->su_sin6.sin6_port;
2468 alen = sizeof(su->su_sin6.sin6_addr);
2476 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2478 for (i = 0; i < alen; i++)
2479 printf("%d,", UC(a[i]));
2480 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2489 switch (su->su_family) {
2501 union sockunion tmp;
2504 if (tmp.su_family == AF_INET6)
2505 tmp.su_sin6.sin6_scope_id = 0;
2506 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2507 hname, sizeof(hname) - 1, NULL, 0,
2509 hname[sizeof(hname) - 1] = 0;
2510 printf(" %s |%d|%s|%d|\r\n",
2511 ispassive ? "EPSV" : "EPRT",
2512 af, hname, htons(tmp.su_port));
2518 printf(" No data connection\r\n");
2519 reply(211, "End of status.");
2526 reply(451, "Error in server: %s", s);
2527 reply(221, "Closing connection due to server error.");
2533 reply(int n, const char *fmt, ...)
2537 (void)printf("%d ", n);
2539 (void)vprintf(fmt, ap);
2541 (void)printf("\r\n");
2542 (void)fflush(stdout);
2544 syslog(LOG_DEBUG, "<--- %d ", n);
2546 vsyslog(LOG_DEBUG, fmt, ap);
2552 lreply(int n, const char *fmt, ...)
2556 (void)printf("%d- ", n);
2558 (void)vprintf(fmt, ap);
2560 (void)printf("\r\n");
2561 (void)fflush(stdout);
2563 syslog(LOG_DEBUG, "<--- %d- ", n);
2565 vsyslog(LOG_DEBUG, fmt, ap);
2574 reply(250, "%s command successful.", s);
2581 reply(502, "%s command not implemented.", s);
2590 if ((cp = strchr(cbuf,'\n')))
2592 reply(500, "%s: command not understood.", cbuf);
2600 LOGCMD("delete", name);
2601 if (lstat(name, &st) < 0) {
2602 perror_reply(550, name);
2605 if (S_ISDIR(st.st_mode)) {
2606 if (rmdir(name) < 0) {
2607 perror_reply(550, name);
2612 if (guest && noguestmod) {
2613 reply(550, "Operation not permitted.");
2616 if (unlink(name) < 0) {
2617 perror_reply(550, name);
2628 if (chdir(path) < 0)
2629 perror_reply(550, path);
2639 LOGCMD("mkdir", name);
2640 if (guest && noguestmkd)
2641 reply(550, "Operation not permitted.");
2642 else if (mkdir(name, 0777) < 0)
2643 perror_reply(550, name);
2645 if ((s = doublequote(name)) == NULL)
2646 fatalerror("Ran out of memory.");
2647 reply(257, "\"%s\" directory created.", s);
2653 removedir(char *name)
2656 LOGCMD("rmdir", name);
2657 if (rmdir(name) < 0)
2658 perror_reply(550, name);
2666 char *s, path[MAXPATHLEN + 1];
2668 if (getcwd(path, sizeof(path)) == NULL)
2669 perror_reply(550, "Get current directory");
2671 if ((s = doublequote(path)) == NULL)
2672 fatalerror("Ran out of memory.");
2673 reply(257, "\"%s\" is current directory.", s);
2679 renamefrom(char *name)
2683 if (guest && noguestmod) {
2684 reply(550, "Operation not permitted.");
2687 if (lstat(name, &st) < 0) {
2688 perror_reply(550, name);
2691 reply(350, "File exists, ready for destination name.");
2696 renamecmd(char *from, char *to)
2700 LOGCMD2("rename", from, to);
2702 if (guest && (stat(to, &st) == 0)) {
2703 reply(550, "%s: permission denied.", to);
2707 if (rename(from, to) < 0)
2708 perror_reply(550, "rename");
2714 dolog(struct sockaddr *who)
2716 char who_name[NI_MAXHOST];
2718 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2719 remotehost[sizeof(remotehost) - 1] = 0;
2720 if (getnameinfo(who, who->sa_len,
2721 who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
2723 who_name[sizeof(who_name) - 1] = 0;
2726 #ifdef VIRTUAL_HOSTING
2727 if (thishost != firsthost)
2728 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2729 remotehost, hostname);
2732 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2734 setproctitle("%s", proctitle);
2735 #endif /* SETPROCTITLE */
2738 #ifdef VIRTUAL_HOSTING
2739 if (thishost != firsthost)
2740 syslog(LOG_INFO, "connection from %s (%s) to %s",
2741 remotehost, who_name, hostname);
2744 syslog(LOG_INFO, "connection from %s (%s)",
2745 remotehost, who_name);
2750 * Record logout in wtmp file
2751 * and exit with supplied status.
2754 dologout(int status)
2757 if (logged_in && dowtmp) {
2759 ftpd_logwtmp(wtmpid, NULL, NULL);
2761 /* beware of flushing buffers after a SIGPIPE */
2779 syslog(LOG_ERR, "Internal: maskurg() while no transfer");
2784 sigaddset(&sset, SIGURG);
2785 sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
2795 syslog(LOG_ERR, "Internal: flagxfer(1): "
2796 "transfer already under way");
2802 syslog(LOG_ERR, "Internal: flagxfer(0): "
2803 "no active transfer");
2810 * Returns 0 if OK to resume or -1 if abort requested.
2819 syslog(LOG_ERR, "Internal: myoob() while no transfer");
2823 ret = getline(cp, 7, stdin);
2825 reply(221, "You could at least say goodbye.");
2827 } else if (ret == -2) {
2828 /* Ignore truncated command. */
2832 if (strcmp(cp, "ABOR\r\n") == 0) {
2834 reply(426, "Transfer aborted. Data connection closed.");
2835 reply(226, "Abort successful.");
2838 if (strcmp(cp, "STAT\r\n") == 0) {
2840 if (file_size != -1)
2841 reply(213, "Status: %jd of %jd bytes transferred.",
2842 (intmax_t)byte_count, (intmax_t)file_size);
2844 reply(213, "Status: %jd bytes transferred.",
2845 (intmax_t)byte_count);
2851 * Note: a response of 425 is not mentioned as a possible response to
2852 * the PASV command in RFC959. However, it has been blessed as
2853 * a legitimate response by Jon Postel in a telephone conversation
2854 * with Rick Adams on 25 Jan 89.
2863 if (pdata >= 0) /* close old port if one set */
2866 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2868 perror_reply(425, "Can't open passive connection");
2872 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2873 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2878 if (ctrl_addr.su_family == AF_INET) {
2879 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2880 : IP_PORTRANGE_DEFAULT;
2882 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2883 &on, sizeof(on)) < 0)
2887 #ifdef IPV6_PORTRANGE
2888 if (ctrl_addr.su_family == AF_INET6) {
2889 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2890 : IPV6_PORTRANGE_DEFAULT;
2892 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2893 &on, sizeof(on)) < 0)
2898 pasv_addr = ctrl_addr;
2899 pasv_addr.su_port = 0;
2900 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2903 (void) seteuid(pw->pw_uid);
2905 len = sizeof(pasv_addr);
2906 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2908 if (listen(pdata, 1) < 0)
2910 if (pasv_addr.su_family == AF_INET)
2911 a = (char *) &pasv_addr.su_sin.sin_addr;
2912 else if (pasv_addr.su_family == AF_INET6 &&
2913 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2914 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2918 p = (char *) &pasv_addr.su_port;
2920 #define UC(b) (((int) b) & 0xff)
2922 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2923 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2927 (void) seteuid(pw->pw_uid);
2928 (void) close(pdata);
2930 perror_reply(425, "Can't open passive connection");
2935 * Long Passive defined in RFC 1639.
2936 * 228 Entering Long Passive Mode
2937 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2941 long_passive(char *cmd, int pf)
2947 if (pdata >= 0) /* close old port if one set */
2950 if (pf != PF_UNSPEC) {
2951 if (ctrl_addr.su_family != pf) {
2952 switch (ctrl_addr.su_family) {
2965 * only EPRT/EPSV ready clients will understand this
2967 if (strcmp(cmd, "EPSV") == 0 && pf) {
2968 reply(522, "Network protocol mismatch, "
2971 reply(501, "Network protocol mismatch."); /*XXX*/
2977 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2979 perror_reply(425, "Can't open passive connection");
2983 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2984 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2988 pasv_addr = ctrl_addr;
2989 pasv_addr.su_port = 0;
2990 len = pasv_addr.su_len;
2993 if (ctrl_addr.su_family == AF_INET) {
2994 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2995 : IP_PORTRANGE_DEFAULT;
2997 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2998 &on, sizeof(on)) < 0)
3002 #ifdef IPV6_PORTRANGE
3003 if (ctrl_addr.su_family == AF_INET6) {
3004 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
3005 : IPV6_PORTRANGE_DEFAULT;
3007 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
3008 &on, sizeof(on)) < 0)
3013 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
3016 (void) seteuid(pw->pw_uid);
3018 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
3020 if (listen(pdata, 1) < 0)
3023 #define UC(b) (((int) b) & 0xff)
3025 if (strcmp(cmd, "LPSV") == 0) {
3026 p = (char *)&pasv_addr.su_port;
3027 switch (pasv_addr.su_family) {
3029 a = (char *) &pasv_addr.su_sin.sin_addr;
3032 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3033 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3034 2, UC(p[0]), UC(p[1]));
3037 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
3038 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
3041 a = (char *) &pasv_addr.su_sin6.sin6_addr;
3043 "Entering Long Passive Mode "
3044 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3045 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3046 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3047 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3048 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3049 2, UC(p[0]), UC(p[1]));
3052 } else if (strcmp(cmd, "EPSV") == 0) {
3053 switch (pasv_addr.su_family) {
3056 reply(229, "Entering Extended Passive Mode (|||%d|)",
3057 ntohs(pasv_addr.su_port));
3061 /* more proper error code? */
3065 (void) seteuid(pw->pw_uid);
3066 (void) close(pdata);
3068 perror_reply(425, "Can't open passive connection");
3073 * Generate unique name for file with basename "local"
3074 * and open the file in order to avoid possible races.
3075 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3076 * Return descriptor to the file, set "name" to its name.
3078 * Generates failure reply on error.
3081 guniquefd(char *local, char **name)
3083 static char new[MAXPATHLEN];
3089 cp = strrchr(local, '/');
3092 if (stat(cp ? local : ".", &st) < 0) {
3093 perror_reply(553, cp ? local : ".");
3098 * Let not overwrite dirname with counter suffix.
3100 * In this extreme case dot won't be put in front of suffix.
3102 if (strlen(local) > sizeof(new) - 4) {
3103 reply(553, "Pathname too long.");
3108 /* -4 is for the .nn<null> we put on the end below */
3109 (void) snprintf(new, sizeof(new) - 4, "%s", local);
3110 cp = new + strlen(new);
3112 * Don't generate dotfile unless requested explicitly.
3113 * This covers the case when basename gets truncated off
3116 if (cp > new && cp[-1] != '/')
3118 for (count = 0; count < 100; count++) {
3119 /* At count 0 try unmodified name */
3121 (void)sprintf(cp, "%d", count);
3122 if ((fd = open(count ? new : local,
3123 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3124 *name = count ? new : local;
3127 if (errno != EEXIST) {
3128 perror_reply(553, count ? new : local);
3132 reply(452, "Unique file name cannot be created.");
3137 * Format and send reply containing system error number.
3140 perror_reply(int code, char *string)
3143 reply(code, "%s: %s.", string, strerror(errno));
3146 static char *onefile[] = {
3152 send_file_list(char *whichf)
3158 char **dirlist, *dirname;
3163 if (strpbrk(whichf, "~{[*?") != NULL) {
3164 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3166 memset(&gl, 0, sizeof(gl));
3167 gl.gl_matchc = MAXGLOBARGS;
3168 flags |= GLOB_LIMIT;
3170 if (glob(whichf, flags, 0, &gl)) {
3171 reply(550, "No matching files found.");
3173 } else if (gl.gl_pathc == 0) {
3175 perror_reply(550, whichf);
3178 dirlist = gl.gl_pathv;
3180 onefile[0] = whichf;
3185 while ((dirname = *dirlist++)) {
3186 if (stat(dirname, &st) < 0) {
3188 * If user typed "ls -l", etc, and the client
3189 * used NLST, do what the user meant.
3191 if (dirname[0] == '-' && *dirlist == NULL &&
3193 retrieve(_PATH_LS " %s", dirname);
3195 perror_reply(550, whichf);
3199 if (S_ISREG(st.st_mode)) {
3201 dout = dataconn("file list", -1, "w");
3207 fprintf(dout, "%s%s\n", dirname,
3208 type == TYPE_A ? "\r" : "");
3212 byte_count += strlen(dirname) +
3213 (type == TYPE_A ? 2 : 1);
3214 CHECKOOB(goto abrt);
3216 } else if (!S_ISDIR(st.st_mode))
3219 if ((dirp = opendir(dirname)) == NULL)
3222 while ((dir = readdir(dirp)) != NULL) {
3223 char nbuf[MAXPATHLEN];
3225 CHECKOOB(goto abrt);
3227 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
3229 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3233 snprintf(nbuf, sizeof(nbuf),
3234 "%s/%s", dirname, dir->d_name);
3237 * We have to do a stat to insure it's
3238 * not a directory or special file.
3240 if (simple || (stat(nbuf, &st) == 0 &&
3241 S_ISREG(st.st_mode))) {
3243 dout = dataconn("file list", -1, "w");
3249 if (nbuf[0] == '.' && nbuf[1] == '/')
3250 fprintf(dout, "%s%s\n", &nbuf[2],
3251 type == TYPE_A ? "\r" : "");
3253 fprintf(dout, "%s%s\n", nbuf,
3254 type == TYPE_A ? "\r" : "");
3258 byte_count += strlen(nbuf) +
3259 (type == TYPE_A ? 2 : 1);
3260 CHECKOOB(goto abrt);
3263 (void) closedir(dirp);
3268 reply(550, "No files found.");
3269 else if (ferror(dout))
3270 data_err: perror_reply(550, "Data connection");
3272 reply(226, "Transfer complete.");
3277 (void) fclose(dout);
3282 (void) closedir(dirp);
3290 reapchild(int signo)
3292 while (waitpid(-1, NULL, WNOHANG) > 0);
3295 #ifdef OLD_SETPROCTITLE
3297 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.)
3298 * Warning, since this is usually started from inetd.conf, it often doesn't
3299 * have much of an environment or arglist to overwrite.
3302 setproctitle(const char *fmt, ...)
3310 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
3312 /* make ps print our process name */
3317 if (i > LastArgv - p - 2) {
3318 i = LastArgv - p - 2;
3323 if (ch != '\n' && ch != '\r')
3325 while (p < LastArgv)
3328 #endif /* OLD_SETPROCTITLE */
3331 appendf(char **strp, char *fmt, ...)
3337 vasprintf(&p, fmt, ap);
3340 fatalerror("Ran out of memory.");
3345 asprintf(strp, "%s%s", ostr, p);
3347 fatalerror("Ran out of memory.");
3353 logcmd(char *cmd, char *file1, char *file2, off_t cnt)
3356 char wd[MAXPATHLEN + 1];
3361 if (getcwd(wd, sizeof(wd) - 1) == NULL)
3362 strcpy(wd, strerror(errno));
3364 appendf(&msg, "%s", cmd);
3366 appendf(&msg, " %s", file1);
3368 appendf(&msg, " %s", file2);
3370 appendf(&msg, " = %jd bytes", (intmax_t)cnt);
3371 appendf(&msg, " (wd: %s", wd);
3372 if (guest || dochroot)
3373 appendf(&msg, "; chrooted");
3375 syslog(LOG_INFO, "%s", msg);
3380 logxfer(char *name, off_t size, time_t start)
3382 char buf[MAXPATHLEN + 1024];
3383 char path[MAXPATHLEN + 1];
3388 if (realpath(name, path) == NULL) {
3389 syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
3392 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n",
3393 ctime(&now)+4, ident, remotehost,
3394 path, (intmax_t)size,
3395 (long)(now - start + (now == start)));
3396 write(statfd, buf, strlen(buf));
3401 doublequote(char *s)
3406 for (p = s, n = 0; *p; p++)
3410 if ((s2 = malloc(p - s + n + 1)) == NULL)
3413 for (p = s2; *s; s++, p++) {
3414 if ((*p = *s) == '"')
3422 /* setup server socket for specified address family */
3423 /* if af is PF_UNSPEC more than one socket may be returned */
3424 /* the returned list is dynamically allocated, so caller needs to free it */
3426 socksetup(int af, char *bindname, const char *bindport)
3428 struct addrinfo hints, *res, *r;
3429 int error, maxs, *s, *socks;
3432 memset(&hints, 0, sizeof(hints));
3433 hints.ai_flags = AI_PASSIVE;
3434 hints.ai_family = af;
3435 hints.ai_socktype = SOCK_STREAM;
3436 error = getaddrinfo(bindname, bindport, &hints, &res);
3438 syslog(LOG_ERR, "%s", gai_strerror(error));
3439 if (error == EAI_SYSTEM)
3440 syslog(LOG_ERR, "%s", strerror(errno));
3444 /* Count max number of sockets we may open */
3445 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3447 socks = malloc((maxs + 1) * sizeof(int));
3450 syslog(LOG_ERR, "couldn't allocate memory for sockets");
3454 *socks = 0; /* num of sockets counter at start of array */
3456 for (r = res; r; r = r->ai_next) {
3457 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3459 syslog(LOG_DEBUG, "control socket: %m");
3462 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3463 &on, sizeof(on)) < 0)
3465 "control setsockopt (SO_REUSEADDR): %m");
3466 if (r->ai_family == AF_INET6) {
3467 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3468 &on, sizeof(on)) < 0)
3470 "control setsockopt (IPV6_V6ONLY): %m");
3472 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3473 syslog(LOG_DEBUG, "control bind: %m");
3485 syslog(LOG_ERR, "control socket: Couldn't bind to any socket");