2 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 static char copyright[] =
33 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
34 The Regents of the University of California. All rights reserved.\n";
40 static char sccsid[] = "@(#)ftpd.c 8.4 (Berkeley) 4/16/94";
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
50 #include <sys/param.h>
51 #include <sys/ioctl.h>
53 #include <sys/socket.h>
58 #include <netinet/in.h>
59 #include <netinet/in_systm.h>
60 #include <netinet/ip.h>
61 #include <netinet/tcp.h>
65 #include <arpa/inet.h>
66 #include <arpa/telnet.h>
89 #include <login_cap.h>
93 #include <security/pam_appl.h>
96 #include "blacklist_client.h"
97 #include "pathnames.h"
102 static char version[] = "Version 6.00LS";
105 union sockunion ctrl_addr;
106 union sockunion data_source;
107 union sockunion data_dest;
108 union sockunion his_addr;
109 union sockunion pasv_addr;
114 int hostinfo = 1; /* print host-specific info in messages */
119 int timeout = 900; /* timeout after 15 minutes of inactivity */
120 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
122 int restricted_data_ports = 1;
123 int paranoid = 1; /* be extra careful about security */
124 int anon_only = 0; /* Only anonymous ftp allowed */
125 int assumeutf8 = 0; /* Assume that server file names are in UTF-8 */
134 int stru; /* avoid C keyword */
136 int usedefault = 1; /* for data transfers */
137 int pdata = -1; /* for passive mode */
138 int readonly = 0; /* Server is in readonly mode. */
139 int noepsv = 0; /* EPSV command is disabled. */
140 int noretr = 0; /* RETR command is disabled. */
141 int noguestretr = 0; /* RETR command is disabled for anon users. */
142 int noguestmkd = 0; /* MKD command is disabled for anon users. */
143 int noguestmod = 1; /* anon users may not modify existing files. */
144 int use_blacklist = 0;
148 #if !defined(CMASK) || CMASK == 0
152 int defumask = CMASK; /* default umask value */
157 #ifdef VIRTUAL_HOSTING
160 static struct ftphost {
161 struct ftphost *next;
162 struct addrinfo *hostinfo;
168 } *thishost, *firsthost;
171 char remotehost[NI_MAXHOST];
174 static char wtmpid[20];
177 static int auth_pam(struct passwd**, const char*);
178 pam_handle_t *pamh = NULL;
181 static struct opie opiedata;
182 static char opieprompt[OPIE_CHALLENGE_MAX+1];
185 char *pid_file = NULL; /* means default location to pidfile(3) */
188 * Limit number of pathnames that glob can return.
189 * A limit of 0 indicates the number of pathnames is unlimited.
191 #define MAXGLOBARGS 16384
195 * Timeout intervals for retrying connections
196 * to hosts that don't accept PORT cmds. This
197 * is a kludge, but given the problems with TCP...
199 #define SWAITMAX 90 /* wait at most 90 seconds */
200 #define SWAITINT 5 /* interval between retries */
202 int swaitmax = SWAITMAX;
203 int swaitint = SWAITINT;
206 #ifdef OLD_SETPROCTITLE
207 char **Argv = NULL; /* pointer to argument vector */
208 char *LastArgv = NULL; /* end of argv */
209 #endif /* OLD_SETPROCTITLE */
210 char proctitle[LINE_MAX]; /* initial part of title */
211 #endif /* SETPROCTITLE */
213 #define LOGCMD(cmd, file) logcmd((cmd), (file), NULL, -1)
214 #define LOGCMD2(cmd, file1, file2) logcmd((cmd), (file1), (file2), -1)
215 #define LOGBYTES(cmd, file, cnt) logcmd((cmd), (file), NULL, (cnt))
217 static volatile sig_atomic_t recvurg;
218 static int transflag; /* NB: for debugging only */
220 #define STARTXFER flagxfer(1)
221 #define ENDXFER flagxfer(0)
223 #define START_UNSAFE maskurg(1)
224 #define END_UNSAFE maskurg(0)
226 /* It's OK to put an `else' clause after this macro. */
227 #define CHECKOOB(action) \
236 #ifdef VIRTUAL_HOSTING
237 static void inithosts(int);
238 static void selecthost(union sockunion *);
240 static void ack(char *);
241 static void sigurg(int);
242 static void maskurg(int);
243 static void flagxfer(int);
244 static int myoob(void);
245 static int checkuser(char *, char *, int, char **, int *);
246 static FILE *dataconn(char *, off_t, char *);
247 static void dolog(struct sockaddr *);
248 static void end_login(void);
249 static FILE *getdatasock(char *);
250 static int guniquefd(char *, char **);
251 static void lostconn(int);
252 static void sigquit(int);
253 static int receive_data(FILE *, FILE *);
254 static int send_data(FILE *, FILE *, size_t, off_t, int);
255 static struct passwd *
257 static char *sgetsave(char *);
258 static void reapchild(int);
259 static void appendf(char **, char *, ...) __printflike(2, 3);
260 static void logcmd(char *, char *, char *, off_t);
261 static void logxfer(char *, off_t, time_t);
262 static char *doublequote(char *);
263 static int *socksetup(int, char *, const char *);
266 main(int argc, char *argv[], char **envp)
269 int ch, on = 1, tos, s = STDIN_FILENO;
270 char *cp, line[LINE_MAX];
272 char *bindname = NULL;
273 const char *bindport = "ftp";
274 int family = AF_UNSPEC;
277 tzset(); /* in case no timezone database in ~ftp */
278 sigemptyset(&sa.sa_mask);
279 sa.sa_flags = SA_RESTART;
281 #ifdef OLD_SETPROCTITLE
283 * Save start and extent of argv for setproctitle.
288 LastArgv = envp[-1] + strlen(envp[-1]);
289 #endif /* OLD_SETPROCTITLE */
292 * Prevent diagnostic messages from appearing on stderr.
293 * We run as a daemon or from inetd; in both cases, there's
294 * more reason in logging to syslog.
296 (void) freopen(_PATH_DEVNULL, "w", stderr);
300 * LOG_NDELAY sets up the logging connection immediately,
301 * necessary for anonymous ftp's that chroot and can't do it later.
303 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
305 while ((ch = getopt(argc, argv,
306 "468a:ABdDEhlmMoOp:P:rRSt:T:u:UvW")) != -1) {
309 family = (family == AF_INET6) ? AF_UNSPEC : AF_INET;
313 family = (family == AF_INET) ? AF_UNSPEC : AF_INET6;
332 syslog(LOG_WARNING, "not compiled with USE_BLACKLIST support");
353 logging++; /* > 1 == extra logging */
393 timeout = atoi(optarg);
394 if (maxtimeout < timeout)
395 maxtimeout = timeout;
399 maxtimeout = atoi(optarg);
400 if (timeout > maxtimeout)
401 timeout = maxtimeout;
408 val = strtol(optarg, &optarg, 8);
409 if (*optarg != '\0' || val < 0)
410 syslog(LOG_WARNING, "bad value for -u");
416 restricted_data_ports = 0;
428 syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
434 int *ctl_sock, fd, maxfd = -1, nfds, i;
435 fd_set defreadfds, readfds;
439 if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
440 if (errno == EEXIST) {
441 syslog(LOG_ERR, "%s already running, pid %d",
442 getprogname(), (int)pid);
445 syslog(LOG_WARNING, "pidfile_open: %m");
449 * Detach from parent.
451 if (daemon(1, 1) < 0) {
452 syslog(LOG_ERR, "failed to become a daemon");
456 if (pfh != NULL && pidfile_write(pfh) == -1)
457 syslog(LOG_WARNING, "pidfile_write: %m");
459 sa.sa_handler = reapchild;
460 (void)sigaction(SIGCHLD, &sa, NULL);
462 #ifdef VIRTUAL_HOSTING
467 * Open a socket, bind it to the FTP port, and start
470 ctl_sock = socksetup(family, bindname, bindport);
471 if (ctl_sock == NULL)
474 FD_ZERO(&defreadfds);
475 for (i = 1; i <= *ctl_sock; i++) {
476 FD_SET(ctl_sock[i], &defreadfds);
477 if (listen(ctl_sock[i], 32) < 0) {
478 syslog(LOG_ERR, "control listen: %m");
481 if (maxfd < ctl_sock[i])
486 * Loop forever accepting connection requests and forking off
487 * children to handle them.
490 FD_COPY(&defreadfds, &readfds);
491 nfds = select(maxfd + 1, &readfds, NULL, NULL, 0);
493 if (nfds < 0 && errno != EINTR)
494 syslog(LOG_WARNING, "select: %m");
499 for (i = 1; i <= *ctl_sock; i++)
500 if (FD_ISSET(ctl_sock[i], &readfds)) {
501 addrlen = sizeof(his_addr);
502 fd = accept(ctl_sock[i],
503 (struct sockaddr *)&his_addr,
510 switch (pid = fork()) {
514 (void) dup2(fd, STDOUT_FILENO);
516 for (i = 1; i <= *ctl_sock; i++)
522 syslog(LOG_WARNING, "fork: %m");
530 addrlen = sizeof(his_addr);
531 if (getpeername(s, (struct sockaddr *)&his_addr, &addrlen) < 0) {
532 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
536 #ifdef VIRTUAL_HOSTING
537 if (his_addr.su_family == AF_INET6 &&
538 IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))
541 family = his_addr.su_family;
547 sa.sa_handler = SIG_DFL;
548 (void)sigaction(SIGCHLD, &sa, NULL);
550 sa.sa_handler = sigurg;
551 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
552 (void)sigaction(SIGURG, &sa, NULL);
554 sigfillset(&sa.sa_mask); /* block all signals in handler */
555 sa.sa_flags = SA_RESTART;
556 sa.sa_handler = sigquit;
557 (void)sigaction(SIGHUP, &sa, NULL);
558 (void)sigaction(SIGINT, &sa, NULL);
559 (void)sigaction(SIGQUIT, &sa, NULL);
560 (void)sigaction(SIGTERM, &sa, NULL);
562 sa.sa_handler = lostconn;
563 (void)sigaction(SIGPIPE, &sa, NULL);
565 addrlen = sizeof(ctrl_addr);
566 if (getsockname(s, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
567 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
570 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
571 #ifdef VIRTUAL_HOSTING
572 /* select our identity from virtual host table */
573 selecthost(&ctrl_addr);
576 if (ctrl_addr.su_family == AF_INET)
578 tos = IPTOS_LOWDELAY;
579 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
580 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
584 * Disable Nagle on the control channel so that we don't have to wait
585 * for peer's ACK before issuing our next reply.
587 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
588 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
590 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
592 (void)snprintf(wtmpid, sizeof(wtmpid), "%xftpd", getpid());
594 /* Try to handle urgent data inline */
596 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
597 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
601 if (fcntl(s, F_SETOWN, getpid()) == -1)
602 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
604 dolog((struct sockaddr *)&his_addr);
606 * Set up default state
615 /* If logins are disabled, print out the message. */
616 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
617 while (fgets(line, sizeof(line), fd) != NULL) {
618 if ((cp = strchr(line, '\n')) != NULL)
620 lreply(530, "%s", line);
622 (void) fflush(stdout);
624 reply(530, "System not available.");
627 #ifdef VIRTUAL_HOSTING
628 fd = fopen(thishost->welcome, "r");
630 fd = fopen(_PATH_FTPWELCOME, "r");
633 while (fgets(line, sizeof(line), fd) != NULL) {
634 if ((cp = strchr(line, '\n')) != NULL)
636 lreply(220, "%s", line);
638 (void) fflush(stdout);
640 /* reply(220,) must follow */
642 #ifndef VIRTUAL_HOSTING
643 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
644 fatalerror("Ran out of memory.");
645 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
647 hostname[MAXHOSTNAMELEN - 1] = '\0';
650 reply(220, "%s FTP server (%s) ready.", hostname, version);
652 reply(220, "FTP server ready.");
664 syslog(LOG_DEBUG, "lost connection");
672 syslog(LOG_ERR, "got signal %d", signo);
676 #ifdef VIRTUAL_HOSTING
678 * read in virtual host tables (if they exist)
682 inithosts(int family)
687 char *cp, *mp, *line;
689 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
690 struct ftphost *hrp, *lhrp;
691 struct addrinfo hints, *res, *ai;
694 * Fill in the default host information
696 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
697 fatalerror("Ran out of memory.");
698 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
700 hostname[MAXHOSTNAMELEN - 1] = '\0';
701 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
702 fatalerror("Ran out of memory.");
703 hrp->hostname = hostname;
704 hrp->hostinfo = NULL;
706 memset(&hints, 0, sizeof(hints));
707 hints.ai_flags = AI_PASSIVE;
708 hints.ai_family = family;
709 hints.ai_socktype = SOCK_STREAM;
710 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
712 hrp->statfile = _PATH_FTPDSTATFILE;
713 hrp->welcome = _PATH_FTPWELCOME;
714 hrp->loginmsg = _PATH_FTPLOGINMESG;
715 hrp->anonuser = "ftp";
717 thishost = firsthost = lhrp = hrp;
718 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
719 int addrsize, gothost;
723 while ((line = fgetln(fp, &len)) != NULL) {
729 if (line[len - 1] == '\n') {
730 line[len - 1] = '\0';
733 if ((mp = malloc(len + 1)) == NULL)
734 fatalerror("Ran out of memory.");
735 memcpy(mp, line, len);
739 cp = strtok(line, " \t");
740 /* skip empty lines */
747 statfile = _PATH_FTPDSTATFILE;
748 welcome = _PATH_FTPWELCOME;
749 loginmsg = _PATH_FTPLOGINMESG;
752 * Preparse the line so we can use its info
753 * for all the addresses associated with
754 * the virtual host name.
755 * Field 0, the virtual host name, is special:
756 * it's already parsed off and will be strdup'ed
757 * later, after we know its canonical form.
759 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
760 if (*cp != '-' && (cp = strdup(cp)))
762 case 1: /* anon user permissions */
765 case 2: /* statistics file */
768 case 3: /* welcome message */
771 case 4: /* login message */
774 default: /* programming error */
779 hints.ai_flags = AI_PASSIVE;
780 hints.ai_family = family;
781 hints.ai_socktype = SOCK_STREAM;
782 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
784 for (ai = res; ai != NULL && ai->ai_addr != NULL;
788 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
791 for (hi = hrp->hostinfo; hi != NULL;
793 if (hi->ai_addrlen == ai->ai_addrlen &&
796 ai->ai_addr->sa_len) == 0) {
804 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
806 hrp->hostname = NULL;
809 if (hrp->hostinfo && hrp->hostinfo != res)
810 freeaddrinfo(hrp->hostinfo);
811 insert = 0; /* host already in the chain */
816 * determine hostname to use.
817 * force defined name if there is a valid alias
818 * otherwise fallback to primary hostname
820 /* XXX: getaddrinfo() can't do alias check */
821 switch(hrp->hostinfo->ai_family) {
823 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
824 addrsize = sizeof(struct in_addr);
827 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
828 addrsize = sizeof(struct in6_addr);
831 /* should not reach here */
832 freeaddrinfo(hrp->hostinfo);
834 free(hrp); /*not in chain, can free*/
836 hrp->hostinfo = NULL; /*mark as blank*/
840 if ((hp = getipnodebyaddr(addr, addrsize,
841 hrp->hostinfo->ai_family,
842 &hp_error)) != NULL) {
843 if (strcmp(vhost, hp->h_name) != 0) {
844 if (hp->h_aliases == NULL)
848 while (hp->h_aliases[i] &&
849 strcmp(vhost, hp->h_aliases[i]) != 0)
851 if (hp->h_aliases[i] == NULL)
857 strcmp(hrp->hostname, vhost) != 0) {
859 hrp->hostname = NULL;
861 if (hrp->hostname == NULL &&
862 (hrp->hostname = strdup(vhost)) == NULL) {
863 freeaddrinfo(hrp->hostinfo);
864 hrp->hostinfo = NULL; /* mark as blank */
869 hrp->anonuser = anonuser;
870 hrp->statfile = statfile;
871 hrp->welcome = welcome;
872 hrp->loginmsg = loginmsg;
890 selecthost(union sockunion *su)
895 struct in6_addr *mapped_in6 = NULL;
901 * XXX IPv4 mapped IPv6 addr consideraton,
902 * specified in rfc2373.
904 if (su->su_family == AF_INET6 &&
905 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
906 mapped_in6 = &su->su_sin6.sin6_addr;
909 hrp = thishost = firsthost; /* default */
912 while (hrp != NULL) {
913 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
914 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
919 /* XXX IPv4 mapped IPv6 addr consideraton */
920 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
921 (memcmp(&mapped_in6->s6_addr[12],
922 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
923 sizeof(struct in_addr)) == 0)) {
933 /* setup static variables as appropriate */
934 hostname = thishost->hostname;
935 ftpuser = thishost->anonuser;
940 * Helper function for sgetpwnam().
945 char *new = malloc(strlen(s) + 1);
948 reply(421, "Ran out of memory.");
952 (void) strcpy(new, s);
957 * Save the result of a getpwnam. Used for USER command, since
958 * the data returned must not be clobbered by any other command
960 * NB: The data returned by sgetpwnam() will remain valid until
961 * the next call to this function. Its difference from getpwnam()
962 * is that sgetpwnam() is known to be called from ftpd code only.
964 static struct passwd *
965 sgetpwnam(char *name)
967 static struct passwd save;
970 if ((p = getpwnam(name)) == NULL)
974 free(save.pw_passwd);
981 save.pw_name = sgetsave(p->pw_name);
982 save.pw_passwd = sgetsave(p->pw_passwd);
983 save.pw_class = sgetsave(p->pw_class);
984 save.pw_gecos = sgetsave(p->pw_gecos);
985 save.pw_dir = sgetsave(p->pw_dir);
986 save.pw_shell = sgetsave(p->pw_shell);
990 static int login_attempts; /* number of failed login attempts */
991 static int askpasswd; /* had user command, ask for passwd */
992 static char curname[MAXLOGNAME]; /* current USER name */
996 * Sets global passwd pointer pw if named account exists and is acceptable;
997 * sets askpasswd if a PASS command is expected. If logged in previously,
998 * need to reset state. If name is "ftp" or "anonymous", the name is not in
999 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
1000 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
1001 * requesting login privileges. Disallow anyone who does not have a standard
1002 * shell as returned by getusershell(). Disallow anyone mentioned in the file
1003 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
1013 reply(530, "Can't change user from guest login.");
1015 } else if (dochroot) {
1016 reply(530, "Can't change user from chroot user.");
1023 #ifdef VIRTUAL_HOSTING
1024 pw = sgetpwnam(thishost->anonuser);
1026 pw = sgetpwnam("ftp");
1028 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1029 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL, &ecode) ||
1030 (ecode != 0 && ecode != ENOENT))
1031 reply(530, "User %s access denied.", name);
1032 else if (checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL, &ecode) ||
1033 (ecode != 0 && ecode != ENOENT))
1034 reply(530, "User %s access denied.", name);
1035 else if (pw != NULL) {
1039 "Guest login ok, send your email address as password.");
1041 reply(530, "User %s unknown.", name);
1042 if (!askpasswd && logging)
1044 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1047 if (anon_only != 0) {
1048 reply(530, "Sorry, only anonymous ftp allowed.");
1052 if ((pw = sgetpwnam(name))) {
1053 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1054 shell = _PATH_BSHELL;
1056 while ((cp = getusershell()) != NULL)
1057 if (strcmp(cp, shell) == 0)
1062 (checkuser(_PATH_FTPUSERS, name, 1, NULL, &ecode) ||
1063 (ecode != 0 && ecode != ENOENT))) {
1064 reply(530, "User %s access denied.", name);
1067 "FTP LOGIN REFUSED FROM %s, %s",
1074 strncpy(curname, name, sizeof(curname)-1);
1078 /* XXX Kluge! The conversation mechanism needs to be fixed. */
1080 if (opiechallenge(&opiedata, name, opieprompt) == 0) {
1081 pwok = (pw != NULL) &&
1082 opieaccessfile(remotehost) &&
1083 opiealways(pw->pw_dir);
1084 reply(331, "Response to %s %s for %s.",
1085 opieprompt, pwok ? "requested" : "required", name);
1088 reply(331, "Password required for %s.", name);
1092 * Delay before reading passwd after first failed
1093 * attempt to slow down passwd-guessing programs.
1096 sleep(login_attempts);
1100 * Check if a user is in the file "fname",
1101 * return a pointer to a malloc'd string with the rest
1102 * of the matching line in "residue" if not NULL.
1105 checkuser(char *fname, char *name, int pwset, char **residue, int *ecode)
1110 char *line, *mp, *p;
1114 if ((fd = fopen(fname, "r")) != NULL) {
1115 while (!found && (line = fgetln(fd, &len)) != NULL) {
1119 if (line[len - 1] == '\n') {
1120 line[len - 1] = '\0';
1123 if ((mp = malloc(len + 1)) == NULL)
1124 fatalerror("Ran out of memory.");
1125 memcpy(mp, line, len);
1129 /* avoid possible leading and trailing whitespace */
1130 p = strtok(line, " \t");
1131 /* skip empty lines */
1135 * if first chr is '@', check group membership
1141 if (p[1] == '\0') /* single @ matches anyone */
1144 if ((grp = getgrnam(p+1)) == NULL)
1147 * Check user's default group
1149 if (pwset && grp->gr_gid == pw->pw_gid)
1152 * Check supplementary groups
1154 while (!found && grp->gr_mem[i])
1155 found = strcmp(name,
1161 * Otherwise, just check for username match
1164 found = strcmp(p, name) == 0;
1166 * Save the rest of line to "residue" if matched
1168 if (found && residue) {
1169 if ((p = strtok(NULL, "")) != NULL)
1170 p += strspn(p, " \t");
1172 if ((*residue = strdup(p)) == NULL)
1173 fatalerror("Ran out of memory.");
1182 } else if (ecode != NULL)
1188 * Terminate login as previous user, if any, resetting state;
1189 * used when USER command is given or login fails.
1199 if (logged_in && dowtmp)
1200 ftpd_logwtmp(wtmpid, NULL, NULL);
1203 setusercontext(NULL, getpwuid(0), 0, LOGIN_SETALL & ~(LOGIN_SETLOGIN |
1204 LOGIN_SETUSER | LOGIN_SETGROUP | LOGIN_SETPATH |
1209 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1210 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1211 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1212 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1213 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1214 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1226 * the following code is stolen from imap-uw PAM authentication module and
1229 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1232 const char *uname; /* user name */
1233 const char *pass; /* password */
1235 typedef struct cred_t cred_t;
1238 auth_conv(int num_msg, const struct pam_message **msg,
1239 struct pam_response **resp, void *appdata)
1242 cred_t *cred = (cred_t *) appdata;
1243 struct pam_response *reply;
1245 reply = calloc(num_msg, sizeof *reply);
1249 for (i = 0; i < num_msg; i++) {
1250 switch (msg[i]->msg_style) {
1251 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1252 reply[i].resp_retcode = PAM_SUCCESS;
1253 reply[i].resp = COPY_STRING(cred->uname);
1254 /* PAM frees resp. */
1256 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1257 reply[i].resp_retcode = PAM_SUCCESS;
1258 reply[i].resp = COPY_STRING(cred->pass);
1259 /* PAM frees resp. */
1263 reply[i].resp_retcode = PAM_SUCCESS;
1264 reply[i].resp = NULL;
1266 default: /* unknown message style */
1268 return PAM_CONV_ERR;
1277 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1278 * authenticated, or 1 if not authenticated. If some sort of PAM system
1279 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1280 * function returns -1. This can be used as an indication that we should
1281 * fall back to a different authentication mechanism.
1284 auth_pam(struct passwd **ppw, const char *pass)
1286 const char *tmpl_user;
1290 cred_t auth_cred = { (*ppw)->pw_name, pass };
1291 struct pam_conv conv = { &auth_conv, &auth_cred };
1293 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1294 if (e != PAM_SUCCESS) {
1296 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1297 * if context creation has failed in the first place.
1299 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
1303 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1304 if (e != PAM_SUCCESS) {
1305 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1306 pam_strerror(pamh, e));
1307 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1308 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1314 e = pam_authenticate(pamh, 0);
1318 * With PAM we support the concept of a "template"
1319 * user. The user enters a login name which is
1320 * authenticated by PAM, usually via a remote service
1321 * such as RADIUS or TACACS+. If authentication
1322 * succeeds, a different but related "template" name
1323 * is used for setting the credentials, shell, and
1324 * home directory. The name the user enters need only
1325 * exist on the remote authentication server, but the
1326 * template name must be present in the local password
1329 * This is supported by two various mechanisms in the
1330 * individual modules. However, from the application's
1331 * point of view, the template user is always passed
1332 * back as a changed value of the PAM_USER item.
1334 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1336 tmpl_user = (const char *) item;
1337 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1338 *ppw = getpwnam(tmpl_user);
1340 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1341 pam_strerror(pamh, e));
1346 case PAM_USER_UNKNOWN:
1352 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1358 e = pam_acct_mgmt(pamh, 0);
1359 if (e != PAM_SUCCESS) {
1360 syslog(LOG_ERR, "pam_acct_mgmt: %s",
1361 pam_strerror(pamh, e));
1367 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1368 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1375 #endif /* USE_PAM */
1383 login_cap_t *lc = NULL;
1388 char *residue = NULL;
1391 if (logged_in || askpasswd == 0) {
1392 reply(503, "Login with USER first.");
1396 if (!guest) { /* "ftp" is only account allowed no password */
1398 rval = 1; /* failure below */
1402 rval = auth_pam(&pw, passwd);
1408 if (opieverify(&opiedata, passwd) == 0)
1409 xpasswd = pw->pw_passwd;
1411 xpasswd = crypt(passwd, pw->pw_passwd);
1412 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1418 rval = strcmp(pw->pw_passwd, xpasswd);
1419 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1420 rval = 1; /* failure */
1423 * If rval == 1, the user failed the authentication check
1424 * above. If rval == 0, either PAM or local authentication
1428 reply(530, "Login incorrect.");
1429 BLACKLIST_NOTIFY(BLACKLIST_AUTH_FAIL, STDIN_FILENO, "Login incorrect");
1432 "FTP LOGIN FAILED FROM %s",
1434 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1435 "FTP LOGIN FAILED FROM %s, %s",
1436 remotehost, curname);
1439 if (login_attempts++ >= 5) {
1441 "repeated login failures from %s",
1447 BLACKLIST_NOTIFY(BLACKLIST_AUTH_OK, STDIN_FILENO, "Login successful");
1450 login_attempts = 0; /* this time successful */
1451 if (setegid(pw->pw_gid) < 0) {
1452 reply(550, "Can't set gid.");
1455 /* May be overridden by login.conf */
1456 (void) umask(defumask);
1458 if ((lc = login_getpwclass(pw)) != NULL) {
1459 char remote_ip[NI_MAXHOST];
1461 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1462 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1465 remote_ip[sizeof(remote_ip) - 1] = 0;
1466 if (!auth_hostok(lc, remotehost, remote_ip)) {
1467 syslog(LOG_INFO|LOG_AUTH,
1468 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1470 reply(530, "Permission denied.");
1474 if (!auth_timeok(lc, time(NULL))) {
1475 reply(530, "Login not available right now.");
1480 setusercontext(lc, pw, 0, LOGIN_SETALL &
1481 ~(LOGIN_SETUSER | LOGIN_SETPATH | LOGIN_SETENV));
1483 setlogin(pw->pw_name);
1484 (void) initgroups(pw->pw_name, pw->pw_gid);
1489 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1490 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1491 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1492 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1498 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue, &ecode)
1499 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1500 || login_getcapbool(lc, "ftp-chroot", 0)
1504 * It is possible that checkuser() failed to open the chroot file.
1505 * If this is the case, report that logins are un-available, since we
1506 * have no way of checking whether or not the user should be chrooted.
1507 * We ignore ENOENT since it is not required that this file be present.
1509 if (ecode != 0 && ecode != ENOENT) {
1510 reply(530, "Login not available right now.");
1515 /* Disable wtmp logging when chrooting. */
1516 if (dochroot || guest)
1519 ftpd_logwtmp(wtmpid, pw->pw_name,
1520 (struct sockaddr *)&his_addr);
1523 if (guest && stats && statfd < 0)
1524 #ifdef VIRTUAL_HOSTING
1525 statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1527 statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1533 * For a chrooted local user,
1534 * a) see whether ftpchroot(5) specifies a chroot directory,
1535 * b) extract the directory pathname from the line,
1536 * c) expand it to the absolute pathname if necessary.
1538 if (dochroot && residue &&
1539 (chrootdir = strtok(residue, " \t")) != NULL) {
1540 if (chrootdir[0] != '/')
1541 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1543 chrootdir = strdup(chrootdir); /* make it permanent */
1544 if (chrootdir == NULL)
1545 fatalerror("Ran out of memory.");
1547 if (guest || dochroot) {
1549 * If no chroot directory set yet, use the login directory.
1550 * Copy it so it can be modified while pw->pw_dir stays intact.
1552 if (chrootdir == NULL &&
1553 (chrootdir = strdup(pw->pw_dir)) == NULL)
1554 fatalerror("Ran out of memory.");
1556 * Check for the "/chroot/./home" syntax,
1557 * separate the chroot and home directory pathnames.
1559 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1560 *(homedir++) = '\0'; /* wipe '/' */
1561 homedir++; /* skip '.' */
1564 * We MUST do a chdir() after the chroot. Otherwise
1565 * the old current directory will be accessible as "."
1566 * outside the new root!
1571 * Finally, do chroot()
1573 if (chroot(chrootdir) < 0) {
1574 reply(550, "Can't change root.");
1577 __FreeBSD_libc_enter_restricted_mode();
1578 } else /* real user w/o chroot */
1579 homedir = pw->pw_dir;
1581 * Set euid *before* doing chdir() so
1582 * a) the user won't be carried to a directory that he couldn't reach
1583 * on his own due to no permission to upper path components,
1584 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1585 * (uid 0 has no root power over NFS if not mapped explicitly.)
1587 if (seteuid(pw->pw_uid) < 0) {
1588 reply(550, "Can't set uid.");
1591 if (chdir(homedir) < 0) {
1592 if (guest || dochroot) {
1593 reply(550, "Can't change to base directory.");
1596 if (chdir("/") < 0) {
1597 reply(550, "Root is inaccessible.");
1600 lreply(230, "No directory! Logging in with home=/.");
1605 * Display a login message, if it exists.
1606 * N.B. reply(230,) must follow the message.
1608 #ifdef VIRTUAL_HOSTING
1609 fd = fopen(thishost->loginmsg, "r");
1611 fd = fopen(_PATH_FTPLOGINMESG, "r");
1614 char *cp, line[LINE_MAX];
1616 while (fgets(line, sizeof(line), fd) != NULL) {
1617 if ((cp = strchr(line, '\n')) != NULL)
1619 lreply(230, "%s", line);
1621 (void) fflush(stdout);
1627 ident = strdup(passwd);
1629 fatalerror("Ran out of memory.");
1631 reply(230, "Guest login ok, access restrictions apply.");
1633 #ifdef VIRTUAL_HOSTING
1634 if (thishost != firsthost)
1635 snprintf(proctitle, sizeof(proctitle),
1636 "%s: anonymous(%s)/%s", remotehost, hostname,
1640 snprintf(proctitle, sizeof(proctitle),
1641 "%s: anonymous/%s", remotehost, passwd);
1642 setproctitle("%s", proctitle);
1643 #endif /* SETPROCTITLE */
1645 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1646 remotehost, passwd);
1649 reply(230, "User %s logged in, "
1650 "access restrictions apply.", pw->pw_name);
1652 reply(230, "User %s logged in.", pw->pw_name);
1655 snprintf(proctitle, sizeof(proctitle),
1656 "%s: user/%s", remotehost, pw->pw_name);
1657 setproctitle("%s", proctitle);
1658 #endif /* SETPROCTITLE */
1660 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1661 remotehost, pw->pw_name);
1663 if (logging && (guest || dochroot))
1664 syslog(LOG_INFO, "session root changed to %s", chrootdir);
1672 /* Forget all about it... */
1682 retrieve(char *cmd, char *name)
1686 int (*closefunc)(FILE *);
1691 fin = fopen(name, "r"), closefunc = fclose;
1694 (void) snprintf(line, sizeof(line), cmd, name);
1696 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1698 st.st_blksize = BUFSIZ;
1702 perror_reply(550, name);
1704 LOGCMD("get", name);
1711 if (fstat(fileno(fin), &st) < 0) {
1712 perror_reply(550, name);
1715 if (!S_ISREG(st.st_mode)) {
1717 * Never sending a raw directory is a workaround
1718 * for buggy clients that will attempt to RETR
1719 * a directory before listing it, e.g., Mozilla.
1720 * Preventing a guest from getting irregular files
1721 * is a simple security measure.
1723 if (S_ISDIR(st.st_mode) || guest) {
1724 reply(550, "%s: not a plain file.", name);
1728 /* st.st_blksize is set for all descriptor types */
1731 if (restart_point) {
1732 if (type == TYPE_A) {
1739 if ((c=getc(fin)) == EOF) {
1740 perror_reply(550, name);
1746 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1747 perror_reply(550, name);
1751 dout = dataconn(name, st.st_size, "w");
1755 send_data(fin, dout, st.st_blksize, st.st_size,
1756 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1757 if (cmd == 0 && guest && stats && byte_count > 0)
1758 logxfer(name, byte_count, start);
1759 (void) fclose(dout);
1764 LOGBYTES("get", name, byte_count);
1769 store(char *name, char *mode, int unique)
1773 int (*closefunc)(FILE *);
1775 if (*mode == 'a') { /* APPE */
1777 /* Programming error */
1778 syslog(LOG_ERR, "Internal: unique flag to APPE");
1781 if (guest && noguestmod) {
1782 reply(550, "Appending to existing file denied.");
1785 restart_point = 0; /* not affected by preceding REST */
1787 if (unique) /* STOU overrides REST */
1789 if (guest && noguestmod) {
1790 if (restart_point) { /* guest STOR w/REST */
1791 reply(550, "Modifying existing file denied.");
1793 } else /* treat guest STOR as STOU */
1798 mode = "r+"; /* so ASCII manual seek can work */
1800 if ((fd = guniquefd(name, &name)) < 0)
1802 fout = fdopen(fd, mode);
1804 fout = fopen(name, mode);
1807 perror_reply(553, name);
1811 if (restart_point) {
1812 if (type == TYPE_A) {
1819 if ((c=getc(fout)) == EOF) {
1820 perror_reply(550, name);
1827 * We must do this seek to "current" position
1828 * because we are changing from reading to
1831 if (fseeko(fout, 0, SEEK_CUR) < 0) {
1832 perror_reply(550, name);
1835 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1836 perror_reply(550, name);
1840 din = dataconn(name, -1, "r");
1843 if (receive_data(din, fout) == 0) {
1845 reply(226, "Transfer complete (unique file name:%s).",
1848 reply(226, "Transfer complete.");
1854 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1858 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1863 getdatasock(char *mode)
1865 int on = 1, s, t, tries;
1868 return (fdopen(data, mode));
1870 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1873 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1874 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1875 /* anchor socket to avoid multi-homing problems */
1876 data_source = ctrl_addr;
1877 data_source.su_port = htons(dataport);
1879 for (tries = 1; ; tries++) {
1881 * We should loop here since it's possible that
1882 * another ftpd instance has passed this point and is
1883 * trying to open a data connection in active mode now.
1884 * Until the other connection is opened, we'll be getting
1885 * EADDRINUSE because no SOCK_STREAM sockets in the system
1886 * can share both local and remote addresses, localIP:20
1887 * and *:* in this case.
1889 if (bind(s, (struct sockaddr *)&data_source,
1890 data_source.su_len) >= 0)
1892 if (errno != EADDRINUSE || tries > 10)
1896 (void) seteuid(pw->pw_uid);
1898 if (data_source.su_family == AF_INET)
1900 on = IPTOS_THROUGHPUT;
1901 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1902 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1907 * Turn off push flag to keep sender TCP from sending short packets
1908 * at the boundaries of each write().
1911 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1912 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1914 return (fdopen(s, mode));
1916 /* Return the real value of errno (close may change it) */
1918 (void) seteuid(pw->pw_uid);
1925 dataconn(char *name, off_t size, char *mode)
1929 int retry = 0, tos, conerrno;
1934 (void) snprintf(sizebuf, sizeof(sizebuf),
1935 " (%jd bytes)", (intmax_t)size);
1939 union sockunion from;
1940 socklen_t fromlen = ctrl_addr.su_len;
1942 struct timeval timeout;
1946 FD_SET(pdata, &set);
1948 timeout.tv_usec = 0;
1949 timeout.tv_sec = 120;
1952 * Granted a socket is in the blocking I/O mode,
1953 * accept() will block after a successful select()
1954 * if the selected connection dies in between.
1955 * Therefore set the non-blocking I/O flag here.
1957 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1958 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1960 if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
1961 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1963 (void) close(pdata);
1966 * Unset the inherited non-blocking I/O flag
1967 * on the child socket so stdio can work on it.
1969 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1970 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1973 if (from.su_family == AF_INET)
1975 tos = IPTOS_THROUGHPUT;
1976 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1977 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1980 reply(150, "Opening %s mode data connection for '%s'%s.",
1981 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1982 return (fdopen(pdata, mode));
1984 reply(425, "Can't open data connection.");
1985 (void) close(pdata);
1990 reply(125, "Using existing data connection for '%s'%s.",
1993 return (fdopen(data, mode));
1996 data_dest = his_addr;
1999 file = getdatasock(mode);
2001 char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
2003 if (getnameinfo((struct sockaddr *)&data_source,
2005 hostbuf, sizeof(hostbuf) - 1,
2006 portbuf, sizeof(portbuf) - 1,
2007 NI_NUMERICHOST|NI_NUMERICSERV))
2008 *hostbuf = *portbuf = 0;
2009 hostbuf[sizeof(hostbuf) - 1] = 0;
2010 portbuf[sizeof(portbuf) - 1] = 0;
2011 reply(425, "Can't create data socket (%s,%s): %s.",
2012 hostbuf, portbuf, strerror(errno));
2015 data = fileno(file);
2017 if (connect(data, (struct sockaddr *)&data_dest,
2018 data_dest.su_len) == 0)
2021 (void) fclose(file);
2023 if (conerrno == EADDRINUSE) {
2029 } while (retry <= swaitmax);
2030 if (conerrno != 0) {
2031 reply(425, "Can't build data connection: %s.",
2032 strerror(conerrno));
2035 reply(150, "Opening %s mode data connection for '%s'%s.",
2036 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2041 * A helper macro to avoid code duplication
2042 * in send_data() and receive_data().
2044 * XXX We have to block SIGURG during putc() because BSD stdio
2045 * is unable to restart interrupted write operations and hence
2046 * the entire buffer contents will be lost as soon as a write()
2047 * call indicates EINTR to stdio.
2049 #define FTPD_PUTC(ch, file, label) \
2055 ret = putc((ch), (file)); \
2057 CHECKOOB(return (-1)) \
2058 else if (ferror(file)) \
2061 } while (ret == EOF); \
2065 * Transfer the contents of "instr" to "outstr" peer using the appropriate
2066 * encapsulation of the data subject to Mode, Structure, and Type.
2068 * NB: Form isn't handled.
2071 send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2073 int c, cp, filefd, netfd;
2084 CHECKOOB(return (-1))
2085 else if (c == EOF && ferror(instr))
2088 if (ferror(instr)) { /* resume after OOB */
2092 if (feof(instr)) /* EOF */
2094 syslog(LOG_ERR, "Internal: impossible condition"
2095 " on file after getc()");
2098 if (c == '\n' && cp != '\r') {
2099 FTPD_PUTC('\r', outstr, data_err);
2102 FTPD_PUTC(c, outstr, data_err);
2106 #ifdef notyet /* BSD stdio isn't ready for that */
2107 while (fflush(outstr) == EOF) {
2108 CHECKOOB(return (-1))
2116 if (fflush(outstr) == EOF)
2119 reply(226, "Transfer complete.");
2125 * isreg is only set if we are not doing restart and we
2126 * are sending a regular file
2128 netfd = fileno(outstr);
2129 filefd = fileno(instr);
2132 char *msg = "Transfer complete.";
2138 while (filesize > 0) {
2139 err = sendfile(filefd, netfd, offset, 0,
2142 * Calculate byte_count before OOB processing.
2143 * It can be used in myoob() later.
2148 CHECKOOB(return (-1))
2149 else if (err == -1) {
2150 if (errno != EINTR &&
2151 cnt == 0 && offset == 0)
2155 if (err == -1) /* resume after OOB */
2158 * We hit the EOF prematurely.
2159 * Perhaps the file was externally truncated.
2162 msg = "Transfer finished due to "
2163 "premature end of file.";
2168 reply(226, "%s", msg);
2173 if ((buf = malloc(blksize)) == NULL) {
2175 reply(451, "Ran out of memory.");
2183 cnt = read(filefd, buf, blksize);
2184 CHECKOOB(free(buf); return (-1))
2189 if (cnt < 0) /* resume after OOB */
2191 if (cnt == 0) /* EOF */
2193 for (len = cnt, bp = buf; len > 0;) {
2194 cnt = write(netfd, bp, len);
2195 CHECKOOB(free(buf); return (-1))
2209 reply(226, "Transfer complete.");
2213 reply(550, "Unimplemented TYPE %d in send_data.", type);
2219 perror_reply(426, "Data connection");
2224 perror_reply(551, "Error on input file");
2229 * Transfer data from peer to "outstr" using the appropriate encapulation of
2230 * the data subject to Mode, Structure, and Type.
2232 * N.B.: Form isn't handled.
2235 receive_data(FILE *instr, FILE *outstr)
2251 cnt = read(fileno(instr), buf, sizeof(buf));
2252 CHECKOOB(return (-1))
2255 if (cnt < 0) /* resume after OOB */
2257 if (cnt == 0) /* EOF */
2259 for (len = cnt, bp = buf; len > 0;) {
2260 cnt = write(fileno(outstr), bp, len);
2261 CHECKOOB(return (-1))
2276 reply(553, "TYPE E not implemented.");
2283 CHECKOOB(return (-1))
2284 else if (c == EOF && ferror(instr))
2286 if (c == EOF && ferror(instr)) { /* resume after OOB */
2293 FTPD_PUTC('\r', outstr, file_err);
2303 /* Check for EOF here in order not to lose last \r. */
2305 if (feof(instr)) /* EOF */
2307 syslog(LOG_ERR, "Internal: impossible condition"
2308 " on data stream after getc()");
2313 FTPD_PUTC(c, outstr, file_err);
2316 #ifdef notyet /* BSD stdio isn't ready for that */
2317 while (fflush(outstr) == EOF) {
2318 CHECKOOB(return (-1))
2326 if (fflush(outstr) == EOF)
2331 "WARNING! %d bare linefeeds received in ASCII mode.",
2333 (void)printf(" File may not have transferred correctly.\r\n");
2338 reply(550, "Unimplemented TYPE %d in receive_data.", type);
2344 perror_reply(426, "Data connection");
2349 perror_reply(452, "Error writing to file");
2354 statfilecmd(char *filename)
2359 char line[LINE_MAX];
2362 code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2363 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2364 fin = ftpd_popen(line, "r");
2366 perror_reply(551, filename);
2369 lreply(code, "Status of %s:", filename);
2371 while ((c = getc(fin)) != EOF) {
2373 if (ferror(stdout)){
2374 perror_reply(421, "Control connection");
2375 (void) ftpd_pclose(fin);
2380 perror_reply(551, filename);
2381 (void) ftpd_pclose(fin);
2384 (void) putc('\r', stdout);
2387 * RFC 959 says neutral text should be prepended before
2388 * a leading 3-digit number followed by whitespace, but
2389 * many ftp clients can be confused by any leading digits,
2390 * as a matter of fact.
2392 if (atstart && isdigit(c))
2393 (void) putc(' ', stdout);
2394 (void) putc(c, stdout);
2395 atstart = (c == '\n');
2397 (void) ftpd_pclose(fin);
2398 reply(code, "End of status.");
2404 union sockunion *su;
2406 char hname[NI_MAXHOST];
2410 lreply(211, "%s FTP server status:", hostname);
2411 printf(" %s\r\n", version);
2413 lreply(211, "FTP server status:");
2414 printf(" Connected to %s", remotehost);
2415 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2416 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2417 hname[sizeof(hname) - 1] = 0;
2418 if (strcmp(hname, remotehost) != 0)
2419 printf(" (%s)", hname);
2424 printf(" Logged in anonymously\r\n");
2426 printf(" Logged in as %s\r\n", pw->pw_name);
2427 } else if (askpasswd)
2428 printf(" Waiting for password\r\n");
2430 printf(" Waiting for user name\r\n");
2431 printf(" TYPE: %s", typenames[type]);
2432 if (type == TYPE_A || type == TYPE_E)
2433 printf(", FORM: %s", formnames[form]);
2436 printf(" %d", CHAR_BIT);
2438 printf(" %d", bytesize); /* need definition! */
2440 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2441 strunames[stru], modenames[mode]);
2443 printf(" Data connection open\r\n");
2444 else if (pdata != -1) {
2448 } else if (usedefault == 0) {
2452 #define UC(b) (((int) b) & 0xff)
2454 printf(" EPSV only mode (EPSV ALL)\r\n");
2459 if (su->su_family == AF_INET) {
2460 a = (u_char *) &su->su_sin.sin_addr;
2461 p = (u_char *) &su->su_sin.sin_port;
2462 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2463 ispassive ? "PASV" : "PORT",
2464 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2465 UC(p[0]), UC(p[1]));
2472 switch (su->su_family) {
2474 a = (u_char *) &su->su_sin.sin_addr;
2475 p = (u_char *) &su->su_sin.sin_port;
2476 alen = sizeof(su->su_sin.sin_addr);
2480 a = (u_char *) &su->su_sin6.sin6_addr;
2481 p = (u_char *) &su->su_sin6.sin6_port;
2482 alen = sizeof(su->su_sin6.sin6_addr);
2490 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2492 for (i = 0; i < alen; i++)
2493 printf("%d,", UC(a[i]));
2494 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2503 switch (su->su_family) {
2515 union sockunion tmp;
2518 if (tmp.su_family == AF_INET6)
2519 tmp.su_sin6.sin6_scope_id = 0;
2520 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2521 hname, sizeof(hname) - 1, NULL, 0,
2523 hname[sizeof(hname) - 1] = 0;
2524 printf(" %s |%d|%s|%d|\r\n",
2525 ispassive ? "EPSV" : "EPRT",
2526 af, hname, htons(tmp.su_port));
2532 printf(" No data connection\r\n");
2533 reply(211, "End of status.");
2540 reply(451, "Error in server: %s", s);
2541 reply(221, "Closing connection due to server error.");
2547 reply(int n, const char *fmt, ...)
2551 (void)printf("%d ", n);
2553 (void)vprintf(fmt, ap);
2555 (void)printf("\r\n");
2556 (void)fflush(stdout);
2558 syslog(LOG_DEBUG, "<--- %d ", n);
2560 vsyslog(LOG_DEBUG, fmt, ap);
2566 lreply(int n, const char *fmt, ...)
2570 (void)printf("%d- ", n);
2572 (void)vprintf(fmt, ap);
2574 (void)printf("\r\n");
2575 (void)fflush(stdout);
2577 syslog(LOG_DEBUG, "<--- %d- ", n);
2579 vsyslog(LOG_DEBUG, fmt, ap);
2588 reply(250, "%s command successful.", s);
2595 reply(502, "%s command not implemented.", s);
2604 if ((cp = strchr(cbuf,'\n')))
2606 reply(500, "%s: command not understood.", cbuf);
2614 LOGCMD("delete", name);
2615 if (lstat(name, &st) < 0) {
2616 perror_reply(550, name);
2619 if (S_ISDIR(st.st_mode)) {
2620 if (rmdir(name) < 0) {
2621 perror_reply(550, name);
2626 if (guest && noguestmod) {
2627 reply(550, "Operation not permitted.");
2630 if (unlink(name) < 0) {
2631 perror_reply(550, name);
2642 if (chdir(path) < 0)
2643 perror_reply(550, path);
2653 LOGCMD("mkdir", name);
2654 if (guest && noguestmkd)
2655 reply(550, "Operation not permitted.");
2656 else if (mkdir(name, 0777) < 0)
2657 perror_reply(550, name);
2659 if ((s = doublequote(name)) == NULL)
2660 fatalerror("Ran out of memory.");
2661 reply(257, "\"%s\" directory created.", s);
2667 removedir(char *name)
2670 LOGCMD("rmdir", name);
2671 if (rmdir(name) < 0)
2672 perror_reply(550, name);
2680 char *s, path[MAXPATHLEN + 1];
2682 if (getcwd(path, sizeof(path)) == NULL)
2683 perror_reply(550, "Get current directory");
2685 if ((s = doublequote(path)) == NULL)
2686 fatalerror("Ran out of memory.");
2687 reply(257, "\"%s\" is current directory.", s);
2693 renamefrom(char *name)
2697 if (guest && noguestmod) {
2698 reply(550, "Operation not permitted.");
2701 if (lstat(name, &st) < 0) {
2702 perror_reply(550, name);
2705 reply(350, "File exists, ready for destination name.");
2710 renamecmd(char *from, char *to)
2714 LOGCMD2("rename", from, to);
2716 if (guest && (stat(to, &st) == 0)) {
2717 reply(550, "%s: permission denied.", to);
2721 if (rename(from, to) < 0)
2722 perror_reply(550, "rename");
2728 dolog(struct sockaddr *who)
2730 char who_name[NI_MAXHOST];
2732 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2733 remotehost[sizeof(remotehost) - 1] = 0;
2734 if (getnameinfo(who, who->sa_len,
2735 who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
2737 who_name[sizeof(who_name) - 1] = 0;
2740 #ifdef VIRTUAL_HOSTING
2741 if (thishost != firsthost)
2742 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2743 remotehost, hostname);
2746 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2748 setproctitle("%s", proctitle);
2749 #endif /* SETPROCTITLE */
2752 #ifdef VIRTUAL_HOSTING
2753 if (thishost != firsthost)
2754 syslog(LOG_INFO, "connection from %s (%s) to %s",
2755 remotehost, who_name, hostname);
2758 syslog(LOG_INFO, "connection from %s (%s)",
2759 remotehost, who_name);
2764 * Record logout in wtmp file
2765 * and exit with supplied status.
2768 dologout(int status)
2771 if (logged_in && dowtmp) {
2773 ftpd_logwtmp(wtmpid, NULL, NULL);
2775 /* beware of flushing buffers after a SIGPIPE */
2793 syslog(LOG_ERR, "Internal: maskurg() while no transfer");
2798 sigaddset(&sset, SIGURG);
2799 sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
2809 syslog(LOG_ERR, "Internal: flagxfer(1): "
2810 "transfer already under way");
2816 syslog(LOG_ERR, "Internal: flagxfer(0): "
2817 "no active transfer");
2824 * Returns 0 if OK to resume or -1 if abort requested.
2833 syslog(LOG_ERR, "Internal: myoob() while no transfer");
2837 ret = get_line(cp, 7, stdin);
2839 reply(221, "You could at least say goodbye.");
2841 } else if (ret == -2) {
2842 /* Ignore truncated command. */
2846 if (strcmp(cp, "ABOR\r\n") == 0) {
2848 reply(426, "Transfer aborted. Data connection closed.");
2849 reply(226, "Abort successful.");
2852 if (strcmp(cp, "STAT\r\n") == 0) {
2854 if (file_size != -1)
2855 reply(213, "Status: %jd of %jd bytes transferred.",
2856 (intmax_t)byte_count, (intmax_t)file_size);
2858 reply(213, "Status: %jd bytes transferred.",
2859 (intmax_t)byte_count);
2865 * Note: a response of 425 is not mentioned as a possible response to
2866 * the PASV command in RFC959. However, it has been blessed as
2867 * a legitimate response by Jon Postel in a telephone conversation
2868 * with Rick Adams on 25 Jan 89.
2877 if (pdata >= 0) /* close old port if one set */
2880 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2882 perror_reply(425, "Can't open passive connection");
2886 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2887 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2892 if (ctrl_addr.su_family == AF_INET) {
2893 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2894 : IP_PORTRANGE_DEFAULT;
2896 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2897 &on, sizeof(on)) < 0)
2901 #ifdef IPV6_PORTRANGE
2902 if (ctrl_addr.su_family == AF_INET6) {
2903 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2904 : IPV6_PORTRANGE_DEFAULT;
2906 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2907 &on, sizeof(on)) < 0)
2912 pasv_addr = ctrl_addr;
2913 pasv_addr.su_port = 0;
2914 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2917 (void) seteuid(pw->pw_uid);
2919 len = sizeof(pasv_addr);
2920 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2922 if (listen(pdata, 1) < 0)
2924 if (pasv_addr.su_family == AF_INET)
2925 a = (char *) &pasv_addr.su_sin.sin_addr;
2926 else if (pasv_addr.su_family == AF_INET6 &&
2927 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2928 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2932 p = (char *) &pasv_addr.su_port;
2934 #define UC(b) (((int) b) & 0xff)
2936 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2937 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2941 (void) seteuid(pw->pw_uid);
2942 (void) close(pdata);
2944 perror_reply(425, "Can't open passive connection");
2949 * Long Passive defined in RFC 1639.
2950 * 228 Entering Long Passive Mode
2951 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2955 long_passive(char *cmd, int pf)
2961 if (pdata >= 0) /* close old port if one set */
2964 if (pf != PF_UNSPEC) {
2965 if (ctrl_addr.su_family != pf) {
2966 switch (ctrl_addr.su_family) {
2979 * only EPRT/EPSV ready clients will understand this
2981 if (strcmp(cmd, "EPSV") == 0 && pf) {
2982 reply(522, "Network protocol mismatch, "
2985 reply(501, "Network protocol mismatch."); /*XXX*/
2991 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2993 perror_reply(425, "Can't open passive connection");
2997 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2998 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
3002 pasv_addr = ctrl_addr;
3003 pasv_addr.su_port = 0;
3004 len = pasv_addr.su_len;
3007 if (ctrl_addr.su_family == AF_INET) {
3008 on = restricted_data_ports ? IP_PORTRANGE_HIGH
3009 : IP_PORTRANGE_DEFAULT;
3011 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
3012 &on, sizeof(on)) < 0)
3016 #ifdef IPV6_PORTRANGE
3017 if (ctrl_addr.su_family == AF_INET6) {
3018 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
3019 : IPV6_PORTRANGE_DEFAULT;
3021 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
3022 &on, sizeof(on)) < 0)
3027 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
3030 (void) seteuid(pw->pw_uid);
3032 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
3034 if (listen(pdata, 1) < 0)
3037 #define UC(b) (((int) b) & 0xff)
3039 if (strcmp(cmd, "LPSV") == 0) {
3040 p = (char *)&pasv_addr.su_port;
3041 switch (pasv_addr.su_family) {
3043 a = (char *) &pasv_addr.su_sin.sin_addr;
3046 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3047 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3048 2, UC(p[0]), UC(p[1]));
3051 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
3052 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
3055 a = (char *) &pasv_addr.su_sin6.sin6_addr;
3057 "Entering Long Passive Mode "
3058 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3059 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3060 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3061 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3062 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3063 2, UC(p[0]), UC(p[1]));
3066 } else if (strcmp(cmd, "EPSV") == 0) {
3067 switch (pasv_addr.su_family) {
3070 reply(229, "Entering Extended Passive Mode (|||%d|)",
3071 ntohs(pasv_addr.su_port));
3075 /* more proper error code? */
3079 (void) seteuid(pw->pw_uid);
3080 (void) close(pdata);
3082 perror_reply(425, "Can't open passive connection");
3087 * Generate unique name for file with basename "local"
3088 * and open the file in order to avoid possible races.
3089 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3090 * Return descriptor to the file, set "name" to its name.
3092 * Generates failure reply on error.
3095 guniquefd(char *local, char **name)
3097 static char new[MAXPATHLEN];
3103 cp = strrchr(local, '/');
3106 if (stat(cp ? local : ".", &st) < 0) {
3107 perror_reply(553, cp ? local : ".");
3112 * Let not overwrite dirname with counter suffix.
3114 * In this extreme case dot won't be put in front of suffix.
3116 if (strlen(local) > sizeof(new) - 4) {
3117 reply(553, "Pathname too long.");
3122 /* -4 is for the .nn<null> we put on the end below */
3123 (void) snprintf(new, sizeof(new) - 4, "%s", local);
3124 cp = new + strlen(new);
3126 * Don't generate dotfile unless requested explicitly.
3127 * This covers the case when basename gets truncated off
3130 if (cp > new && cp[-1] != '/')
3132 for (count = 0; count < 100; count++) {
3133 /* At count 0 try unmodified name */
3135 (void)sprintf(cp, "%d", count);
3136 if ((fd = open(count ? new : local,
3137 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3138 *name = count ? new : local;
3141 if (errno != EEXIST) {
3142 perror_reply(553, count ? new : local);
3146 reply(452, "Unique file name cannot be created.");
3151 * Format and send reply containing system error number.
3154 perror_reply(int code, char *string)
3157 reply(code, "%s: %s.", string, strerror(errno));
3160 static char *onefile[] = {
3166 send_file_list(char *whichf)
3172 char **dirlist, *dirname;
3177 if (strpbrk(whichf, "~{[*?") != NULL) {
3178 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3180 memset(&gl, 0, sizeof(gl));
3181 gl.gl_matchc = MAXGLOBARGS;
3182 flags |= GLOB_LIMIT;
3184 if (glob(whichf, flags, 0, &gl)) {
3185 reply(550, "No matching files found.");
3187 } else if (gl.gl_pathc == 0) {
3189 perror_reply(550, whichf);
3192 dirlist = gl.gl_pathv;
3194 onefile[0] = whichf;
3199 while ((dirname = *dirlist++)) {
3200 if (stat(dirname, &st) < 0) {
3202 * If user typed "ls -l", etc, and the client
3203 * used NLST, do what the user meant.
3205 if (dirname[0] == '-' && *dirlist == NULL &&
3207 retrieve(_PATH_LS " %s", dirname);
3209 perror_reply(550, whichf);
3213 if (S_ISREG(st.st_mode)) {
3215 dout = dataconn("file list", -1, "w");
3221 fprintf(dout, "%s%s\n", dirname,
3222 type == TYPE_A ? "\r" : "");
3226 byte_count += strlen(dirname) +
3227 (type == TYPE_A ? 2 : 1);
3228 CHECKOOB(goto abrt);
3230 } else if (!S_ISDIR(st.st_mode))
3233 if ((dirp = opendir(dirname)) == NULL)
3236 while ((dir = readdir(dirp)) != NULL) {
3237 char nbuf[MAXPATHLEN];
3239 CHECKOOB(goto abrt);
3241 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
3243 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3247 snprintf(nbuf, sizeof(nbuf),
3248 "%s/%s", dirname, dir->d_name);
3251 * We have to do a stat to insure it's
3252 * not a directory or special file.
3254 if (simple || (stat(nbuf, &st) == 0 &&
3255 S_ISREG(st.st_mode))) {
3257 dout = dataconn("file list", -1, "w");
3263 if (nbuf[0] == '.' && nbuf[1] == '/')
3264 fprintf(dout, "%s%s\n", &nbuf[2],
3265 type == TYPE_A ? "\r" : "");
3267 fprintf(dout, "%s%s\n", nbuf,
3268 type == TYPE_A ? "\r" : "");
3272 byte_count += strlen(nbuf) +
3273 (type == TYPE_A ? 2 : 1);
3274 CHECKOOB(goto abrt);
3277 (void) closedir(dirp);
3282 reply(550, "No files found.");
3283 else if (ferror(dout))
3284 data_err: perror_reply(550, "Data connection");
3286 reply(226, "Transfer complete.");
3291 (void) fclose(dout);
3296 (void) closedir(dirp);
3304 reapchild(int signo)
3306 while (waitpid(-1, NULL, WNOHANG) > 0);
3309 #ifdef OLD_SETPROCTITLE
3311 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.)
3312 * Warning, since this is usually started from inetd.conf, it often doesn't
3313 * have much of an environment or arglist to overwrite.
3316 setproctitle(const char *fmt, ...)
3324 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
3326 /* make ps print our process name */
3331 if (i > LastArgv - p - 2) {
3332 i = LastArgv - p - 2;
3337 if (ch != '\n' && ch != '\r')
3339 while (p < LastArgv)
3342 #endif /* OLD_SETPROCTITLE */
3345 appendf(char **strp, char *fmt, ...)
3351 vasprintf(&p, fmt, ap);
3354 fatalerror("Ran out of memory.");
3359 asprintf(strp, "%s%s", ostr, p);
3361 fatalerror("Ran out of memory.");
3367 logcmd(char *cmd, char *file1, char *file2, off_t cnt)
3370 char wd[MAXPATHLEN + 1];
3375 if (getcwd(wd, sizeof(wd) - 1) == NULL)
3376 strcpy(wd, strerror(errno));
3378 appendf(&msg, "%s", cmd);
3380 appendf(&msg, " %s", file1);
3382 appendf(&msg, " %s", file2);
3384 appendf(&msg, " = %jd bytes", (intmax_t)cnt);
3385 appendf(&msg, " (wd: %s", wd);
3386 if (guest || dochroot)
3387 appendf(&msg, "; chrooted");
3389 syslog(LOG_INFO, "%s", msg);
3394 logxfer(char *name, off_t size, time_t start)
3396 char buf[MAXPATHLEN + 1024];
3397 char path[MAXPATHLEN + 1];
3402 if (realpath(name, path) == NULL) {
3403 syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
3406 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n",
3407 ctime(&now)+4, ident, remotehost,
3408 path, (intmax_t)size,
3409 (long)(now - start + (now == start)));
3410 write(statfd, buf, strlen(buf));
3415 doublequote(char *s)
3420 for (p = s, n = 0; *p; p++)
3424 if ((s2 = malloc(p - s + n + 1)) == NULL)
3427 for (p = s2; *s; s++, p++) {
3428 if ((*p = *s) == '"')
3436 /* setup server socket for specified address family */
3437 /* if af is PF_UNSPEC more than one socket may be returned */
3438 /* the returned list is dynamically allocated, so caller needs to free it */
3440 socksetup(int af, char *bindname, const char *bindport)
3442 struct addrinfo hints, *res, *r;
3443 int error, maxs, *s, *socks;
3446 memset(&hints, 0, sizeof(hints));
3447 hints.ai_flags = AI_PASSIVE;
3448 hints.ai_family = af;
3449 hints.ai_socktype = SOCK_STREAM;
3450 error = getaddrinfo(bindname, bindport, &hints, &res);
3452 syslog(LOG_ERR, "%s", gai_strerror(error));
3453 if (error == EAI_SYSTEM)
3454 syslog(LOG_ERR, "%s", strerror(errno));
3458 /* Count max number of sockets we may open */
3459 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3461 socks = malloc((maxs + 1) * sizeof(int));
3464 syslog(LOG_ERR, "couldn't allocate memory for sockets");
3468 *socks = 0; /* num of sockets counter at start of array */
3470 for (r = res; r; r = r->ai_next) {
3471 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3473 syslog(LOG_DEBUG, "control socket: %m");
3476 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3477 &on, sizeof(on)) < 0)
3479 "control setsockopt (SO_REUSEADDR): %m");
3480 if (r->ai_family == AF_INET6) {
3481 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3482 &on, sizeof(on)) < 0)
3484 "control setsockopt (IPV6_V6ONLY): %m");
3486 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3487 syslog(LOG_DEBUG, "control bind: %m");
3499 syslog(LOG_ERR, "control socket: Couldn't bind to any socket");