2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 static char copyright[] =
35 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
36 The Regents of the University of California. All rights reserved.\n";
42 static char sccsid[] = "@(#)ftpd.c 8.4 (Berkeley) 4/16/94";
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
52 #include <sys/param.h>
53 #include <sys/ioctl.h>
55 #include <sys/socket.h>
60 #include <netinet/in.h>
61 #include <netinet/in_systm.h>
62 #include <netinet/ip.h>
63 #include <netinet/tcp.h>
67 #include <arpa/inet.h>
68 #include <arpa/telnet.h>
91 #include <login_cap.h>
95 #include <security/pam_appl.h>
98 #include "blacklist_client.h"
99 #include "pathnames.h"
104 static char version[] = "Version 6.00LS";
107 union sockunion ctrl_addr;
108 union sockunion data_source;
109 union sockunion data_dest;
110 union sockunion his_addr;
111 union sockunion pasv_addr;
116 int hostinfo = 1; /* print host-specific info in messages */
121 int timeout = 900; /* timeout after 15 minutes of inactivity */
122 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
124 int restricted_data_ports = 1;
125 int paranoid = 1; /* be extra careful about security */
126 int anon_only = 0; /* Only anonymous ftp allowed */
127 int assumeutf8 = 0; /* Assume that server file names are in UTF-8 */
136 int stru; /* avoid C keyword */
138 int usedefault = 1; /* for data transfers */
139 int pdata = -1; /* for passive mode */
140 int readonly = 0; /* Server is in readonly mode. */
141 int noepsv = 0; /* EPSV command is disabled. */
142 int noretr = 0; /* RETR command is disabled. */
143 int noguestretr = 0; /* RETR command is disabled for anon users. */
144 int noguestmkd = 0; /* MKD command is disabled for anon users. */
145 int noguestmod = 1; /* anon users may not modify existing files. */
146 int use_blacklist = 0;
150 #if !defined(CMASK) || CMASK == 0
154 int defumask = CMASK; /* default umask value */
159 #ifdef VIRTUAL_HOSTING
162 static struct ftphost {
163 struct ftphost *next;
164 struct addrinfo *hostinfo;
170 } *thishost, *firsthost;
173 char remotehost[NI_MAXHOST];
176 static char wtmpid[20];
179 static int auth_pam(struct passwd**, const char*);
180 pam_handle_t *pamh = NULL;
183 static struct opie opiedata;
184 static char opieprompt[OPIE_CHALLENGE_MAX+1];
187 char *pid_file = NULL; /* means default location to pidfile(3) */
190 * Limit number of pathnames that glob can return.
191 * A limit of 0 indicates the number of pathnames is unlimited.
193 #define MAXGLOBARGS 16384
197 * Timeout intervals for retrying connections
198 * to hosts that don't accept PORT cmds. This
199 * is a kludge, but given the problems with TCP...
201 #define SWAITMAX 90 /* wait at most 90 seconds */
202 #define SWAITINT 5 /* interval between retries */
204 int swaitmax = SWAITMAX;
205 int swaitint = SWAITINT;
208 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)
267 int ch, on = 1, tos, s = STDIN_FILENO;
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;
280 * Prevent diagnostic messages from appearing on stderr.
281 * We run as a daemon or from inetd; in both cases, there's
282 * more reason in logging to syslog.
284 (void) freopen(_PATH_DEVNULL, "w", stderr);
288 * LOG_NDELAY sets up the logging connection immediately,
289 * necessary for anonymous ftp's that chroot and can't do it later.
291 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
293 while ((ch = getopt(argc, argv,
294 "468a:ABdDEhlmMoOp:P:rRSt:T:u:UvW")) != -1) {
297 family = (family == AF_INET6) ? AF_UNSPEC : AF_INET;
301 family = (family == AF_INET) ? AF_UNSPEC : AF_INET6;
320 syslog(LOG_WARNING, "not compiled with USE_BLACKLIST support");
341 logging++; /* > 1 == extra logging */
381 timeout = atoi(optarg);
382 if (maxtimeout < timeout)
383 maxtimeout = timeout;
387 maxtimeout = atoi(optarg);
388 if (timeout > maxtimeout)
389 timeout = maxtimeout;
396 val = strtol(optarg, &optarg, 8);
397 if (*optarg != '\0' || val < 0)
398 syslog(LOG_WARNING, "bad value for -u");
404 restricted_data_ports = 0;
416 syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
421 /* handle filesize limit gracefully */
422 sa.sa_handler = SIG_IGN;
423 (void)sigaction(SIGXFSZ, &sa, NULL);
426 int *ctl_sock, fd, maxfd = -1, nfds, i;
427 fd_set defreadfds, readfds;
431 if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
432 if (errno == EEXIST) {
433 syslog(LOG_ERR, "%s already running, pid %d",
434 getprogname(), (int)pid);
437 syslog(LOG_WARNING, "pidfile_open: %m");
441 * Detach from parent.
443 if (daemon(1, 1) < 0) {
444 syslog(LOG_ERR, "failed to become a daemon");
448 if (pfh != NULL && pidfile_write(pfh) == -1)
449 syslog(LOG_WARNING, "pidfile_write: %m");
451 sa.sa_handler = reapchild;
452 (void)sigaction(SIGCHLD, &sa, NULL);
454 #ifdef VIRTUAL_HOSTING
459 * Open a socket, bind it to the FTP port, and start
462 ctl_sock = socksetup(family, bindname, bindport);
463 if (ctl_sock == NULL)
466 FD_ZERO(&defreadfds);
467 for (i = 1; i <= *ctl_sock; i++) {
468 FD_SET(ctl_sock[i], &defreadfds);
469 if (listen(ctl_sock[i], 32) < 0) {
470 syslog(LOG_ERR, "control listen: %m");
473 if (maxfd < ctl_sock[i])
478 * Loop forever accepting connection requests and forking off
479 * children to handle them.
482 FD_COPY(&defreadfds, &readfds);
483 nfds = select(maxfd + 1, &readfds, NULL, NULL, 0);
485 if (nfds < 0 && errno != EINTR)
486 syslog(LOG_WARNING, "select: %m");
491 for (i = 1; i <= *ctl_sock; i++)
492 if (FD_ISSET(ctl_sock[i], &readfds)) {
493 addrlen = sizeof(his_addr);
494 fd = accept(ctl_sock[i],
495 (struct sockaddr *)&his_addr,
502 switch (pid = fork()) {
506 (void) dup2(fd, STDOUT_FILENO);
508 for (i = 1; i <= *ctl_sock; i++)
514 syslog(LOG_WARNING, "fork: %m");
522 addrlen = sizeof(his_addr);
523 if (getpeername(s, (struct sockaddr *)&his_addr, &addrlen) < 0) {
524 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
528 #ifdef VIRTUAL_HOSTING
529 if (his_addr.su_family == AF_INET6 &&
530 IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))
533 family = his_addr.su_family;
539 sa.sa_handler = SIG_DFL;
540 (void)sigaction(SIGCHLD, &sa, NULL);
542 sa.sa_handler = sigurg;
543 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
544 (void)sigaction(SIGURG, &sa, NULL);
546 sigfillset(&sa.sa_mask); /* block all signals in handler */
547 sa.sa_flags = SA_RESTART;
548 sa.sa_handler = sigquit;
549 (void)sigaction(SIGHUP, &sa, NULL);
550 (void)sigaction(SIGINT, &sa, NULL);
551 (void)sigaction(SIGQUIT, &sa, NULL);
552 (void)sigaction(SIGTERM, &sa, NULL);
554 sa.sa_handler = lostconn;
555 (void)sigaction(SIGPIPE, &sa, NULL);
557 addrlen = sizeof(ctrl_addr);
558 if (getsockname(s, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
559 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
562 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
563 #ifdef VIRTUAL_HOSTING
564 /* select our identity from virtual host table */
565 selecthost(&ctrl_addr);
568 if (ctrl_addr.su_family == AF_INET)
570 tos = IPTOS_LOWDELAY;
571 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
572 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
576 * Disable Nagle on the control channel so that we don't have to wait
577 * for peer's ACK before issuing our next reply.
579 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
580 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
582 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
584 (void)snprintf(wtmpid, sizeof(wtmpid), "%xftpd", getpid());
586 /* Try to handle urgent data inline */
588 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
589 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
593 if (fcntl(s, F_SETOWN, getpid()) == -1)
594 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
596 dolog((struct sockaddr *)&his_addr);
598 * Set up default state
607 /* If logins are disabled, print out the message. */
608 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
609 while (fgets(line, sizeof(line), fd) != NULL) {
610 if ((cp = strchr(line, '\n')) != NULL)
612 lreply(530, "%s", line);
614 (void) fflush(stdout);
616 reply(530, "System not available.");
619 #ifdef VIRTUAL_HOSTING
620 fd = fopen(thishost->welcome, "r");
622 fd = fopen(_PATH_FTPWELCOME, "r");
625 while (fgets(line, sizeof(line), fd) != NULL) {
626 if ((cp = strchr(line, '\n')) != NULL)
628 lreply(220, "%s", line);
630 (void) fflush(stdout);
632 /* reply(220,) must follow */
634 #ifndef VIRTUAL_HOSTING
635 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
636 fatalerror("Ran out of memory.");
637 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
639 hostname[MAXHOSTNAMELEN - 1] = '\0';
642 reply(220, "%s FTP server (%s) ready.", hostname, version);
644 reply(220, "FTP server ready.");
656 syslog(LOG_DEBUG, "lost connection");
664 syslog(LOG_ERR, "got signal %d", signo);
668 #ifdef VIRTUAL_HOSTING
670 * read in virtual host tables (if they exist)
674 inithosts(int family)
679 char *cp, *mp, *line;
681 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
682 struct ftphost *hrp, *lhrp;
683 struct addrinfo hints, *res, *ai;
686 * Fill in the default host information
688 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
689 fatalerror("Ran out of memory.");
690 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
692 hostname[MAXHOSTNAMELEN - 1] = '\0';
693 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
694 fatalerror("Ran out of memory.");
695 hrp->hostname = hostname;
696 hrp->hostinfo = NULL;
698 memset(&hints, 0, sizeof(hints));
699 hints.ai_flags = AI_PASSIVE;
700 hints.ai_family = family;
701 hints.ai_socktype = SOCK_STREAM;
702 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
704 hrp->statfile = _PATH_FTPDSTATFILE;
705 hrp->welcome = _PATH_FTPWELCOME;
706 hrp->loginmsg = _PATH_FTPLOGINMESG;
707 hrp->anonuser = "ftp";
709 thishost = firsthost = lhrp = hrp;
710 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
711 int addrsize, gothost;
715 while ((line = fgetln(fp, &len)) != NULL) {
721 if (line[len - 1] == '\n') {
722 line[len - 1] = '\0';
725 if ((mp = malloc(len + 1)) == NULL)
726 fatalerror("Ran out of memory.");
727 memcpy(mp, line, len);
731 cp = strtok(line, " \t");
732 /* skip empty lines */
739 statfile = _PATH_FTPDSTATFILE;
740 welcome = _PATH_FTPWELCOME;
741 loginmsg = _PATH_FTPLOGINMESG;
744 * Preparse the line so we can use its info
745 * for all the addresses associated with
746 * the virtual host name.
747 * Field 0, the virtual host name, is special:
748 * it's already parsed off and will be strdup'ed
749 * later, after we know its canonical form.
751 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
752 if (*cp != '-' && (cp = strdup(cp)))
754 case 1: /* anon user permissions */
757 case 2: /* statistics file */
760 case 3: /* welcome message */
763 case 4: /* login message */
766 default: /* programming error */
771 hints.ai_flags = AI_PASSIVE;
772 hints.ai_family = family;
773 hints.ai_socktype = SOCK_STREAM;
774 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
776 for (ai = res; ai != NULL && ai->ai_addr != NULL;
780 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
783 for (hi = hrp->hostinfo; hi != NULL;
785 if (hi->ai_addrlen == ai->ai_addrlen &&
788 ai->ai_addr->sa_len) == 0) {
796 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
798 hrp->hostname = NULL;
801 if (hrp->hostinfo && hrp->hostinfo != res)
802 freeaddrinfo(hrp->hostinfo);
803 insert = 0; /* host already in the chain */
808 * determine hostname to use.
809 * force defined name if there is a valid alias
810 * otherwise fallback to primary hostname
812 /* XXX: getaddrinfo() can't do alias check */
813 switch(hrp->hostinfo->ai_family) {
815 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
816 addrsize = sizeof(struct in_addr);
819 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
820 addrsize = sizeof(struct in6_addr);
823 /* should not reach here */
824 freeaddrinfo(hrp->hostinfo);
826 free(hrp); /*not in chain, can free*/
828 hrp->hostinfo = NULL; /*mark as blank*/
832 if ((hp = getipnodebyaddr(addr, addrsize,
833 hrp->hostinfo->ai_family,
834 &hp_error)) != NULL) {
835 if (strcmp(vhost, hp->h_name) != 0) {
836 if (hp->h_aliases == NULL)
840 while (hp->h_aliases[i] &&
841 strcmp(vhost, hp->h_aliases[i]) != 0)
843 if (hp->h_aliases[i] == NULL)
849 strcmp(hrp->hostname, vhost) != 0) {
851 hrp->hostname = NULL;
853 if (hrp->hostname == NULL &&
854 (hrp->hostname = strdup(vhost)) == NULL) {
855 freeaddrinfo(hrp->hostinfo);
856 hrp->hostinfo = NULL; /* mark as blank */
861 hrp->anonuser = anonuser;
862 hrp->statfile = statfile;
863 hrp->welcome = welcome;
864 hrp->loginmsg = loginmsg;
882 selecthost(union sockunion *su)
887 struct in6_addr *mapped_in6 = NULL;
893 * XXX IPv4 mapped IPv6 addr consideraton,
894 * specified in rfc2373.
896 if (su->su_family == AF_INET6 &&
897 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
898 mapped_in6 = &su->su_sin6.sin6_addr;
901 hrp = thishost = firsthost; /* default */
904 while (hrp != NULL) {
905 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
906 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
911 /* XXX IPv4 mapped IPv6 addr consideraton */
912 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
913 (memcmp(&mapped_in6->s6_addr[12],
914 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
915 sizeof(struct in_addr)) == 0)) {
925 /* setup static variables as appropriate */
926 hostname = thishost->hostname;
927 ftpuser = thishost->anonuser;
932 * Helper function for sgetpwnam().
937 char *new = malloc(strlen(s) + 1);
940 reply(421, "Ran out of memory.");
944 (void) strcpy(new, s);
949 * Save the result of a getpwnam. Used for USER command, since
950 * the data returned must not be clobbered by any other command
952 * NB: The data returned by sgetpwnam() will remain valid until
953 * the next call to this function. Its difference from getpwnam()
954 * is that sgetpwnam() is known to be called from ftpd code only.
956 static struct passwd *
957 sgetpwnam(char *name)
959 static struct passwd save;
962 if ((p = getpwnam(name)) == NULL)
966 free(save.pw_passwd);
973 save.pw_name = sgetsave(p->pw_name);
974 save.pw_passwd = sgetsave(p->pw_passwd);
975 save.pw_class = sgetsave(p->pw_class);
976 save.pw_gecos = sgetsave(p->pw_gecos);
977 save.pw_dir = sgetsave(p->pw_dir);
978 save.pw_shell = sgetsave(p->pw_shell);
982 static int login_attempts; /* number of failed login attempts */
983 static int askpasswd; /* had user command, ask for passwd */
984 static char curname[MAXLOGNAME]; /* current USER name */
988 * Sets global passwd pointer pw if named account exists and is acceptable;
989 * sets askpasswd if a PASS command is expected. If logged in previously,
990 * need to reset state. If name is "ftp" or "anonymous", the name is not in
991 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
992 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
993 * requesting login privileges. Disallow anyone who does not have a standard
994 * shell as returned by getusershell(). Disallow anyone mentioned in the file
995 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
1005 reply(530, "Can't change user from guest login.");
1007 } else if (dochroot) {
1008 reply(530, "Can't change user from chroot user.");
1015 #ifdef VIRTUAL_HOSTING
1016 pw = sgetpwnam(thishost->anonuser);
1018 pw = sgetpwnam("ftp");
1020 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1021 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL, &ecode) ||
1022 (ecode != 0 && ecode != ENOENT))
1023 reply(530, "User %s access denied.", name);
1024 else if (checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL, &ecode) ||
1025 (ecode != 0 && ecode != ENOENT))
1026 reply(530, "User %s access denied.", name);
1027 else if (pw != NULL) {
1031 "Guest login ok, send your email address as password.");
1033 reply(530, "User %s unknown.", name);
1034 if (!askpasswd && logging)
1036 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1039 if (anon_only != 0) {
1040 reply(530, "Sorry, only anonymous ftp allowed.");
1044 if ((pw = sgetpwnam(name))) {
1045 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1046 shell = _PATH_BSHELL;
1048 while ((cp = getusershell()) != NULL)
1049 if (strcmp(cp, shell) == 0)
1054 (checkuser(_PATH_FTPUSERS, name, 1, NULL, &ecode) ||
1055 (ecode != 0 && ecode != ENOENT))) {
1056 reply(530, "User %s access denied.", name);
1059 "FTP LOGIN REFUSED FROM %s, %s",
1066 strlcpy(curname, name, sizeof(curname));
1070 /* XXX Kluge! The conversation mechanism needs to be fixed. */
1072 if (opiechallenge(&opiedata, name, opieprompt) == 0) {
1073 pwok = (pw != NULL) &&
1074 opieaccessfile(remotehost) &&
1075 opiealways(pw->pw_dir);
1076 reply(331, "Response to %s %s for %s.",
1077 opieprompt, pwok ? "requested" : "required", name);
1080 reply(331, "Password required for %s.", name);
1084 * Delay before reading passwd after first failed
1085 * attempt to slow down passwd-guessing programs.
1088 sleep(login_attempts);
1092 * Check if a user is in the file "fname",
1093 * return a pointer to a malloc'd string with the rest
1094 * of the matching line in "residue" if not NULL.
1097 checkuser(char *fname, char *name, int pwset, char **residue, int *ecode)
1102 char *line, *mp, *p;
1106 if ((fd = fopen(fname, "r")) != NULL) {
1107 while (!found && (line = fgetln(fd, &len)) != NULL) {
1111 if (line[len - 1] == '\n') {
1112 line[len - 1] = '\0';
1115 if ((mp = malloc(len + 1)) == NULL)
1116 fatalerror("Ran out of memory.");
1117 memcpy(mp, line, len);
1121 /* avoid possible leading and trailing whitespace */
1122 p = strtok(line, " \t");
1123 /* skip empty lines */
1127 * if first chr is '@', check group membership
1133 if (p[1] == '\0') /* single @ matches anyone */
1136 if ((grp = getgrnam(p+1)) == NULL)
1139 * Check user's default group
1141 if (pwset && grp->gr_gid == pw->pw_gid)
1144 * Check supplementary groups
1146 while (!found && grp->gr_mem[i])
1147 found = strcmp(name,
1153 * Otherwise, just check for username match
1156 found = strcmp(p, name) == 0;
1158 * Save the rest of line to "residue" if matched
1160 if (found && residue) {
1161 if ((p = strtok(NULL, "")) != NULL)
1162 p += strspn(p, " \t");
1164 if ((*residue = strdup(p)) == NULL)
1165 fatalerror("Ran out of memory.");
1174 } else if (ecode != NULL)
1180 * Terminate login as previous user, if any, resetting state;
1181 * used when USER command is given or login fails.
1192 setusercontext(NULL, getpwuid(0), 0, LOGIN_SETALL & ~(LOGIN_SETLOGIN |
1193 LOGIN_SETUSER | LOGIN_SETGROUP | LOGIN_SETPATH |
1196 if (logged_in && dowtmp)
1197 ftpd_logwtmp(wtmpid, NULL, NULL);
1201 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1202 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1203 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1204 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1205 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1206 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1218 * the following code is stolen from imap-uw PAM authentication module and
1221 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1224 const char *uname; /* user name */
1225 const char *pass; /* password */
1227 typedef struct cred_t cred_t;
1230 auth_conv(int num_msg, const struct pam_message **msg,
1231 struct pam_response **resp, void *appdata)
1234 cred_t *cred = (cred_t *) appdata;
1235 struct pam_response *reply;
1237 reply = calloc(num_msg, sizeof *reply);
1241 for (i = 0; i < num_msg; i++) {
1242 switch (msg[i]->msg_style) {
1243 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1244 reply[i].resp_retcode = PAM_SUCCESS;
1245 reply[i].resp = COPY_STRING(cred->uname);
1246 /* PAM frees resp. */
1248 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1249 reply[i].resp_retcode = PAM_SUCCESS;
1250 reply[i].resp = COPY_STRING(cred->pass);
1251 /* PAM frees resp. */
1255 reply[i].resp_retcode = PAM_SUCCESS;
1256 reply[i].resp = NULL;
1258 default: /* unknown message style */
1260 return PAM_CONV_ERR;
1269 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1270 * authenticated, or 1 if not authenticated. If some sort of PAM system
1271 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1272 * function returns -1. This can be used as an indication that we should
1273 * fall back to a different authentication mechanism.
1276 auth_pam(struct passwd **ppw, const char *pass)
1278 const char *tmpl_user;
1282 cred_t auth_cred = { (*ppw)->pw_name, pass };
1283 struct pam_conv conv = { &auth_conv, &auth_cred };
1285 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1286 if (e != PAM_SUCCESS) {
1288 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1289 * if context creation has failed in the first place.
1291 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
1295 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1296 if (e != PAM_SUCCESS) {
1297 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1298 pam_strerror(pamh, e));
1299 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1300 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1306 e = pam_authenticate(pamh, 0);
1310 * With PAM we support the concept of a "template"
1311 * user. The user enters a login name which is
1312 * authenticated by PAM, usually via a remote service
1313 * such as RADIUS or TACACS+. If authentication
1314 * succeeds, a different but related "template" name
1315 * is used for setting the credentials, shell, and
1316 * home directory. The name the user enters need only
1317 * exist on the remote authentication server, but the
1318 * template name must be present in the local password
1321 * This is supported by two various mechanisms in the
1322 * individual modules. However, from the application's
1323 * point of view, the template user is always passed
1324 * back as a changed value of the PAM_USER item.
1326 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1328 tmpl_user = (const char *) item;
1329 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1330 *ppw = getpwnam(tmpl_user);
1332 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1333 pam_strerror(pamh, e));
1338 case PAM_USER_UNKNOWN:
1344 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1350 e = pam_acct_mgmt(pamh, 0);
1351 if (e != PAM_SUCCESS) {
1352 syslog(LOG_ERR, "pam_acct_mgmt: %s",
1353 pam_strerror(pamh, e));
1359 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1360 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1367 #endif /* USE_PAM */
1375 login_cap_t *lc = NULL;
1380 char *residue = NULL;
1383 if (logged_in || askpasswd == 0) {
1384 reply(503, "Login with USER first.");
1388 if (!guest) { /* "ftp" is only account allowed no password */
1390 rval = 1; /* failure below */
1394 rval = auth_pam(&pw, passwd);
1400 if (opieverify(&opiedata, passwd) == 0)
1401 xpasswd = pw->pw_passwd;
1403 xpasswd = crypt(passwd, pw->pw_passwd);
1404 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1410 rval = strcmp(pw->pw_passwd, xpasswd);
1411 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1412 rval = 1; /* failure */
1415 * If rval == 1, the user failed the authentication check
1416 * above. If rval == 0, either PAM or local authentication
1420 reply(530, "Login incorrect.");
1421 BLACKLIST_NOTIFY(BLACKLIST_AUTH_FAIL, STDIN_FILENO, "Login incorrect");
1424 "FTP LOGIN FAILED FROM %s",
1426 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1427 "FTP LOGIN FAILED FROM %s, %s",
1428 remotehost, curname);
1431 if (login_attempts++ >= 5) {
1433 "repeated login failures from %s",
1439 BLACKLIST_NOTIFY(BLACKLIST_AUTH_OK, STDIN_FILENO, "Login successful");
1442 login_attempts = 0; /* this time successful */
1443 if (setegid(pw->pw_gid) < 0) {
1444 reply(550, "Can't set gid.");
1447 /* May be overridden by login.conf */
1448 (void) umask(defumask);
1450 if ((lc = login_getpwclass(pw)) != NULL) {
1451 char remote_ip[NI_MAXHOST];
1453 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1454 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1457 remote_ip[sizeof(remote_ip) - 1] = 0;
1458 if (!auth_hostok(lc, remotehost, remote_ip)) {
1459 syslog(LOG_INFO|LOG_AUTH,
1460 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1462 reply(530, "Permission denied.");
1466 if (!auth_timeok(lc, time(NULL))) {
1467 reply(530, "Login not available right now.");
1472 setusercontext(lc, pw, 0, LOGIN_SETALL &
1473 ~(LOGIN_SETRESOURCES | LOGIN_SETUSER | LOGIN_SETPATH | LOGIN_SETENV));
1475 setlogin(pw->pw_name);
1476 (void) initgroups(pw->pw_name, pw->pw_gid);
1481 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1482 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1483 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1484 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1490 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue, &ecode)
1491 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1492 || login_getcapbool(lc, "ftp-chroot", 0)
1496 * It is possible that checkuser() failed to open the chroot file.
1497 * If this is the case, report that logins are un-available, since we
1498 * have no way of checking whether or not the user should be chrooted.
1499 * We ignore ENOENT since it is not required that this file be present.
1501 if (ecode != 0 && ecode != ENOENT) {
1502 reply(530, "Login not available right now.");
1507 /* Disable wtmp logging when chrooting. */
1508 if (dochroot || guest)
1511 ftpd_logwtmp(wtmpid, pw->pw_name,
1512 (struct sockaddr *)&his_addr);
1516 setusercontext(lc, pw, 0, LOGIN_SETRESOURCES);
1519 if (guest && stats && statfd < 0) {
1520 #ifdef VIRTUAL_HOSTING
1521 statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1523 statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1530 * For a chrooted local user,
1531 * a) see whether ftpchroot(5) specifies a chroot directory,
1532 * b) extract the directory pathname from the line,
1533 * c) expand it to the absolute pathname if necessary.
1535 if (dochroot && residue &&
1536 (chrootdir = strtok(residue, " \t")) != NULL) {
1537 if (chrootdir[0] != '/')
1538 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1540 chrootdir = strdup(chrootdir); /* make it permanent */
1541 if (chrootdir == NULL)
1542 fatalerror("Ran out of memory.");
1544 if (guest || dochroot) {
1546 * If no chroot directory set yet, use the login directory.
1547 * Copy it so it can be modified while pw->pw_dir stays intact.
1549 if (chrootdir == NULL &&
1550 (chrootdir = strdup(pw->pw_dir)) == NULL)
1551 fatalerror("Ran out of memory.");
1553 * Check for the "/chroot/./home" syntax,
1554 * separate the chroot and home directory pathnames.
1556 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1557 *(homedir++) = '\0'; /* wipe '/' */
1558 homedir++; /* skip '.' */
1561 * We MUST do a chdir() after the chroot. Otherwise
1562 * the old current directory will be accessible as "."
1563 * outside the new root!
1568 * Finally, do chroot()
1570 if (chroot(chrootdir) < 0) {
1571 reply(550, "Can't change root.");
1574 __FreeBSD_libc_enter_restricted_mode();
1575 } else /* real user w/o chroot */
1576 homedir = pw->pw_dir;
1578 * Set euid *before* doing chdir() so
1579 * a) the user won't be carried to a directory that he couldn't reach
1580 * on his own due to no permission to upper path components,
1581 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1582 * (uid 0 has no root power over NFS if not mapped explicitly.)
1584 if (seteuid(pw->pw_uid) < 0) {
1585 if (guest || dochroot) {
1586 fatalerror("Can't set uid.");
1588 reply(550, "Can't set uid.");
1593 * Do not allow the session to live if we're chroot()'ed and chdir()
1594 * fails. Otherwise the chroot jail can be escaped.
1596 if (chdir(homedir) < 0) {
1597 if (guest || dochroot) {
1598 fatalerror("Can't change to base directory.");
1600 if (chdir("/") < 0) {
1601 reply(550, "Root is inaccessible.");
1604 lreply(230, "No directory! Logging in with home=/.");
1609 * Display a login message, if it exists.
1610 * N.B. reply(230,) must follow the message.
1612 #ifdef VIRTUAL_HOSTING
1613 fd = fopen(thishost->loginmsg, "r");
1615 fd = fopen(_PATH_FTPLOGINMESG, "r");
1618 char *cp, line[LINE_MAX];
1620 while (fgets(line, sizeof(line), fd) != NULL) {
1621 if ((cp = strchr(line, '\n')) != NULL)
1623 lreply(230, "%s", line);
1625 (void) fflush(stdout);
1631 ident = strdup(passwd);
1633 fatalerror("Ran out of memory.");
1635 reply(230, "Guest login ok, access restrictions apply.");
1637 #ifdef VIRTUAL_HOSTING
1638 if (thishost != firsthost)
1639 snprintf(proctitle, sizeof(proctitle),
1640 "%s: anonymous(%s)/%s", remotehost, hostname,
1644 snprintf(proctitle, sizeof(proctitle),
1645 "%s: anonymous/%s", remotehost, passwd);
1646 setproctitle("%s", proctitle);
1647 #endif /* SETPROCTITLE */
1649 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1650 remotehost, passwd);
1653 reply(230, "User %s logged in, "
1654 "access restrictions apply.", pw->pw_name);
1656 reply(230, "User %s logged in.", pw->pw_name);
1659 snprintf(proctitle, sizeof(proctitle),
1660 "%s: user/%s", remotehost, pw->pw_name);
1661 setproctitle("%s", proctitle);
1662 #endif /* SETPROCTITLE */
1664 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1665 remotehost, pw->pw_name);
1667 if (logging && (guest || dochroot))
1668 syslog(LOG_INFO, "session root changed to %s", chrootdir);
1676 /* Forget all about it... */
1686 retrieve(char *cmd, char *name)
1690 int (*closefunc)(FILE *);
1695 fin = fopen(name, "r"), closefunc = fclose;
1698 (void) snprintf(line, sizeof(line), cmd, name);
1700 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1702 st.st_blksize = BUFSIZ;
1706 perror_reply(550, name);
1708 LOGCMD("get", name);
1715 if (fstat(fileno(fin), &st) < 0) {
1716 perror_reply(550, name);
1719 if (!S_ISREG(st.st_mode)) {
1721 * Never sending a raw directory is a workaround
1722 * for buggy clients that will attempt to RETR
1723 * a directory before listing it, e.g., Mozilla.
1724 * Preventing a guest from getting irregular files
1725 * is a simple security measure.
1727 if (S_ISDIR(st.st_mode) || guest) {
1728 reply(550, "%s: not a plain file.", name);
1732 /* st.st_blksize is set for all descriptor types */
1735 if (restart_point) {
1736 if (type == TYPE_A) {
1743 if ((c=getc(fin)) == EOF) {
1744 perror_reply(550, name);
1750 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1751 perror_reply(550, name);
1755 dout = dataconn(name, st.st_size, "w");
1759 send_data(fin, dout, st.st_blksize, st.st_size,
1760 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1761 if (cmd == 0 && guest && stats && byte_count > 0)
1762 logxfer(name, byte_count, start);
1763 (void) fclose(dout);
1768 LOGBYTES("get", name, byte_count);
1773 store(char *name, char *mode, int unique)
1777 int (*closefunc)(FILE *);
1779 if (*mode == 'a') { /* APPE */
1781 /* Programming error */
1782 syslog(LOG_ERR, "Internal: unique flag to APPE");
1785 if (guest && noguestmod) {
1786 reply(550, "Appending to existing file denied.");
1789 restart_point = 0; /* not affected by preceding REST */
1791 if (unique) /* STOU overrides REST */
1793 if (guest && noguestmod) {
1794 if (restart_point) { /* guest STOR w/REST */
1795 reply(550, "Modifying existing file denied.");
1797 } else /* treat guest STOR as STOU */
1802 mode = "r+"; /* so ASCII manual seek can work */
1804 if ((fd = guniquefd(name, &name)) < 0)
1806 fout = fdopen(fd, mode);
1808 fout = fopen(name, mode);
1811 perror_reply(553, name);
1815 if (restart_point) {
1816 if (type == TYPE_A) {
1823 if ((c=getc(fout)) == EOF) {
1824 perror_reply(550, name);
1831 * We must do this seek to "current" position
1832 * because we are changing from reading to
1835 if (fseeko(fout, 0, SEEK_CUR) < 0) {
1836 perror_reply(550, name);
1839 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1840 perror_reply(550, name);
1844 din = dataconn(name, -1, "r");
1847 if (receive_data(din, fout) == 0) {
1849 reply(226, "Transfer complete (unique file name:%s).",
1852 reply(226, "Transfer complete.");
1858 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1862 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1867 getdatasock(char *mode)
1869 int on = 1, s, t, tries;
1872 return (fdopen(data, mode));
1874 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1877 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1878 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1879 /* anchor socket to avoid multi-homing problems */
1880 data_source = ctrl_addr;
1881 data_source.su_port = htons(dataport);
1883 for (tries = 1; ; tries++) {
1885 * We should loop here since it's possible that
1886 * another ftpd instance has passed this point and is
1887 * trying to open a data connection in active mode now.
1888 * Until the other connection is opened, we'll be getting
1889 * EADDRINUSE because no SOCK_STREAM sockets in the system
1890 * can share both local and remote addresses, localIP:20
1891 * and *:* in this case.
1893 if (bind(s, (struct sockaddr *)&data_source,
1894 data_source.su_len) >= 0)
1896 if (errno != EADDRINUSE || tries > 10)
1900 (void) seteuid(pw->pw_uid);
1902 if (data_source.su_family == AF_INET)
1904 on = IPTOS_THROUGHPUT;
1905 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1906 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1911 * Turn off push flag to keep sender TCP from sending short packets
1912 * at the boundaries of each write().
1915 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1916 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1918 return (fdopen(s, mode));
1920 /* Return the real value of errno (close may change it) */
1922 (void) seteuid(pw->pw_uid);
1929 dataconn(char *name, off_t size, char *mode)
1933 int retry = 0, tos, conerrno;
1938 (void) snprintf(sizebuf, sizeof(sizebuf),
1939 " (%jd bytes)", (intmax_t)size);
1943 union sockunion from;
1944 socklen_t fromlen = ctrl_addr.su_len;
1946 struct timeval timeout;
1950 FD_SET(pdata, &set);
1952 timeout.tv_usec = 0;
1953 timeout.tv_sec = 120;
1956 * Granted a socket is in the blocking I/O mode,
1957 * accept() will block after a successful select()
1958 * if the selected connection dies in between.
1959 * Therefore set the non-blocking I/O flag here.
1961 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1962 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1964 if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
1965 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1967 (void) close(pdata);
1970 * Unset the inherited non-blocking I/O flag
1971 * on the child socket so stdio can work on it.
1973 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1974 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1977 if (from.su_family == AF_INET)
1979 tos = IPTOS_THROUGHPUT;
1980 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1981 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1984 reply(150, "Opening %s mode data connection for '%s'%s.",
1985 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1986 return (fdopen(pdata, mode));
1988 reply(425, "Can't open data connection.");
1989 (void) close(pdata);
1994 reply(125, "Using existing data connection for '%s'%s.",
1997 return (fdopen(data, mode));
2000 data_dest = his_addr;
2003 file = getdatasock(mode);
2005 char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
2007 if (getnameinfo((struct sockaddr *)&data_source,
2009 hostbuf, sizeof(hostbuf) - 1,
2010 portbuf, sizeof(portbuf) - 1,
2011 NI_NUMERICHOST|NI_NUMERICSERV))
2012 *hostbuf = *portbuf = 0;
2013 hostbuf[sizeof(hostbuf) - 1] = 0;
2014 portbuf[sizeof(portbuf) - 1] = 0;
2015 reply(425, "Can't create data socket (%s,%s): %s.",
2016 hostbuf, portbuf, strerror(errno));
2019 data = fileno(file);
2021 if (connect(data, (struct sockaddr *)&data_dest,
2022 data_dest.su_len) == 0)
2025 (void) fclose(file);
2027 if (conerrno == EADDRINUSE) {
2033 } while (retry <= swaitmax);
2034 if (conerrno != 0) {
2035 reply(425, "Can't build data connection: %s.",
2036 strerror(conerrno));
2039 reply(150, "Opening %s mode data connection for '%s'%s.",
2040 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2045 * A helper macro to avoid code duplication
2046 * in send_data() and receive_data().
2048 * XXX We have to block SIGURG during putc() because BSD stdio
2049 * is unable to restart interrupted write operations and hence
2050 * the entire buffer contents will be lost as soon as a write()
2051 * call indicates EINTR to stdio.
2053 #define FTPD_PUTC(ch, file, label) \
2059 ret = putc((ch), (file)); \
2061 CHECKOOB(return (-1)) \
2062 else if (ferror(file)) \
2065 } while (ret == EOF); \
2069 * Transfer the contents of "instr" to "outstr" peer using the appropriate
2070 * encapsulation of the data subject to Mode, Structure, and Type.
2072 * NB: Form isn't handled.
2075 send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2077 int c, cp, filefd, netfd;
2088 CHECKOOB(return (-1))
2089 else if (c == EOF && ferror(instr))
2092 if (ferror(instr)) { /* resume after OOB */
2096 if (feof(instr)) /* EOF */
2098 syslog(LOG_ERR, "Internal: impossible condition"
2099 " on file after getc()");
2102 if (c == '\n' && cp != '\r') {
2103 FTPD_PUTC('\r', outstr, data_err);
2106 FTPD_PUTC(c, outstr, data_err);
2110 #ifdef notyet /* BSD stdio isn't ready for that */
2111 while (fflush(outstr) == EOF) {
2112 CHECKOOB(return (-1))
2120 if (fflush(outstr) == EOF)
2123 reply(226, "Transfer complete.");
2129 * isreg is only set if we are not doing restart and we
2130 * are sending a regular file
2132 netfd = fileno(outstr);
2133 filefd = fileno(instr);
2136 char *msg = "Transfer complete.";
2142 while (filesize > 0) {
2143 err = sendfile(filefd, netfd, offset, 0,
2146 * Calculate byte_count before OOB processing.
2147 * It can be used in myoob() later.
2152 CHECKOOB(return (-1))
2153 else if (err == -1) {
2154 if (errno != EINTR &&
2155 cnt == 0 && offset == 0)
2159 if (err == -1) /* resume after OOB */
2162 * We hit the EOF prematurely.
2163 * Perhaps the file was externally truncated.
2166 msg = "Transfer finished due to "
2167 "premature end of file.";
2172 reply(226, "%s", msg);
2177 if ((buf = malloc(blksize)) == NULL) {
2179 reply(451, "Ran out of memory.");
2187 cnt = read(filefd, buf, blksize);
2188 CHECKOOB(free(buf); return (-1))
2193 if (cnt < 0) /* resume after OOB */
2195 if (cnt == 0) /* EOF */
2197 for (len = cnt, bp = buf; len > 0;) {
2198 cnt = write(netfd, bp, len);
2199 CHECKOOB(free(buf); return (-1))
2213 reply(226, "Transfer complete.");
2217 reply(550, "Unimplemented TYPE %d in send_data.", type);
2223 perror_reply(426, "Data connection");
2228 perror_reply(551, "Error on input file");
2233 * Transfer data from peer to "outstr" using the appropriate encapulation of
2234 * the data subject to Mode, Structure, and Type.
2236 * N.B.: Form isn't handled.
2239 receive_data(FILE *instr, FILE *outstr)
2255 cnt = read(fileno(instr), buf, sizeof(buf));
2256 CHECKOOB(return (-1))
2259 if (cnt < 0) /* resume after OOB */
2261 if (cnt == 0) /* EOF */
2263 for (len = cnt, bp = buf; len > 0;) {
2264 cnt = write(fileno(outstr), bp, len);
2265 CHECKOOB(return (-1))
2280 reply(553, "TYPE E not implemented.");
2287 CHECKOOB(return (-1))
2288 else if (c == EOF && ferror(instr))
2290 if (c == EOF && ferror(instr)) { /* resume after OOB */
2297 FTPD_PUTC('\r', outstr, file_err);
2307 /* Check for EOF here in order not to lose last \r. */
2309 if (feof(instr)) /* EOF */
2311 syslog(LOG_ERR, "Internal: impossible condition"
2312 " on data stream after getc()");
2317 FTPD_PUTC(c, outstr, file_err);
2320 #ifdef notyet /* BSD stdio isn't ready for that */
2321 while (fflush(outstr) == EOF) {
2322 CHECKOOB(return (-1))
2330 if (fflush(outstr) == EOF)
2335 "WARNING! %d bare linefeeds received in ASCII mode.",
2337 (void)printf(" File may not have transferred correctly.\r\n");
2342 reply(550, "Unimplemented TYPE %d in receive_data.", type);
2348 perror_reply(426, "Data connection");
2353 perror_reply(452, "Error writing to file");
2358 statfilecmd(char *filename)
2363 char line[LINE_MAX];
2366 code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2367 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2368 fin = ftpd_popen(line, "r");
2370 perror_reply(551, filename);
2373 lreply(code, "Status of %s:", filename);
2375 while ((c = getc(fin)) != EOF) {
2377 if (ferror(stdout)){
2378 perror_reply(421, "Control connection");
2379 (void) ftpd_pclose(fin);
2384 perror_reply(551, filename);
2385 (void) ftpd_pclose(fin);
2388 (void) putc('\r', stdout);
2391 * RFC 959 says neutral text should be prepended before
2392 * a leading 3-digit number followed by whitespace, but
2393 * many ftp clients can be confused by any leading digits,
2394 * as a matter of fact.
2396 if (atstart && isdigit(c))
2397 (void) putc(' ', stdout);
2398 (void) putc(c, stdout);
2399 atstart = (c == '\n');
2401 (void) ftpd_pclose(fin);
2402 reply(code, "End of status.");
2408 union sockunion *su;
2410 char hname[NI_MAXHOST];
2414 lreply(211, "%s FTP server status:", hostname);
2415 printf(" %s\r\n", version);
2417 lreply(211, "FTP server status:");
2418 printf(" Connected to %s", remotehost);
2419 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2420 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2421 hname[sizeof(hname) - 1] = 0;
2422 if (strcmp(hname, remotehost) != 0)
2423 printf(" (%s)", hname);
2428 printf(" Logged in anonymously\r\n");
2430 printf(" Logged in as %s\r\n", pw->pw_name);
2431 } else if (askpasswd)
2432 printf(" Waiting for password\r\n");
2434 printf(" Waiting for user name\r\n");
2435 printf(" TYPE: %s", typenames[type]);
2436 if (type == TYPE_A || type == TYPE_E)
2437 printf(", FORM: %s", formnames[form]);
2440 printf(" %d", CHAR_BIT);
2442 printf(" %d", bytesize); /* need definition! */
2444 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2445 strunames[stru], modenames[mode]);
2447 printf(" Data connection open\r\n");
2448 else if (pdata != -1) {
2452 } else if (usedefault == 0) {
2456 #define UC(b) (((int) b) & 0xff)
2458 printf(" EPSV only mode (EPSV ALL)\r\n");
2463 if (su->su_family == AF_INET) {
2464 a = (u_char *) &su->su_sin.sin_addr;
2465 p = (u_char *) &su->su_sin.sin_port;
2466 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2467 ispassive ? "PASV" : "PORT",
2468 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2469 UC(p[0]), UC(p[1]));
2476 switch (su->su_family) {
2478 a = (u_char *) &su->su_sin.sin_addr;
2479 p = (u_char *) &su->su_sin.sin_port;
2480 alen = sizeof(su->su_sin.sin_addr);
2484 a = (u_char *) &su->su_sin6.sin6_addr;
2485 p = (u_char *) &su->su_sin6.sin6_port;
2486 alen = sizeof(su->su_sin6.sin6_addr);
2494 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2496 for (i = 0; i < alen; i++)
2497 printf("%d,", UC(a[i]));
2498 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2507 switch (su->su_family) {
2519 union sockunion tmp;
2522 if (tmp.su_family == AF_INET6)
2523 tmp.su_sin6.sin6_scope_id = 0;
2524 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2525 hname, sizeof(hname) - 1, NULL, 0,
2527 hname[sizeof(hname) - 1] = 0;
2528 printf(" %s |%d|%s|%d|\r\n",
2529 ispassive ? "EPSV" : "EPRT",
2530 af, hname, htons(tmp.su_port));
2536 printf(" No data connection\r\n");
2537 reply(211, "End of status.");
2544 reply(451, "Error in server: %s", s);
2545 reply(221, "Closing connection due to server error.");
2551 reply(int n, const char *fmt, ...)
2555 (void)printf("%d ", n);
2557 (void)vprintf(fmt, ap);
2559 (void)printf("\r\n");
2560 (void)fflush(stdout);
2562 syslog(LOG_DEBUG, "<--- %d ", n);
2564 vsyslog(LOG_DEBUG, fmt, ap);
2570 lreply(int n, const char *fmt, ...)
2574 (void)printf("%d- ", n);
2576 (void)vprintf(fmt, ap);
2578 (void)printf("\r\n");
2579 (void)fflush(stdout);
2581 syslog(LOG_DEBUG, "<--- %d- ", n);
2583 vsyslog(LOG_DEBUG, fmt, ap);
2592 reply(250, "%s command successful.", s);
2599 reply(502, "%s command not implemented.", s);
2608 if ((cp = strchr(cbuf,'\n')))
2610 reply(500, "%s: command not understood.", cbuf);
2618 LOGCMD("delete", name);
2619 if (lstat(name, &st) < 0) {
2620 perror_reply(550, name);
2623 if (S_ISDIR(st.st_mode)) {
2624 if (rmdir(name) < 0) {
2625 perror_reply(550, name);
2630 if (guest && noguestmod) {
2631 reply(550, "Operation not permitted.");
2634 if (unlink(name) < 0) {
2635 perror_reply(550, name);
2646 if (chdir(path) < 0)
2647 perror_reply(550, path);
2657 LOGCMD("mkdir", name);
2658 if (guest && noguestmkd)
2659 reply(550, "Operation not permitted.");
2660 else if (mkdir(name, 0777) < 0)
2661 perror_reply(550, name);
2663 if ((s = doublequote(name)) == NULL)
2664 fatalerror("Ran out of memory.");
2665 reply(257, "\"%s\" directory created.", s);
2671 removedir(char *name)
2674 LOGCMD("rmdir", name);
2675 if (rmdir(name) < 0)
2676 perror_reply(550, name);
2684 char *s, path[MAXPATHLEN + 1];
2686 if (getcwd(path, sizeof(path)) == NULL)
2687 perror_reply(550, "Get current directory");
2689 if ((s = doublequote(path)) == NULL)
2690 fatalerror("Ran out of memory.");
2691 reply(257, "\"%s\" is current directory.", s);
2697 renamefrom(char *name)
2701 if (guest && noguestmod) {
2702 reply(550, "Operation not permitted.");
2705 if (lstat(name, &st) < 0) {
2706 perror_reply(550, name);
2709 reply(350, "File exists, ready for destination name.");
2714 renamecmd(char *from, char *to)
2718 LOGCMD2("rename", from, to);
2720 if (guest && (stat(to, &st) == 0)) {
2721 reply(550, "%s: permission denied.", to);
2725 if (rename(from, to) < 0)
2726 perror_reply(550, "rename");
2732 dolog(struct sockaddr *who)
2734 char who_name[NI_MAXHOST];
2736 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2737 remotehost[sizeof(remotehost) - 1] = 0;
2738 if (getnameinfo(who, who->sa_len,
2739 who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
2741 who_name[sizeof(who_name) - 1] = 0;
2744 #ifdef VIRTUAL_HOSTING
2745 if (thishost != firsthost)
2746 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2747 remotehost, hostname);
2750 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2752 setproctitle("%s", proctitle);
2753 #endif /* SETPROCTITLE */
2756 #ifdef VIRTUAL_HOSTING
2757 if (thishost != firsthost)
2758 syslog(LOG_INFO, "connection from %s (%s) to %s",
2759 remotehost, who_name, hostname);
2762 syslog(LOG_INFO, "connection from %s (%s)",
2763 remotehost, who_name);
2768 * Record logout in wtmp file
2769 * and exit with supplied status.
2772 dologout(int status)
2775 if (logged_in && dowtmp) {
2778 setusercontext(NULL, getpwuid(0), 0, LOGIN_SETALL & ~(LOGIN_SETLOGIN |
2779 LOGIN_SETUSER | LOGIN_SETGROUP | LOGIN_SETPATH |
2782 ftpd_logwtmp(wtmpid, NULL, NULL);
2784 /* beware of flushing buffers after a SIGPIPE */
2802 syslog(LOG_ERR, "Internal: maskurg() while no transfer");
2807 sigaddset(&sset, SIGURG);
2808 sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
2818 syslog(LOG_ERR, "Internal: flagxfer(1): "
2819 "transfer already under way");
2825 syslog(LOG_ERR, "Internal: flagxfer(0): "
2826 "no active transfer");
2833 * Returns 0 if OK to resume or -1 if abort requested.
2842 syslog(LOG_ERR, "Internal: myoob() while no transfer");
2846 ret = get_line(cp, 7, stdin);
2848 reply(221, "You could at least say goodbye.");
2850 } else if (ret == -2) {
2851 /* Ignore truncated command. */
2855 if (strcmp(cp, "ABOR\r\n") == 0) {
2857 reply(426, "Transfer aborted. Data connection closed.");
2858 reply(226, "Abort successful.");
2861 if (strcmp(cp, "STAT\r\n") == 0) {
2863 if (file_size != -1)
2864 reply(213, "Status: %jd of %jd bytes transferred.",
2865 (intmax_t)byte_count, (intmax_t)file_size);
2867 reply(213, "Status: %jd bytes transferred.",
2868 (intmax_t)byte_count);
2874 * Note: a response of 425 is not mentioned as a possible response to
2875 * the PASV command in RFC959. However, it has been blessed as
2876 * a legitimate response by Jon Postel in a telephone conversation
2877 * with Rick Adams on 25 Jan 89.
2886 if (pdata >= 0) /* close old port if one set */
2889 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2891 perror_reply(425, "Can't open passive connection");
2895 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2896 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2901 if (ctrl_addr.su_family == AF_INET) {
2902 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2903 : IP_PORTRANGE_DEFAULT;
2905 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2906 &on, sizeof(on)) < 0)
2910 #ifdef IPV6_PORTRANGE
2911 if (ctrl_addr.su_family == AF_INET6) {
2912 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2913 : IPV6_PORTRANGE_DEFAULT;
2915 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2916 &on, sizeof(on)) < 0)
2921 pasv_addr = ctrl_addr;
2922 pasv_addr.su_port = 0;
2923 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2926 (void) seteuid(pw->pw_uid);
2928 len = sizeof(pasv_addr);
2929 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2931 if (listen(pdata, 1) < 0)
2933 if (pasv_addr.su_family == AF_INET)
2934 a = (char *) &pasv_addr.su_sin.sin_addr;
2935 else if (pasv_addr.su_family == AF_INET6 &&
2936 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2937 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2941 p = (char *) &pasv_addr.su_port;
2943 #define UC(b) (((int) b) & 0xff)
2945 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2946 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2950 (void) seteuid(pw->pw_uid);
2951 (void) close(pdata);
2953 perror_reply(425, "Can't open passive connection");
2958 * Long Passive defined in RFC 1639.
2959 * 228 Entering Long Passive Mode
2960 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2964 long_passive(char *cmd, int pf)
2970 if (pdata >= 0) /* close old port if one set */
2973 if (pf != PF_UNSPEC) {
2974 if (ctrl_addr.su_family != pf) {
2975 switch (ctrl_addr.su_family) {
2988 * only EPRT/EPSV ready clients will understand this
2990 if (strcmp(cmd, "EPSV") == 0 && pf) {
2991 reply(522, "Network protocol mismatch, "
2994 reply(501, "Network protocol mismatch."); /*XXX*/
3000 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
3002 perror_reply(425, "Can't open passive connection");
3006 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
3007 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
3011 pasv_addr = ctrl_addr;
3012 pasv_addr.su_port = 0;
3013 len = pasv_addr.su_len;
3016 if (ctrl_addr.su_family == AF_INET) {
3017 on = restricted_data_ports ? IP_PORTRANGE_HIGH
3018 : IP_PORTRANGE_DEFAULT;
3020 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
3021 &on, sizeof(on)) < 0)
3025 #ifdef IPV6_PORTRANGE
3026 if (ctrl_addr.su_family == AF_INET6) {
3027 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
3028 : IPV6_PORTRANGE_DEFAULT;
3030 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
3031 &on, sizeof(on)) < 0)
3036 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
3039 (void) seteuid(pw->pw_uid);
3041 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
3043 if (listen(pdata, 1) < 0)
3046 #define UC(b) (((int) b) & 0xff)
3048 if (strcmp(cmd, "LPSV") == 0) {
3049 p = (char *)&pasv_addr.su_port;
3050 switch (pasv_addr.su_family) {
3052 a = (char *) &pasv_addr.su_sin.sin_addr;
3055 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3056 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3057 2, UC(p[0]), UC(p[1]));
3060 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
3061 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
3064 a = (char *) &pasv_addr.su_sin6.sin6_addr;
3066 "Entering Long Passive Mode "
3067 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3068 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3069 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3070 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3071 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3072 2, UC(p[0]), UC(p[1]));
3075 } else if (strcmp(cmd, "EPSV") == 0) {
3076 switch (pasv_addr.su_family) {
3079 reply(229, "Entering Extended Passive Mode (|||%d|)",
3080 ntohs(pasv_addr.su_port));
3084 /* more proper error code? */
3088 (void) seteuid(pw->pw_uid);
3089 (void) close(pdata);
3091 perror_reply(425, "Can't open passive connection");
3096 * Generate unique name for file with basename "local"
3097 * and open the file in order to avoid possible races.
3098 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3099 * Return descriptor to the file, set "name" to its name.
3101 * Generates failure reply on error.
3104 guniquefd(char *local, char **name)
3106 static char new[MAXPATHLEN];
3112 cp = strrchr(local, '/');
3115 if (stat(cp ? local : ".", &st) < 0) {
3116 perror_reply(553, cp ? local : ".");
3121 * Let not overwrite dirname with counter suffix.
3123 * In this extreme case dot won't be put in front of suffix.
3125 if (strlen(local) > sizeof(new) - 4) {
3126 reply(553, "Pathname too long.");
3131 /* -4 is for the .nn<null> we put on the end below */
3132 (void) snprintf(new, sizeof(new) - 4, "%s", local);
3133 cp = new + strlen(new);
3135 * Don't generate dotfile unless requested explicitly.
3136 * This covers the case when basename gets truncated off
3139 if (cp > new && cp[-1] != '/')
3141 for (count = 0; count < 100; count++) {
3142 /* At count 0 try unmodified name */
3144 (void)sprintf(cp, "%d", count);
3145 if ((fd = open(count ? new : local,
3146 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3147 *name = count ? new : local;
3150 if (errno != EEXIST) {
3151 perror_reply(553, count ? new : local);
3155 reply(452, "Unique file name cannot be created.");
3160 * Format and send reply containing system error number.
3163 perror_reply(int code, char *string)
3166 reply(code, "%s: %s.", string, strerror(errno));
3169 static char *onefile[] = {
3175 send_file_list(char *whichf)
3181 char **dirlist, *dirname;
3186 if (strpbrk(whichf, "~{[*?") != NULL) {
3187 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3189 memset(&gl, 0, sizeof(gl));
3190 gl.gl_matchc = MAXGLOBARGS;
3191 flags |= GLOB_LIMIT;
3193 if (glob(whichf, flags, 0, &gl)) {
3194 reply(550, "No matching files found.");
3196 } else if (gl.gl_pathc == 0) {
3198 perror_reply(550, whichf);
3201 dirlist = gl.gl_pathv;
3203 onefile[0] = whichf;
3208 while ((dirname = *dirlist++)) {
3209 if (stat(dirname, &st) < 0) {
3211 * If user typed "ls -l", etc, and the client
3212 * used NLST, do what the user meant.
3214 if (dirname[0] == '-' && *dirlist == NULL &&
3216 retrieve(_PATH_LS " %s", dirname);
3218 perror_reply(550, whichf);
3222 if (S_ISREG(st.st_mode)) {
3224 dout = dataconn("file list", -1, "w");
3230 fprintf(dout, "%s%s\n", dirname,
3231 type == TYPE_A ? "\r" : "");
3235 byte_count += strlen(dirname) +
3236 (type == TYPE_A ? 2 : 1);
3237 CHECKOOB(goto abrt);
3239 } else if (!S_ISDIR(st.st_mode))
3242 if ((dirp = opendir(dirname)) == NULL)
3245 while ((dir = readdir(dirp)) != NULL) {
3246 char nbuf[MAXPATHLEN];
3248 CHECKOOB(goto abrt);
3250 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
3252 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3256 snprintf(nbuf, sizeof(nbuf),
3257 "%s/%s", dirname, dir->d_name);
3260 * We have to do a stat to insure it's
3261 * not a directory or special file.
3263 if (simple || (stat(nbuf, &st) == 0 &&
3264 S_ISREG(st.st_mode))) {
3266 dout = dataconn("file list", -1, "w");
3272 if (nbuf[0] == '.' && nbuf[1] == '/')
3273 fprintf(dout, "%s%s\n", &nbuf[2],
3274 type == TYPE_A ? "\r" : "");
3276 fprintf(dout, "%s%s\n", nbuf,
3277 type == TYPE_A ? "\r" : "");
3281 byte_count += strlen(nbuf) +
3282 (type == TYPE_A ? 2 : 1);
3283 CHECKOOB(goto abrt);
3286 (void) closedir(dirp);
3291 reply(550, "No files found.");
3292 else if (ferror(dout))
3293 data_err: perror_reply(550, "Data connection");
3295 reply(226, "Transfer complete.");
3300 (void) fclose(dout);
3305 (void) closedir(dirp);
3313 reapchild(int signo)
3315 while (waitpid(-1, NULL, WNOHANG) > 0);
3319 appendf(char **strp, char *fmt, ...)
3325 vasprintf(&p, fmt, ap);
3328 fatalerror("Ran out of memory.");
3333 asprintf(strp, "%s%s", ostr, p);
3335 fatalerror("Ran out of memory.");
3341 logcmd(char *cmd, char *file1, char *file2, off_t cnt)
3344 char wd[MAXPATHLEN + 1];
3349 if (getcwd(wd, sizeof(wd) - 1) == NULL)
3350 strcpy(wd, strerror(errno));
3352 appendf(&msg, "%s", cmd);
3354 appendf(&msg, " %s", file1);
3356 appendf(&msg, " %s", file2);
3358 appendf(&msg, " = %jd bytes", (intmax_t)cnt);
3359 appendf(&msg, " (wd: %s", wd);
3360 if (guest || dochroot)
3361 appendf(&msg, "; chrooted");
3363 syslog(LOG_INFO, "%s", msg);
3368 logxfer(char *name, off_t size, time_t start)
3370 char buf[MAXPATHLEN + 1024];
3371 char path[MAXPATHLEN + 1];
3376 if (realpath(name, path) == NULL) {
3377 syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
3380 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n",
3381 ctime(&now)+4, ident, remotehost,
3382 path, (intmax_t)size,
3383 (long)(now - start + (now == start)));
3384 write(statfd, buf, strlen(buf));
3389 doublequote(char *s)
3394 for (p = s, n = 0; *p; p++)
3398 if ((s2 = malloc(p - s + n + 1)) == NULL)
3401 for (p = s2; *s; s++, p++) {
3402 if ((*p = *s) == '"')
3410 /* setup server socket for specified address family */
3411 /* if af is PF_UNSPEC more than one socket may be returned */
3412 /* the returned list is dynamically allocated, so caller needs to free it */
3414 socksetup(int af, char *bindname, const char *bindport)
3416 struct addrinfo hints, *res, *r;
3417 int error, maxs, *s, *socks;
3420 memset(&hints, 0, sizeof(hints));
3421 hints.ai_flags = AI_PASSIVE;
3422 hints.ai_family = af;
3423 hints.ai_socktype = SOCK_STREAM;
3424 error = getaddrinfo(bindname, bindport, &hints, &res);
3426 syslog(LOG_ERR, "%s", gai_strerror(error));
3427 if (error == EAI_SYSTEM)
3428 syslog(LOG_ERR, "%s", strerror(errno));
3432 /* Count max number of sockets we may open */
3433 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3435 socks = malloc((maxs + 1) * sizeof(int));
3438 syslog(LOG_ERR, "couldn't allocate memory for sockets");
3442 *socks = 0; /* num of sockets counter at start of array */
3444 for (r = res; r; r = r->ai_next) {
3445 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3447 syslog(LOG_DEBUG, "control socket: %m");
3450 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3451 &on, sizeof(on)) < 0)
3453 "control setsockopt (SO_REUSEADDR): %m");
3454 if (r->ai_family == AF_INET6) {
3455 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3456 &on, sizeof(on)) < 0)
3458 "control setsockopt (IPV6_V6ONLY): %m");
3460 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3461 syslog(LOG_DEBUG, "control bind: %m");
3473 syslog(LOG_ERR, "control socket: Couldn't bind to any socket");