2 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 static char copyright[] =
37 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
38 The Regents of the University of California. All rights reserved.\n";
44 static char sccsid[] = "@(#)ftpd.c 8.4 (Berkeley) 4/16/94";
48 #include <sys/cdefs.h>
49 __FBSDID("$FreeBSD$");
54 #include <sys/param.h>
55 #include <sys/ioctl.h>
57 #include <sys/socket.h>
62 #include <netinet/in.h>
63 #include <netinet/in_systm.h>
64 #include <netinet/ip.h>
65 #include <netinet/tcp.h>
69 #include <arpa/inet.h>
70 #include <arpa/telnet.h>
93 #include <login_cap.h>
97 #include <security/pam_appl.h>
100 #include "pathnames.h"
105 static char version[] = "Version 6.00LS";
108 extern off_t restart_point;
111 union sockunion ctrl_addr;
112 union sockunion data_source;
113 union sockunion data_dest;
114 union sockunion his_addr;
115 union sockunion pasv_addr;
120 int hostinfo = 1; /* print host-specific info in messages */
125 int timeout = 900; /* timeout after 15 minutes of inactivity */
126 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
128 int restricted_data_ports = 1;
129 int paranoid = 1; /* be extra careful about security */
130 int anon_only = 0; /* Only anonymous ftp allowed */
139 int stru; /* avoid C keyword */
141 int usedefault = 1; /* for data transfers */
142 int pdata = -1; /* for passive mode */
143 int readonly = 0; /* Server is in readonly mode. */
144 int noepsv = 0; /* EPSV command is disabled. */
145 int noretr = 0; /* RETR command is disabled. */
146 int noguestretr = 0; /* RETR command is disabled for anon users. */
147 int noguestmkd = 0; /* MKD command is disabled for anon users. */
148 int noguestmod = 1; /* anon users may not modify existing files. */
152 #if !defined(CMASK) || CMASK == 0
156 int defumask = CMASK; /* default umask value */
161 #ifdef VIRTUAL_HOSTING
164 static struct ftphost {
165 struct ftphost *next;
166 struct addrinfo *hostinfo;
172 } *thishost, *firsthost;
175 char remotehost[NI_MAXHOST];
178 static char ttyline[20];
179 char *tty = ttyline; /* for klogin */
182 static int auth_pam(struct passwd**, const char*);
183 pam_handle_t *pamh = NULL;
186 static struct opie opiedata;
187 static char opieprompt[OPIE_CHALLENGE_MAX+1];
190 char *pid_file = NULL; /* means default location to pidfile(3) */
193 * Limit number of pathnames that glob can return.
194 * A limit of 0 indicates the number of pathnames is unlimited.
196 #define MAXGLOBARGS 16384
200 * Timeout intervals for retrying connections
201 * to hosts that don't accept PORT cmds. This
202 * is a kludge, but given the problems with TCP...
204 #define SWAITMAX 90 /* wait at most 90 seconds */
205 #define SWAITINT 5 /* interval between retries */
207 int swaitmax = SWAITMAX;
208 int swaitint = SWAITINT;
211 #ifdef OLD_SETPROCTITLE
212 char **Argv = NULL; /* pointer to argument vector */
213 char *LastArgv = NULL; /* end of argv */
214 #endif /* OLD_SETPROCTITLE */
215 char proctitle[LINE_MAX]; /* initial part of title */
216 #endif /* SETPROCTITLE */
218 #define LOGCMD(cmd, file) logcmd((cmd), (file), NULL, -1)
219 #define LOGCMD2(cmd, file1, file2) logcmd((cmd), (file1), (file2), -1)
220 #define LOGBYTES(cmd, file, cnt) logcmd((cmd), (file), NULL, (cnt))
222 static volatile sig_atomic_t recvurg;
223 static int transflag; /* NB: for debugging only */
225 #define STARTXFER flagxfer(1)
226 #define ENDXFER flagxfer(0)
228 #define START_UNSAFE maskurg(1)
229 #define END_UNSAFE maskurg(0)
231 /* It's OK to put an `else' clause after this macro. */
232 #define CHECKOOB(action) \
241 #ifdef VIRTUAL_HOSTING
242 static void inithosts(int);
243 static void selecthost(union sockunion *);
245 static void ack(char *);
246 static void sigurg(int);
247 static void maskurg(int);
248 static void flagxfer(int);
249 static int myoob(void);
250 static int checkuser(char *, char *, int, char **);
251 static FILE *dataconn(char *, off_t, char *);
252 static void dolog(struct sockaddr *);
253 static void end_login(void);
254 static FILE *getdatasock(char *);
255 static int guniquefd(char *, char **);
256 static void lostconn(int);
257 static void sigquit(int);
258 static int receive_data(FILE *, FILE *);
259 static int send_data(FILE *, FILE *, size_t, off_t, int);
260 static struct passwd *
262 static char *sgetsave(char *);
263 static void reapchild(int);
264 static void appendf(char **, char *, ...) __printflike(2, 3);
265 static void logcmd(char *, char *, char *, off_t);
266 static void logxfer(char *, off_t, time_t);
267 static char *doublequote(char *);
268 static int *socksetup(int, char *, const char *);
271 main(int argc, char *argv[], char **envp)
275 char *cp, line[LINE_MAX];
277 char *bindname = NULL;
278 const char *bindport = "ftp";
279 int family = AF_UNSPEC;
282 tzset(); /* in case no timezone database in ~ftp */
283 sigemptyset(&sa.sa_mask);
284 sa.sa_flags = SA_RESTART;
286 #ifdef OLD_SETPROCTITLE
288 * Save start and extent of argv for setproctitle.
293 LastArgv = envp[-1] + strlen(envp[-1]);
294 #endif /* OLD_SETPROCTITLE */
297 * Prevent diagnostic messages from appearing on stderr.
298 * We run as a daemon or from inetd; in both cases, there's
299 * more reason in logging to syslog.
301 (void) freopen(_PATH_DEVNULL, "w", stderr);
305 * LOG_NDELAY sets up the logging connection immediately,
306 * necessary for anonymous ftp's that chroot and can't do it later.
308 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
310 while ((ch = getopt(argc, argv,
311 "46a:AdDEhlmMoOp:P:rRSt:T:u:UvW")) != -1) {
314 family = (family == AF_INET6) ? AF_UNSPEC : AF_INET;
318 family = (family == AF_INET) ? AF_UNSPEC : AF_INET6;
346 logging++; /* > 1 == extra logging */
386 timeout = atoi(optarg);
387 if (maxtimeout < timeout)
388 maxtimeout = timeout;
392 maxtimeout = atoi(optarg);
393 if (timeout > maxtimeout)
394 timeout = maxtimeout;
401 val = strtol(optarg, &optarg, 8);
402 if (*optarg != '\0' || val < 0)
403 syslog(LOG_WARNING, "bad value for -u");
409 restricted_data_ports = 0;
421 syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
427 int *ctl_sock, fd, maxfd = -1, nfds, i;
428 fd_set defreadfds, readfds;
432 if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
433 if (errno == EEXIST) {
434 syslog(LOG_ERR, "%s already running, pid %d",
435 getprogname(), (int)pid);
438 syslog(LOG_WARNING, "pidfile_open: %m");
442 * Detach from parent.
444 if (daemon(1, 1) < 0) {
445 syslog(LOG_ERR, "failed to become a daemon");
449 if (pfh != NULL && pidfile_write(pfh) == -1)
450 syslog(LOG_WARNING, "pidfile_write: %m");
452 sa.sa_handler = reapchild;
453 (void)sigaction(SIGCHLD, &sa, NULL);
455 #ifdef VIRTUAL_HOSTING
460 * Open a socket, bind it to the FTP port, and start
463 ctl_sock = socksetup(family, bindname, bindport);
464 if (ctl_sock == NULL)
467 FD_ZERO(&defreadfds);
468 for (i = 1; i <= *ctl_sock; i++) {
469 FD_SET(ctl_sock[i], &defreadfds);
470 if (listen(ctl_sock[i], 32) < 0) {
471 syslog(LOG_ERR, "control listen: %m");
474 if (maxfd < ctl_sock[i])
479 * Loop forever accepting connection requests and forking off
480 * children to handle them.
483 FD_COPY(&defreadfds, &readfds);
484 nfds = select(maxfd + 1, &readfds, NULL, NULL, 0);
486 if (nfds < 0 && errno != EINTR)
487 syslog(LOG_WARNING, "select: %m");
492 for (i = 1; i <= *ctl_sock; i++)
493 if (FD_ISSET(ctl_sock[i], &readfds)) {
494 addrlen = sizeof(his_addr);
495 fd = accept(ctl_sock[i],
496 (struct sockaddr *)&his_addr,
503 switch (pid = fork()) {
509 for (i = 1; i <= *ctl_sock; i++)
515 syslog(LOG_WARNING, "fork: %m");
523 addrlen = sizeof(his_addr);
524 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
525 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
529 #ifdef VIRTUAL_HOSTING
530 if (his_addr.su_family == AF_INET6 &&
531 IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))
534 family = his_addr.su_family;
540 sa.sa_handler = SIG_DFL;
541 (void)sigaction(SIGCHLD, &sa, NULL);
543 sa.sa_handler = sigurg;
544 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
545 (void)sigaction(SIGURG, &sa, NULL);
547 sigfillset(&sa.sa_mask); /* block all signals in handler */
548 sa.sa_flags = SA_RESTART;
549 sa.sa_handler = sigquit;
550 (void)sigaction(SIGHUP, &sa, NULL);
551 (void)sigaction(SIGINT, &sa, NULL);
552 (void)sigaction(SIGQUIT, &sa, NULL);
553 (void)sigaction(SIGTERM, &sa, NULL);
555 sa.sa_handler = lostconn;
556 (void)sigaction(SIGPIPE, &sa, NULL);
558 addrlen = sizeof(ctrl_addr);
559 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
560 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
563 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
564 #ifdef VIRTUAL_HOSTING
565 /* select our identity from virtual host table */
566 selecthost(&ctrl_addr);
569 if (ctrl_addr.su_family == AF_INET)
571 tos = IPTOS_LOWDELAY;
572 if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
573 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
577 * Disable Nagle on the control channel so that we don't have to wait
578 * for peer's ACK before issuing our next reply.
580 if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
581 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
583 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
585 /* set this here so klogin can use it... */
586 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
588 /* Try to handle urgent data inline */
590 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
591 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
595 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
596 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
598 dolog((struct sockaddr *)&his_addr);
600 * Set up default state
609 /* If logins are disabled, print out the message. */
610 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
611 while (fgets(line, sizeof(line), fd) != NULL) {
612 if ((cp = strchr(line, '\n')) != NULL)
614 lreply(530, "%s", line);
616 (void) fflush(stdout);
618 reply(530, "System not available.");
621 #ifdef VIRTUAL_HOSTING
622 fd = fopen(thishost->welcome, "r");
624 fd = fopen(_PATH_FTPWELCOME, "r");
627 while (fgets(line, sizeof(line), fd) != NULL) {
628 if ((cp = strchr(line, '\n')) != NULL)
630 lreply(220, "%s", line);
632 (void) fflush(stdout);
634 /* reply(220,) must follow */
636 #ifndef VIRTUAL_HOSTING
637 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
638 fatalerror("Ran out of memory.");
639 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
641 hostname[MAXHOSTNAMELEN - 1] = '\0';
644 reply(220, "%s FTP server (%s) ready.", hostname, version);
646 reply(220, "FTP server ready.");
657 syslog(LOG_DEBUG, "lost connection");
665 syslog(LOG_ERR, "got signal %d", signo);
669 #ifdef VIRTUAL_HOSTING
671 * read in virtual host tables (if they exist)
675 inithosts(int family)
680 char *cp, *mp, *line;
682 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
683 struct ftphost *hrp, *lhrp;
684 struct addrinfo hints, *res, *ai;
687 * Fill in the default host information
689 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
690 fatalerror("Ran out of memory.");
691 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
693 hostname[MAXHOSTNAMELEN - 1] = '\0';
694 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
695 fatalerror("Ran out of memory.");
696 hrp->hostname = hostname;
697 hrp->hostinfo = NULL;
699 memset(&hints, 0, sizeof(hints));
700 hints.ai_flags = AI_PASSIVE;
701 hints.ai_family = family;
702 hints.ai_socktype = SOCK_STREAM;
703 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
705 hrp->statfile = _PATH_FTPDSTATFILE;
706 hrp->welcome = _PATH_FTPWELCOME;
707 hrp->loginmsg = _PATH_FTPLOGINMESG;
708 hrp->anonuser = "ftp";
710 thishost = firsthost = lhrp = hrp;
711 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
712 int addrsize, gothost;
716 while ((line = fgetln(fp, &len)) != NULL) {
722 if (line[len - 1] == '\n') {
723 line[len - 1] = '\0';
726 if ((mp = malloc(len + 1)) == NULL)
727 fatalerror("Ran out of memory.");
728 memcpy(mp, line, len);
732 cp = strtok(line, " \t");
733 /* skip empty lines */
740 statfile = _PATH_FTPDSTATFILE;
741 welcome = _PATH_FTPWELCOME;
742 loginmsg = _PATH_FTPLOGINMESG;
745 * Preparse the line so we can use its info
746 * for all the addresses associated with
747 * the virtual host name.
748 * Field 0, the virtual host name, is special:
749 * it's already parsed off and will be strdup'ed
750 * later, after we know its canonical form.
752 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
753 if (*cp != '-' && (cp = strdup(cp)))
755 case 1: /* anon user permissions */
758 case 2: /* statistics file */
761 case 3: /* welcome message */
764 case 4: /* login message */
767 default: /* programming error */
772 hints.ai_flags = AI_PASSIVE;
773 hints.ai_family = family;
774 hints.ai_socktype = SOCK_STREAM;
775 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
777 for (ai = res; ai != NULL && ai->ai_addr != NULL;
781 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
784 for (hi = hrp->hostinfo; hi != NULL;
786 if (hi->ai_addrlen == ai->ai_addrlen &&
789 ai->ai_addr->sa_len) == 0) {
797 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
799 hrp->hostname = NULL;
802 if (hrp->hostinfo && hrp->hostinfo != res)
803 freeaddrinfo(hrp->hostinfo);
804 insert = 0; /* host already in the chain */
809 * determine hostname to use.
810 * force defined name if there is a valid alias
811 * otherwise fallback to primary hostname
813 /* XXX: getaddrinfo() can't do alias check */
814 switch(hrp->hostinfo->ai_family) {
816 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
817 addrsize = sizeof(struct in_addr);
820 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
821 addrsize = sizeof(struct in6_addr);
824 /* should not reach here */
825 freeaddrinfo(hrp->hostinfo);
827 free(hrp); /*not in chain, can free*/
829 hrp->hostinfo = NULL; /*mark as blank*/
833 if ((hp = getipnodebyaddr(addr, addrsize,
834 hrp->hostinfo->ai_family,
835 &hp_error)) != NULL) {
836 if (strcmp(vhost, hp->h_name) != 0) {
837 if (hp->h_aliases == NULL)
841 while (hp->h_aliases[i] &&
842 strcmp(vhost, hp->h_aliases[i]) != 0)
844 if (hp->h_aliases[i] == NULL)
850 strcmp(hrp->hostname, vhost) != 0) {
852 hrp->hostname = NULL;
854 if (hrp->hostname == NULL &&
855 (hrp->hostname = strdup(vhost)) == NULL) {
856 freeaddrinfo(hrp->hostinfo);
857 hrp->hostinfo = NULL; /* mark as blank */
862 hrp->anonuser = anonuser;
863 hrp->statfile = statfile;
864 hrp->welcome = welcome;
865 hrp->loginmsg = loginmsg;
883 selecthost(union sockunion *su)
888 struct in6_addr *mapped_in6 = NULL;
894 * XXX IPv4 mapped IPv6 addr consideraton,
895 * specified in rfc2373.
897 if (su->su_family == AF_INET6 &&
898 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
899 mapped_in6 = &su->su_sin6.sin6_addr;
902 hrp = thishost = firsthost; /* default */
905 while (hrp != NULL) {
906 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
907 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
912 /* XXX IPv4 mapped IPv6 addr consideraton */
913 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
914 (memcmp(&mapped_in6->s6_addr[12],
915 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
916 sizeof(struct in_addr)) == 0)) {
926 /* setup static variables as appropriate */
927 hostname = thishost->hostname;
928 ftpuser = thishost->anonuser;
933 * Helper function for sgetpwnam().
938 char *new = malloc(strlen(s) + 1);
941 reply(421, "Ran out of memory.");
945 (void) strcpy(new, s);
950 * Save the result of a getpwnam. Used for USER command, since
951 * the data returned must not be clobbered by any other command
953 * NB: The data returned by sgetpwnam() will remain valid until
954 * the next call to this function. Its difference from getpwnam()
955 * is that sgetpwnam() is known to be called from ftpd code only.
957 static struct passwd *
958 sgetpwnam(char *name)
960 static struct passwd save;
963 if ((p = getpwnam(name)) == NULL)
967 free(save.pw_passwd);
973 save.pw_name = sgetsave(p->pw_name);
974 save.pw_passwd = sgetsave(p->pw_passwd);
975 save.pw_gecos = sgetsave(p->pw_gecos);
976 save.pw_dir = sgetsave(p->pw_dir);
977 save.pw_shell = sgetsave(p->pw_shell);
981 static int login_attempts; /* number of failed login attempts */
982 static int askpasswd; /* had user command, ask for passwd */
983 static char curname[MAXLOGNAME]; /* current USER name */
987 * Sets global passwd pointer pw if named account exists and is acceptable;
988 * sets askpasswd if a PASS command is expected. If logged in previously,
989 * need to reset state. If name is "ftp" or "anonymous", the name is not in
990 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
991 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
992 * requesting login privileges. Disallow anyone who does not have a standard
993 * shell as returned by getusershell(). Disallow anyone mentioned in the file
994 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
1003 reply(530, "Can't change user from guest login.");
1005 } else if (dochroot) {
1006 reply(530, "Can't change user from chroot user.");
1013 #ifdef VIRTUAL_HOSTING
1014 pw = sgetpwnam(thishost->anonuser);
1016 pw = sgetpwnam("ftp");
1018 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1019 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL) ||
1020 checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL))
1021 reply(530, "User %s access denied.", name);
1022 else if (pw != NULL) {
1026 "Guest login ok, send your email address as password.");
1028 reply(530, "User %s unknown.", name);
1029 if (!askpasswd && logging)
1031 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1034 if (anon_only != 0) {
1035 reply(530, "Sorry, only anonymous ftp allowed.");
1039 if ((pw = sgetpwnam(name))) {
1040 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1041 shell = _PATH_BSHELL;
1043 while ((cp = getusershell()) != NULL)
1044 if (strcmp(cp, shell) == 0)
1048 if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1, NULL)) {
1049 reply(530, "User %s access denied.", name);
1052 "FTP LOGIN REFUSED FROM %s, %s",
1059 strncpy(curname, name, sizeof(curname)-1);
1063 /* XXX Kluge! The conversation mechanism needs to be fixed. */
1065 if (opiechallenge(&opiedata, name, opieprompt) == 0) {
1066 pwok = (pw != NULL) &&
1067 opieaccessfile(remotehost) &&
1068 opiealways(pw->pw_dir);
1069 reply(331, "Response to %s %s for %s.",
1070 opieprompt, pwok ? "requested" : "required", name);
1073 reply(331, "Password required for %s.", name);
1077 * Delay before reading passwd after first failed
1078 * attempt to slow down passwd-guessing programs.
1081 sleep(login_attempts);
1085 * Check if a user is in the file "fname",
1086 * return a pointer to a malloc'd string with the rest
1087 * of the matching line in "residue" if not NULL.
1090 checkuser(char *fname, char *name, int pwset, char **residue)
1095 char *line, *mp, *p;
1097 if ((fd = fopen(fname, "r")) != NULL) {
1098 while (!found && (line = fgetln(fd, &len)) != NULL) {
1102 if (line[len - 1] == '\n') {
1103 line[len - 1] = '\0';
1106 if ((mp = malloc(len + 1)) == NULL)
1107 fatalerror("Ran out of memory.");
1108 memcpy(mp, line, len);
1112 /* avoid possible leading and trailing whitespace */
1113 p = strtok(line, " \t");
1114 /* skip empty lines */
1118 * if first chr is '@', check group membership
1124 if (p[1] == '\0') /* single @ matches anyone */
1127 if ((grp = getgrnam(p+1)) == NULL)
1130 * Check user's default group
1132 if (pwset && grp->gr_gid == pw->pw_gid)
1135 * Check supplementary groups
1137 while (!found && grp->gr_mem[i])
1138 found = strcmp(name,
1144 * Otherwise, just check for username match
1147 found = strcmp(p, name) == 0;
1149 * Save the rest of line to "residue" if matched
1151 if (found && residue) {
1152 if ((p = strtok(NULL, "")) != NULL)
1153 p += strspn(p, " \t");
1155 if ((*residue = strdup(p)) == NULL)
1156 fatalerror("Ran out of memory.");
1170 * Terminate login as previous user, if any, resetting state;
1171 * used when USER command is given or login fails.
1181 if (logged_in && dowtmp)
1182 ftpd_logwtmp(ttyline, "", NULL);
1185 setusercontext(NULL, getpwuid(0), 0,
1186 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK|
1191 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1192 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1193 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1194 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1195 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1196 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1208 * the following code is stolen from imap-uw PAM authentication module and
1211 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1214 const char *uname; /* user name */
1215 const char *pass; /* password */
1217 typedef struct cred_t cred_t;
1220 auth_conv(int num_msg, const struct pam_message **msg,
1221 struct pam_response **resp, void *appdata)
1224 cred_t *cred = (cred_t *) appdata;
1225 struct pam_response *reply;
1227 reply = calloc(num_msg, sizeof *reply);
1231 for (i = 0; i < num_msg; i++) {
1232 switch (msg[i]->msg_style) {
1233 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1234 reply[i].resp_retcode = PAM_SUCCESS;
1235 reply[i].resp = COPY_STRING(cred->uname);
1236 /* PAM frees resp. */
1238 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1239 reply[i].resp_retcode = PAM_SUCCESS;
1240 reply[i].resp = COPY_STRING(cred->pass);
1241 /* PAM frees resp. */
1245 reply[i].resp_retcode = PAM_SUCCESS;
1246 reply[i].resp = NULL;
1248 default: /* unknown message style */
1250 return PAM_CONV_ERR;
1259 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1260 * authenticated, or 1 if not authenticated. If some sort of PAM system
1261 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1262 * function returns -1. This can be used as an indication that we should
1263 * fall back to a different authentication mechanism.
1266 auth_pam(struct passwd **ppw, const char *pass)
1268 const char *tmpl_user;
1272 cred_t auth_cred = { (*ppw)->pw_name, pass };
1273 struct pam_conv conv = { &auth_conv, &auth_cred };
1275 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1276 if (e != PAM_SUCCESS) {
1278 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1279 * if context creation has failed in the first place.
1281 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
1285 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1286 if (e != PAM_SUCCESS) {
1287 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1288 pam_strerror(pamh, e));
1289 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1290 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1296 e = pam_authenticate(pamh, 0);
1300 * With PAM we support the concept of a "template"
1301 * user. The user enters a login name which is
1302 * authenticated by PAM, usually via a remote service
1303 * such as RADIUS or TACACS+. If authentication
1304 * succeeds, a different but related "template" name
1305 * is used for setting the credentials, shell, and
1306 * home directory. The name the user enters need only
1307 * exist on the remote authentication server, but the
1308 * template name must be present in the local password
1311 * This is supported by two various mechanisms in the
1312 * individual modules. However, from the application's
1313 * point of view, the template user is always passed
1314 * back as a changed value of the PAM_USER item.
1316 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1318 tmpl_user = (const char *) item;
1319 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1320 *ppw = getpwnam(tmpl_user);
1322 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1323 pam_strerror(pamh, e));
1328 case PAM_USER_UNKNOWN:
1334 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1340 e = pam_acct_mgmt(pamh, 0);
1341 if (e != PAM_SUCCESS) {
1342 syslog(LOG_ERR, "pam_acct_mgmt: %s",
1343 pam_strerror(pamh, e));
1349 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1350 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1357 #endif /* USE_PAM */
1365 login_cap_t *lc = NULL;
1370 char *residue = NULL;
1373 if (logged_in || askpasswd == 0) {
1374 reply(503, "Login with USER first.");
1378 if (!guest) { /* "ftp" is only account allowed no password */
1380 rval = 1; /* failure below */
1384 rval = auth_pam(&pw, passwd);
1390 if (opieverify(&opiedata, passwd) == 0)
1391 xpasswd = pw->pw_passwd;
1393 xpasswd = crypt(passwd, pw->pw_passwd);
1394 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1400 rval = strcmp(pw->pw_passwd, xpasswd);
1401 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1402 rval = 1; /* failure */
1405 * If rval == 1, the user failed the authentication check
1406 * above. If rval == 0, either PAM or local authentication
1410 reply(530, "Login incorrect.");
1413 "FTP LOGIN FAILED FROM %s",
1415 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1416 "FTP LOGIN FAILED FROM %s, %s",
1417 remotehost, curname);
1420 if (login_attempts++ >= 5) {
1422 "repeated login failures from %s",
1429 login_attempts = 0; /* this time successful */
1430 if (setegid(pw->pw_gid) < 0) {
1431 reply(550, "Can't set gid.");
1434 /* May be overridden by login.conf */
1435 (void) umask(defumask);
1437 if ((lc = login_getpwclass(pw)) != NULL) {
1438 char remote_ip[NI_MAXHOST];
1440 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1441 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1444 remote_ip[sizeof(remote_ip) - 1] = 0;
1445 if (!auth_hostok(lc, remotehost, remote_ip)) {
1446 syslog(LOG_INFO|LOG_AUTH,
1447 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1449 reply(530, "Permission denied.");
1453 if (!auth_timeok(lc, time(NULL))) {
1454 reply(530, "Login not available right now.");
1459 setusercontext(lc, pw, 0,
1460 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1461 LOGIN_SETRESOURCES|LOGIN_SETUMASK|LOGIN_SETMAC);
1463 setlogin(pw->pw_name);
1464 (void) initgroups(pw->pw_name, pw->pw_gid);
1469 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1470 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1471 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1472 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1477 /* open wtmp before chroot */
1479 ftpd_logwtmp(ttyline, pw->pw_name,
1480 (struct sockaddr *)&his_addr);
1483 if (guest && stats && statfd < 0)
1484 #ifdef VIRTUAL_HOSTING
1485 statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1487 statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1493 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue)
1494 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1495 || login_getcapbool(lc, "ftp-chroot", 0)
1500 * For a chrooted local user,
1501 * a) see whether ftpchroot(5) specifies a chroot directory,
1502 * b) extract the directory pathname from the line,
1503 * c) expand it to the absolute pathname if necessary.
1505 if (dochroot && residue &&
1506 (chrootdir = strtok(residue, " \t")) != NULL) {
1507 if (chrootdir[0] != '/')
1508 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1510 chrootdir = strdup(chrootdir); /* make it permanent */
1511 if (chrootdir == NULL)
1512 fatalerror("Ran out of memory.");
1514 if (guest || dochroot) {
1516 * If no chroot directory set yet, use the login directory.
1517 * Copy it so it can be modified while pw->pw_dir stays intact.
1519 if (chrootdir == NULL &&
1520 (chrootdir = strdup(pw->pw_dir)) == NULL)
1521 fatalerror("Ran out of memory.");
1523 * Check for the "/chroot/./home" syntax,
1524 * separate the chroot and home directory pathnames.
1526 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1527 *(homedir++) = '\0'; /* wipe '/' */
1528 homedir++; /* skip '.' */
1531 * We MUST do a chdir() after the chroot. Otherwise
1532 * the old current directory will be accessible as "."
1533 * outside the new root!
1538 * Finally, do chroot()
1540 if (chroot(chrootdir) < 0) {
1541 reply(550, "Can't change root.");
1544 } else /* real user w/o chroot */
1545 homedir = pw->pw_dir;
1547 * Set euid *before* doing chdir() so
1548 * a) the user won't be carried to a directory that he couldn't reach
1549 * on his own due to no permission to upper path components,
1550 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1551 * (uid 0 has no root power over NFS if not mapped explicitly.)
1553 if (seteuid(pw->pw_uid) < 0) {
1554 reply(550, "Can't set uid.");
1557 if (chdir(homedir) < 0) {
1558 if (guest || dochroot) {
1559 reply(550, "Can't change to base directory.");
1562 if (chdir("/") < 0) {
1563 reply(550, "Root is inaccessible.");
1566 lreply(230, "No directory! Logging in with home=/.");
1571 * Display a login message, if it exists.
1572 * N.B. reply(230,) must follow the message.
1574 #ifdef VIRTUAL_HOSTING
1575 fd = fopen(thishost->loginmsg, "r");
1577 fd = fopen(_PATH_FTPLOGINMESG, "r");
1580 char *cp, line[LINE_MAX];
1582 while (fgets(line, sizeof(line), fd) != NULL) {
1583 if ((cp = strchr(line, '\n')) != NULL)
1585 lreply(230, "%s", line);
1587 (void) fflush(stdout);
1593 ident = strdup(passwd);
1595 fatalerror("Ran out of memory.");
1597 reply(230, "Guest login ok, access restrictions apply.");
1599 #ifdef VIRTUAL_HOSTING
1600 if (thishost != firsthost)
1601 snprintf(proctitle, sizeof(proctitle),
1602 "%s: anonymous(%s)/%s", remotehost, hostname,
1606 snprintf(proctitle, sizeof(proctitle),
1607 "%s: anonymous/%s", remotehost, passwd);
1608 setproctitle("%s", proctitle);
1609 #endif /* SETPROCTITLE */
1611 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1612 remotehost, passwd);
1615 reply(230, "User %s logged in, "
1616 "access restrictions apply.", pw->pw_name);
1618 reply(230, "User %s logged in.", pw->pw_name);
1621 snprintf(proctitle, sizeof(proctitle),
1622 "%s: user/%s", remotehost, pw->pw_name);
1623 setproctitle("%s", proctitle);
1624 #endif /* SETPROCTITLE */
1626 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1627 remotehost, pw->pw_name);
1629 if (logging && (guest || dochroot))
1630 syslog(LOG_INFO, "session root changed to %s", chrootdir);
1638 /* Forget all about it... */
1648 retrieve(char *cmd, char *name)
1652 int (*closefunc)(FILE *);
1656 fin = fopen(name, "r"), closefunc = fclose;
1661 (void) snprintf(line, sizeof(line), cmd, name), name = line;
1662 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1664 st.st_blksize = BUFSIZ;
1668 perror_reply(550, name);
1670 LOGCMD("get", name);
1677 if (fstat(fileno(fin), &st) < 0) {
1678 perror_reply(550, name);
1681 if (!S_ISREG(st.st_mode)) {
1683 * Never sending a raw directory is a workaround
1684 * for buggy clients that will attempt to RETR
1685 * a directory before listing it, e.g., Mozilla.
1686 * Preventing a guest from getting irregular files
1687 * is a simple security measure.
1689 if (S_ISDIR(st.st_mode) || guest) {
1690 reply(550, "%s: not a plain file.", name);
1694 /* st.st_blksize is set for all descriptor types */
1697 if (restart_point) {
1698 if (type == TYPE_A) {
1705 if ((c=getc(fin)) == EOF) {
1706 perror_reply(550, name);
1712 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1713 perror_reply(550, name);
1717 dout = dataconn(name, st.st_size, "w");
1721 send_data(fin, dout, st.st_blksize, st.st_size,
1722 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1723 if (cmd == 0 && guest && stats && byte_count > 0)
1724 logxfer(name, byte_count, start);
1725 (void) fclose(dout);
1730 LOGBYTES("get", name, byte_count);
1735 store(char *name, char *mode, int unique)
1739 int (*closefunc)(FILE *);
1741 if (*mode == 'a') { /* APPE */
1743 /* Programming error */
1744 syslog(LOG_ERR, "Internal: unique flag to APPE");
1747 if (guest && noguestmod) {
1748 reply(550, "Appending to existing file denied.");
1751 restart_point = 0; /* not affected by preceding REST */
1753 if (unique) /* STOU overrides REST */
1755 if (guest && noguestmod) {
1756 if (restart_point) { /* guest STOR w/REST */
1757 reply(550, "Modifying existing file denied.");
1759 } else /* treat guest STOR as STOU */
1764 mode = "r+"; /* so ASCII manual seek can work */
1766 if ((fd = guniquefd(name, &name)) < 0)
1768 fout = fdopen(fd, mode);
1770 fout = fopen(name, mode);
1773 perror_reply(553, name);
1777 if (restart_point) {
1778 if (type == TYPE_A) {
1785 if ((c=getc(fout)) == EOF) {
1786 perror_reply(550, name);
1793 * We must do this seek to "current" position
1794 * because we are changing from reading to
1797 if (fseeko(fout, 0, SEEK_CUR) < 0) {
1798 perror_reply(550, name);
1801 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1802 perror_reply(550, name);
1806 din = dataconn(name, -1, "r");
1809 if (receive_data(din, fout) == 0) {
1811 reply(226, "Transfer complete (unique file name:%s).",
1814 reply(226, "Transfer complete.");
1820 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1824 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1829 getdatasock(char *mode)
1831 int on = 1, s, t, tries;
1834 return (fdopen(data, mode));
1836 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1839 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1840 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1841 /* anchor socket to avoid multi-homing problems */
1842 data_source = ctrl_addr;
1843 data_source.su_port = htons(dataport);
1845 for (tries = 1; ; tries++) {
1847 * We should loop here since it's possible that
1848 * another ftpd instance has passed this point and is
1849 * trying to open a data connection in active mode now.
1850 * Until the other connection is opened, we'll be getting
1851 * EADDRINUSE because no SOCK_STREAM sockets in the system
1852 * can share both local and remote addresses, localIP:20
1853 * and *:* in this case.
1855 if (bind(s, (struct sockaddr *)&data_source,
1856 data_source.su_len) >= 0)
1858 if (errno != EADDRINUSE || tries > 10)
1862 (void) seteuid(pw->pw_uid);
1864 if (data_source.su_family == AF_INET)
1866 on = IPTOS_THROUGHPUT;
1867 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1868 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1873 * Turn off push flag to keep sender TCP from sending short packets
1874 * at the boundaries of each write(). Should probably do a SO_SNDBUF
1875 * to set the send buffer size as well, but that may not be desirable
1876 * in heavy-load situations.
1879 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1880 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1884 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &on, sizeof on) < 0)
1885 syslog(LOG_WARNING, "data setsockopt (SO_SNDBUF): %m");
1888 return (fdopen(s, mode));
1890 /* Return the real value of errno (close may change it) */
1892 (void) seteuid(pw->pw_uid);
1899 dataconn(char *name, off_t size, char *mode)
1903 int retry = 0, tos, conerrno;
1908 (void) snprintf(sizebuf, sizeof(sizebuf),
1909 " (%jd bytes)", (intmax_t)size);
1913 union sockunion from;
1914 socklen_t fromlen = ctrl_addr.su_len;
1916 struct timeval timeout;
1920 FD_SET(pdata, &set);
1922 timeout.tv_usec = 0;
1923 timeout.tv_sec = 120;
1926 * Granted a socket is in the blocking I/O mode,
1927 * accept() will block after a successful select()
1928 * if the selected connection dies in between.
1929 * Therefore set the non-blocking I/O flag here.
1931 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1932 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1934 if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
1935 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1937 (void) close(pdata);
1940 * Unset the inherited non-blocking I/O flag
1941 * on the child socket so stdio can work on it.
1943 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1944 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1947 if (from.su_family == AF_INET)
1949 tos = IPTOS_THROUGHPUT;
1950 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1951 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1954 reply(150, "Opening %s mode data connection for '%s'%s.",
1955 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1956 return (fdopen(pdata, mode));
1958 reply(425, "Can't open data connection.");
1959 (void) close(pdata);
1964 reply(125, "Using existing data connection for '%s'%s.",
1967 return (fdopen(data, mode));
1970 data_dest = his_addr;
1973 file = getdatasock(mode);
1975 char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
1977 if (getnameinfo((struct sockaddr *)&data_source,
1979 hostbuf, sizeof(hostbuf) - 1,
1980 portbuf, sizeof(portbuf) - 1,
1981 NI_NUMERICHOST|NI_NUMERICSERV))
1982 *hostbuf = *portbuf = 0;
1983 hostbuf[sizeof(hostbuf) - 1] = 0;
1984 portbuf[sizeof(portbuf) - 1] = 0;
1985 reply(425, "Can't create data socket (%s,%s): %s.",
1986 hostbuf, portbuf, strerror(errno));
1989 data = fileno(file);
1991 if (connect(data, (struct sockaddr *)&data_dest,
1992 data_dest.su_len) == 0)
1995 (void) fclose(file);
1997 if (conerrno == EADDRINUSE) {
2003 } while (retry <= swaitmax);
2004 if (conerrno != 0) {
2005 reply(425, "Can't build data connection: %s.",
2006 strerror(conerrno));
2009 reply(150, "Opening %s mode data connection for '%s'%s.",
2010 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2015 * A helper macro to avoid code duplication
2016 * in send_data() and receive_data().
2018 * XXX We have to block SIGURG during putc() because BSD stdio
2019 * is unable to restart interrupted write operations and hence
2020 * the entire buffer contents will be lost as soon as a write()
2021 * call indicates EINTR to stdio.
2023 #define FTPD_PUTC(ch, file, label) \
2029 ret = putc((ch), (file)); \
2031 CHECKOOB(return (-1)) \
2032 else if (ferror(file)) \
2035 } while (ret == EOF); \
2039 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
2040 * encapsulation of the data subject to Mode, Structure, and Type.
2042 * NB: Form isn't handled.
2045 send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2047 int c, cp, filefd, netfd;
2058 CHECKOOB(return (-1))
2059 else if (c == EOF && ferror(instr))
2062 if (ferror(instr)) { /* resume after OOB */
2066 if (feof(instr)) /* EOF */
2068 syslog(LOG_ERR, "Internal: impossible condition"
2069 " on file after getc()");
2072 if (c == '\n' && cp != '\r') {
2073 FTPD_PUTC('\r', outstr, data_err);
2076 FTPD_PUTC(c, outstr, data_err);
2080 #ifdef notyet /* BSD stdio isn't ready for that */
2081 while (fflush(outstr) == EOF) {
2082 CHECKOOB(return (-1))
2090 if (fflush(outstr) == EOF)
2093 reply(226, "Transfer complete.");
2099 * isreg is only set if we are not doing restart and we
2100 * are sending a regular file
2102 netfd = fileno(outstr);
2103 filefd = fileno(instr);
2106 char *msg = "Transfer complete.";
2112 while (filesize > 0) {
2113 err = sendfile(filefd, netfd, offset, 0,
2116 * Calculate byte_count before OOB processing.
2117 * It can be used in myoob() later.
2122 CHECKOOB(return (-1))
2123 else if (err == -1) {
2124 if (errno != EINTR &&
2125 cnt == 0 && offset == 0)
2129 if (err == -1) /* resume after OOB */
2132 * We hit the EOF prematurely.
2133 * Perhaps the file was externally truncated.
2136 msg = "Transfer finished due to "
2137 "premature end of file.";
2147 if ((buf = malloc(blksize)) == NULL) {
2149 reply(451, "Ran out of memory.");
2157 cnt = read(filefd, buf, blksize);
2158 CHECKOOB(free(buf); return (-1))
2163 if (cnt < 0) /* resume after OOB */
2165 if (cnt == 0) /* EOF */
2167 for (len = cnt, bp = buf; len > 0;) {
2168 cnt = write(netfd, bp, len);
2169 CHECKOOB(free(buf); return (-1))
2183 reply(226, "Transfer complete.");
2187 reply(550, "Unimplemented TYPE %d in send_data.", type);
2193 perror_reply(426, "Data connection");
2198 perror_reply(551, "Error on input file");
2203 * Transfer data from peer to "outstr" using the appropriate encapulation of
2204 * the data subject to Mode, Structure, and Type.
2206 * N.B.: Form isn't handled.
2209 receive_data(FILE *instr, FILE *outstr)
2225 cnt = read(fileno(instr), buf, sizeof(buf));
2226 CHECKOOB(return (-1))
2229 if (cnt < 0) /* resume after OOB */
2231 if (cnt == 0) /* EOF */
2233 for (len = cnt, bp = buf; len > 0;) {
2234 cnt = write(fileno(outstr), bp, len);
2235 CHECKOOB(return (-1))
2250 reply(553, "TYPE E not implemented.");
2257 CHECKOOB(return (-1))
2258 else if (c == EOF && ferror(instr))
2260 if (c == EOF && ferror(instr)) { /* resume after OOB */
2267 FTPD_PUTC('\r', outstr, file_err);
2277 /* Check for EOF here in order not to lose last \r. */
2279 if (feof(instr)) /* EOF */
2281 syslog(LOG_ERR, "Internal: impossible condition"
2282 " on data stream after getc()");
2287 FTPD_PUTC(c, outstr, file_err);
2290 #ifdef notyet /* BSD stdio isn't ready for that */
2291 while (fflush(outstr) == EOF) {
2292 CHECKOOB(return (-1))
2300 if (fflush(outstr) == EOF)
2305 "WARNING! %d bare linefeeds received in ASCII mode.",
2307 (void)printf(" File may not have transferred correctly.\r\n");
2312 reply(550, "Unimplemented TYPE %d in receive_data.", type);
2318 perror_reply(426, "Data connection");
2323 perror_reply(452, "Error writing to file");
2328 statfilecmd(char *filename)
2333 char line[LINE_MAX];
2336 code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2337 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2338 fin = ftpd_popen(line, "r");
2339 lreply(code, "Status of %s:", filename);
2341 while ((c = getc(fin)) != EOF) {
2343 if (ferror(stdout)){
2344 perror_reply(421, "Control connection");
2345 (void) ftpd_pclose(fin);
2350 perror_reply(551, filename);
2351 (void) ftpd_pclose(fin);
2354 (void) putc('\r', stdout);
2357 * RFC 959 says neutral text should be prepended before
2358 * a leading 3-digit number followed by whitespace, but
2359 * many ftp clients can be confused by any leading digits,
2360 * as a matter of fact.
2362 if (atstart && isdigit(c))
2363 (void) putc(' ', stdout);
2364 (void) putc(c, stdout);
2365 atstart = (c == '\n');
2367 (void) ftpd_pclose(fin);
2368 reply(code, "End of status.");
2374 union sockunion *su;
2376 char hname[NI_MAXHOST];
2380 lreply(211, "%s FTP server status:", hostname);
2381 printf(" %s\r\n", version);
2383 lreply(211, "FTP server status:");
2384 printf(" Connected to %s", remotehost);
2385 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2386 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2387 hname[sizeof(hname) - 1] = 0;
2388 if (strcmp(hname, remotehost) != 0)
2389 printf(" (%s)", hname);
2394 printf(" Logged in anonymously\r\n");
2396 printf(" Logged in as %s\r\n", pw->pw_name);
2397 } else if (askpasswd)
2398 printf(" Waiting for password\r\n");
2400 printf(" Waiting for user name\r\n");
2401 printf(" TYPE: %s", typenames[type]);
2402 if (type == TYPE_A || type == TYPE_E)
2403 printf(", FORM: %s", formnames[form]);
2406 printf(" %d", CHAR_BIT);
2408 printf(" %d", bytesize); /* need definition! */
2410 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2411 strunames[stru], modenames[mode]);
2413 printf(" Data connection open\r\n");
2414 else if (pdata != -1) {
2418 } else if (usedefault == 0) {
2422 #define UC(b) (((int) b) & 0xff)
2424 printf(" EPSV only mode (EPSV ALL)\r\n");
2429 if (su->su_family == AF_INET) {
2430 a = (u_char *) &su->su_sin.sin_addr;
2431 p = (u_char *) &su->su_sin.sin_port;
2432 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2433 ispassive ? "PASV" : "PORT",
2434 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2435 UC(p[0]), UC(p[1]));
2442 switch (su->su_family) {
2444 a = (u_char *) &su->su_sin.sin_addr;
2445 p = (u_char *) &su->su_sin.sin_port;
2446 alen = sizeof(su->su_sin.sin_addr);
2450 a = (u_char *) &su->su_sin6.sin6_addr;
2451 p = (u_char *) &su->su_sin6.sin6_port;
2452 alen = sizeof(su->su_sin6.sin6_addr);
2460 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2462 for (i = 0; i < alen; i++)
2463 printf("%d,", UC(a[i]));
2464 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2473 switch (su->su_family) {
2485 union sockunion tmp;
2488 if (tmp.su_family == AF_INET6)
2489 tmp.su_sin6.sin6_scope_id = 0;
2490 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2491 hname, sizeof(hname) - 1, NULL, 0,
2493 hname[sizeof(hname) - 1] = 0;
2494 printf(" %s |%d|%s|%d|\r\n",
2495 ispassive ? "EPSV" : "EPRT",
2496 af, hname, htons(tmp.su_port));
2502 printf(" No data connection\r\n");
2503 reply(211, "End of status.");
2510 reply(451, "Error in server: %s", s);
2511 reply(221, "Closing connection due to server error.");
2517 reply(int n, const char *fmt, ...)
2521 (void)printf("%d ", n);
2523 (void)vprintf(fmt, ap);
2525 (void)printf("\r\n");
2526 (void)fflush(stdout);
2528 syslog(LOG_DEBUG, "<--- %d ", n);
2530 vsyslog(LOG_DEBUG, fmt, ap);
2536 lreply(int n, const char *fmt, ...)
2540 (void)printf("%d- ", n);
2542 (void)vprintf(fmt, ap);
2544 (void)printf("\r\n");
2545 (void)fflush(stdout);
2547 syslog(LOG_DEBUG, "<--- %d- ", n);
2549 vsyslog(LOG_DEBUG, fmt, ap);
2558 reply(250, "%s command successful.", s);
2565 reply(502, "%s command not implemented.", s);
2574 if ((cp = strchr(cbuf,'\n')))
2576 reply(500, "%s: command not understood.", cbuf);
2584 LOGCMD("delete", name);
2585 if (lstat(name, &st) < 0) {
2586 perror_reply(550, name);
2589 if (S_ISDIR(st.st_mode)) {
2590 if (rmdir(name) < 0) {
2591 perror_reply(550, name);
2596 if (guest && noguestmod) {
2597 reply(550, "Operation not permitted.");
2600 if (unlink(name) < 0) {
2601 perror_reply(550, name);
2612 if (chdir(path) < 0)
2613 perror_reply(550, path);
2623 LOGCMD("mkdir", name);
2624 if (guest && noguestmkd)
2625 reply(550, "Operation not permitted.");
2626 else if (mkdir(name, 0777) < 0)
2627 perror_reply(550, name);
2629 if ((s = doublequote(name)) == NULL)
2630 fatalerror("Ran out of memory.");
2631 reply(257, "\"%s\" directory created.", s);
2637 removedir(char *name)
2640 LOGCMD("rmdir", name);
2641 if (rmdir(name) < 0)
2642 perror_reply(550, name);
2650 char *s, path[MAXPATHLEN + 1];
2652 if (getcwd(path, sizeof(path)) == NULL)
2653 perror_reply(550, "Get current directory");
2655 if ((s = doublequote(path)) == NULL)
2656 fatalerror("Ran out of memory.");
2657 reply(257, "\"%s\" is current directory.", s);
2663 renamefrom(char *name)
2667 if (guest && noguestmod) {
2668 reply(550, "Operation not permitted.");
2671 if (lstat(name, &st) < 0) {
2672 perror_reply(550, name);
2675 reply(350, "File exists, ready for destination name.");
2680 renamecmd(char *from, char *to)
2684 LOGCMD2("rename", from, to);
2686 if (guest && (stat(to, &st) == 0)) {
2687 reply(550, "%s: permission denied.", to);
2691 if (rename(from, to) < 0)
2692 perror_reply(550, "rename");
2698 dolog(struct sockaddr *who)
2700 char who_name[NI_MAXHOST];
2702 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2703 remotehost[sizeof(remotehost) - 1] = 0;
2704 if (getnameinfo(who, who->sa_len,
2705 who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
2707 who_name[sizeof(who_name) - 1] = 0;
2710 #ifdef VIRTUAL_HOSTING
2711 if (thishost != firsthost)
2712 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2713 remotehost, hostname);
2716 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2718 setproctitle("%s", proctitle);
2719 #endif /* SETPROCTITLE */
2722 #ifdef VIRTUAL_HOSTING
2723 if (thishost != firsthost)
2724 syslog(LOG_INFO, "connection from %s (%s) to %s",
2725 remotehost, who_name, hostname);
2728 syslog(LOG_INFO, "connection from %s (%s)",
2729 remotehost, who_name);
2734 * Record logout in wtmp file
2735 * and exit with supplied status.
2738 dologout(int status)
2741 if (logged_in && dowtmp) {
2743 ftpd_logwtmp(ttyline, "", NULL);
2745 /* beware of flushing buffers after a SIGPIPE */
2763 syslog(LOG_ERR, "Internal: maskurg() while no transfer");
2768 sigaddset(&sset, SIGURG);
2769 sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
2779 syslog(LOG_ERR, "Internal: flagxfer(1): "
2780 "transfer already under way");
2786 syslog(LOG_ERR, "Internal: flagxfer(0): "
2787 "no active transfer");
2794 * Returns 0 if OK to resume or -1 if abort requested.
2802 syslog(LOG_ERR, "Internal: myoob() while no transfer");
2806 if (getline(cp, 7, stdin) == NULL) {
2807 reply(221, "You could at least say goodbye.");
2811 if (strcmp(cp, "ABOR\r\n") == 0) {
2813 reply(426, "Transfer aborted. Data connection closed.");
2814 reply(226, "Abort successful.");
2817 if (strcmp(cp, "STAT\r\n") == 0) {
2819 if (file_size != -1)
2820 reply(213, "Status: %jd of %jd bytes transferred.",
2821 (intmax_t)byte_count, (intmax_t)file_size);
2823 reply(213, "Status: %jd bytes transferred.",
2824 (intmax_t)byte_count);
2830 * Note: a response of 425 is not mentioned as a possible response to
2831 * the PASV command in RFC959. However, it has been blessed as
2832 * a legitimate response by Jon Postel in a telephone conversation
2833 * with Rick Adams on 25 Jan 89.
2842 if (pdata >= 0) /* close old port if one set */
2845 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2847 perror_reply(425, "Can't open passive connection");
2851 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2852 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2857 if (ctrl_addr.su_family == AF_INET) {
2858 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2859 : IP_PORTRANGE_DEFAULT;
2861 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2862 &on, sizeof(on)) < 0)
2866 #ifdef IPV6_PORTRANGE
2867 if (ctrl_addr.su_family == AF_INET6) {
2868 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2869 : IPV6_PORTRANGE_DEFAULT;
2871 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2872 &on, sizeof(on)) < 0)
2877 pasv_addr = ctrl_addr;
2878 pasv_addr.su_port = 0;
2879 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2882 (void) seteuid(pw->pw_uid);
2884 len = sizeof(pasv_addr);
2885 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2887 if (listen(pdata, 1) < 0)
2889 if (pasv_addr.su_family == AF_INET)
2890 a = (char *) &pasv_addr.su_sin.sin_addr;
2891 else if (pasv_addr.su_family == AF_INET6 &&
2892 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2893 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2897 p = (char *) &pasv_addr.su_port;
2899 #define UC(b) (((int) b) & 0xff)
2901 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2902 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2906 (void) seteuid(pw->pw_uid);
2907 (void) close(pdata);
2909 perror_reply(425, "Can't open passive connection");
2914 * Long Passive defined in RFC 1639.
2915 * 228 Entering Long Passive Mode
2916 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2920 long_passive(char *cmd, int pf)
2926 if (pdata >= 0) /* close old port if one set */
2929 if (pf != PF_UNSPEC) {
2930 if (ctrl_addr.su_family != pf) {
2931 switch (ctrl_addr.su_family) {
2944 * only EPRT/EPSV ready clients will understand this
2946 if (strcmp(cmd, "EPSV") == 0 && pf) {
2947 reply(522, "Network protocol mismatch, "
2950 reply(501, "Network protocol mismatch."); /*XXX*/
2956 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2958 perror_reply(425, "Can't open passive connection");
2962 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2963 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2967 pasv_addr = ctrl_addr;
2968 pasv_addr.su_port = 0;
2969 len = pasv_addr.su_len;
2972 if (ctrl_addr.su_family == AF_INET) {
2973 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2974 : IP_PORTRANGE_DEFAULT;
2976 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2977 &on, sizeof(on)) < 0)
2981 #ifdef IPV6_PORTRANGE
2982 if (ctrl_addr.su_family == AF_INET6) {
2983 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2984 : IPV6_PORTRANGE_DEFAULT;
2986 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2987 &on, sizeof(on)) < 0)
2992 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2995 (void) seteuid(pw->pw_uid);
2997 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2999 if (listen(pdata, 1) < 0)
3002 #define UC(b) (((int) b) & 0xff)
3004 if (strcmp(cmd, "LPSV") == 0) {
3005 p = (char *)&pasv_addr.su_port;
3006 switch (pasv_addr.su_family) {
3008 a = (char *) &pasv_addr.su_sin.sin_addr;
3011 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3012 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3013 2, UC(p[0]), UC(p[1]));
3016 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
3017 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
3020 a = (char *) &pasv_addr.su_sin6.sin6_addr;
3022 "Entering Long Passive Mode "
3023 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3024 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3025 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3026 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3027 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3028 2, UC(p[0]), UC(p[1]));
3031 } else if (strcmp(cmd, "EPSV") == 0) {
3032 switch (pasv_addr.su_family) {
3035 reply(229, "Entering Extended Passive Mode (|||%d|)",
3036 ntohs(pasv_addr.su_port));
3040 /* more proper error code? */
3044 (void) seteuid(pw->pw_uid);
3045 (void) close(pdata);
3047 perror_reply(425, "Can't open passive connection");
3052 * Generate unique name for file with basename "local"
3053 * and open the file in order to avoid possible races.
3054 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3055 * Return descriptor to the file, set "name" to its name.
3057 * Generates failure reply on error.
3060 guniquefd(char *local, char **name)
3062 static char new[MAXPATHLEN];
3068 cp = strrchr(local, '/');
3071 if (stat(cp ? local : ".", &st) < 0) {
3072 perror_reply(553, cp ? local : ".");
3077 * Let not overwrite dirname with counter suffix.
3079 * In this extreme case dot won't be put in front of suffix.
3081 if (strlen(local) > sizeof(new) - 4) {
3082 reply(553, "Pathname too long.");
3087 /* -4 is for the .nn<null> we put on the end below */
3088 (void) snprintf(new, sizeof(new) - 4, "%s", local);
3089 cp = new + strlen(new);
3091 * Don't generate dotfile unless requested explicitly.
3092 * This covers the case when basename gets truncated off
3095 if (cp > new && cp[-1] != '/')
3097 for (count = 0; count < 100; count++) {
3098 /* At count 0 try unmodified name */
3100 (void)sprintf(cp, "%d", count);
3101 if ((fd = open(count ? new : local,
3102 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3103 *name = count ? new : local;
3106 if (errno != EEXIST) {
3107 perror_reply(553, count ? new : local);
3111 reply(452, "Unique file name cannot be created.");
3116 * Format and send reply containing system error number.
3119 perror_reply(int code, char *string)
3122 reply(code, "%s: %s.", string, strerror(errno));
3125 static char *onefile[] = {
3131 send_file_list(char *whichf)
3137 char **dirlist, *dirname;
3142 if (strpbrk(whichf, "~{[*?") != NULL) {
3143 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3145 memset(&gl, 0, sizeof(gl));
3146 gl.gl_matchc = MAXGLOBARGS;
3147 flags |= GLOB_LIMIT;
3149 if (glob(whichf, flags, 0, &gl)) {
3150 reply(550, "No matching files found.");
3152 } else if (gl.gl_pathc == 0) {
3154 perror_reply(550, whichf);
3157 dirlist = gl.gl_pathv;
3159 onefile[0] = whichf;
3164 while ((dirname = *dirlist++)) {
3165 if (stat(dirname, &st) < 0) {
3167 * If user typed "ls -l", etc, and the client
3168 * used NLST, do what the user meant.
3170 if (dirname[0] == '-' && *dirlist == NULL &&
3172 retrieve(_PATH_LS " %s", dirname);
3174 perror_reply(550, whichf);
3178 if (S_ISREG(st.st_mode)) {
3180 dout = dataconn("file list", -1, "w");
3186 fprintf(dout, "%s%s\n", dirname,
3187 type == TYPE_A ? "\r" : "");
3191 byte_count += strlen(dirname) +
3192 (type == TYPE_A ? 2 : 1);
3193 CHECKOOB(goto abrt);
3195 } else if (!S_ISDIR(st.st_mode))
3198 if ((dirp = opendir(dirname)) == NULL)
3201 while ((dir = readdir(dirp)) != NULL) {
3202 char nbuf[MAXPATHLEN];
3204 CHECKOOB(goto abrt);
3206 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
3208 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3212 snprintf(nbuf, sizeof(nbuf),
3213 "%s/%s", dirname, dir->d_name);
3216 * We have to do a stat to insure it's
3217 * not a directory or special file.
3219 if (simple || (stat(nbuf, &st) == 0 &&
3220 S_ISREG(st.st_mode))) {
3222 dout = dataconn("file list", -1, "w");
3228 if (nbuf[0] == '.' && nbuf[1] == '/')
3229 fprintf(dout, "%s%s\n", &nbuf[2],
3230 type == TYPE_A ? "\r" : "");
3232 fprintf(dout, "%s%s\n", nbuf,
3233 type == TYPE_A ? "\r" : "");
3237 byte_count += strlen(nbuf) +
3238 (type == TYPE_A ? 2 : 1);
3239 CHECKOOB(goto abrt);
3242 (void) closedir(dirp);
3247 reply(550, "No files found.");
3248 else if (ferror(dout))
3249 data_err: perror_reply(550, "Data connection");
3251 reply(226, "Transfer complete.");
3256 (void) fclose(dout);
3261 (void) closedir(dirp);
3269 reapchild(int signo)
3271 while (waitpid(-1, NULL, WNOHANG) > 0);
3274 #ifdef OLD_SETPROCTITLE
3276 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.)
3277 * Warning, since this is usually started from inetd.conf, it often doesn't
3278 * have much of an environment or arglist to overwrite.
3281 setproctitle(const char *fmt, ...)
3289 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
3291 /* make ps print our process name */
3296 if (i > LastArgv - p - 2) {
3297 i = LastArgv - p - 2;
3302 if (ch != '\n' && ch != '\r')
3304 while (p < LastArgv)
3307 #endif /* OLD_SETPROCTITLE */
3310 appendf(char **strp, char *fmt, ...)
3316 vasprintf(&p, fmt, ap);
3319 fatalerror("Ran out of memory.");
3324 asprintf(strp, "%s%s", ostr, p);
3326 fatalerror("Ran out of memory.");
3332 logcmd(char *cmd, char *file1, char *file2, off_t cnt)
3335 char wd[MAXPATHLEN + 1];
3340 if (getcwd(wd, sizeof(wd) - 1) == NULL)
3341 strcpy(wd, strerror(errno));
3343 appendf(&msg, "%s", cmd);
3345 appendf(&msg, " %s", file1);
3347 appendf(&msg, " %s", file2);
3349 appendf(&msg, " = %jd bytes", (intmax_t)cnt);
3350 appendf(&msg, " (wd: %s", wd);
3351 if (guest || dochroot)
3352 appendf(&msg, "; chrooted");
3354 syslog(LOG_INFO, "%s", msg);
3359 logxfer(char *name, off_t size, time_t start)
3361 char buf[MAXPATHLEN + 1024];
3362 char path[MAXPATHLEN + 1];
3367 if (realpath(name, path) == NULL) {
3368 syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
3371 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n",
3372 ctime(&now)+4, ident, remotehost,
3373 path, (intmax_t)size,
3374 (long)(now - start + (now == start)));
3375 write(statfd, buf, strlen(buf));
3380 doublequote(char *s)
3385 for (p = s, n = 0; *p; p++)
3389 if ((s2 = malloc(p - s + n + 1)) == NULL)
3392 for (p = s2; *s; s++, p++) {
3393 if ((*p = *s) == '"')
3401 /* setup server socket for specified address family */
3402 /* if af is PF_UNSPEC more than one socket may be returned */
3403 /* the returned list is dynamically allocated, so caller needs to free it */
3405 socksetup(int af, char *bindname, const char *bindport)
3407 struct addrinfo hints, *res, *r;
3408 int error, maxs, *s, *socks;
3411 memset(&hints, 0, sizeof(hints));
3412 hints.ai_flags = AI_PASSIVE;
3413 hints.ai_family = af;
3414 hints.ai_socktype = SOCK_STREAM;
3415 error = getaddrinfo(bindname, bindport, &hints, &res);
3417 syslog(LOG_ERR, "%s", gai_strerror(error));
3418 if (error == EAI_SYSTEM)
3419 syslog(LOG_ERR, "%s", strerror(errno));
3423 /* Count max number of sockets we may open */
3424 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3426 socks = malloc((maxs + 1) * sizeof(int));
3429 syslog(LOG_ERR, "couldn't allocate memory for sockets");
3433 *socks = 0; /* num of sockets counter at start of array */
3435 for (r = res; r; r = r->ai_next) {
3436 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3438 syslog(LOG_DEBUG, "control socket: %m");
3441 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3442 &on, sizeof(on)) < 0)
3444 "control setsockopt (SO_REUSEADDR): %m");
3445 if (r->ai_family == AF_INET6) {
3446 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3447 &on, sizeof(on)) < 0)
3449 "control setsockopt (IPV6_V6ONLY): %m");
3451 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3452 syslog(LOG_DEBUG, "control bind: %m");
3464 syslog(LOG_ERR, "control socket: Couldn't bind to any socket");