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(void);
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);
426 #ifdef VIRTUAL_HOSTING
431 int *ctl_sock, fd, maxfd = -1, nfds, i;
432 fd_set defreadfds, readfds;
436 if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
437 if (errno == EEXIST) {
438 syslog(LOG_ERR, "%s already running, pid %d",
439 getprogname(), (int)pid);
442 syslog(LOG_WARNING, "pidfile_open: %m");
446 * Detach from parent.
448 if (daemon(1, 1) < 0) {
449 syslog(LOG_ERR, "failed to become a daemon");
453 if (pfh != NULL && pidfile_write(pfh) == -1)
454 syslog(LOG_WARNING, "pidfile_write: %m");
456 sa.sa_handler = reapchild;
457 (void)sigaction(SIGCHLD, &sa, NULL);
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]);
531 sa.sa_handler = SIG_DFL;
532 (void)sigaction(SIGCHLD, &sa, NULL);
534 sa.sa_handler = sigurg;
535 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
536 (void)sigaction(SIGURG, &sa, NULL);
538 sigfillset(&sa.sa_mask); /* block all signals in handler */
539 sa.sa_flags = SA_RESTART;
540 sa.sa_handler = sigquit;
541 (void)sigaction(SIGHUP, &sa, NULL);
542 (void)sigaction(SIGINT, &sa, NULL);
543 (void)sigaction(SIGQUIT, &sa, NULL);
544 (void)sigaction(SIGTERM, &sa, NULL);
546 sa.sa_handler = lostconn;
547 (void)sigaction(SIGPIPE, &sa, NULL);
549 addrlen = sizeof(ctrl_addr);
550 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
551 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
554 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
555 #ifdef VIRTUAL_HOSTING
556 /* select our identity from virtual host table */
557 selecthost(&ctrl_addr);
560 if (ctrl_addr.su_family == AF_INET)
562 tos = IPTOS_LOWDELAY;
563 if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
564 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
568 * Disable Nagle on the control channel so that we don't have to wait
569 * for peer's ACK before issuing our next reply.
571 if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
572 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
574 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
576 /* set this here so klogin can use it... */
577 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
579 /* Try to handle urgent data inline */
581 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
582 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
586 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
587 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
589 dolog((struct sockaddr *)&his_addr);
591 * Set up default state
600 /* If logins are disabled, print out the message. */
601 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
602 while (fgets(line, sizeof(line), fd) != NULL) {
603 if ((cp = strchr(line, '\n')) != NULL)
605 lreply(530, "%s", line);
607 (void) fflush(stdout);
609 reply(530, "System not available.");
612 #ifdef VIRTUAL_HOSTING
613 fd = fopen(thishost->welcome, "r");
615 fd = fopen(_PATH_FTPWELCOME, "r");
618 while (fgets(line, sizeof(line), fd) != NULL) {
619 if ((cp = strchr(line, '\n')) != NULL)
621 lreply(220, "%s", line);
623 (void) fflush(stdout);
625 /* reply(220,) must follow */
627 #ifndef VIRTUAL_HOSTING
628 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
629 fatalerror("Ran out of memory.");
630 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
632 hostname[MAXHOSTNAMELEN - 1] = '\0';
635 reply(220, "%s FTP server (%s) ready.", hostname, version);
637 reply(220, "FTP server ready.");
648 syslog(LOG_DEBUG, "lost connection");
656 syslog(LOG_ERR, "got signal %d", signo);
660 #ifdef VIRTUAL_HOSTING
662 * read in virtual host tables (if they exist)
671 char *cp, *mp, *line;
673 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
674 struct ftphost *hrp, *lhrp;
675 struct addrinfo hints, *res, *ai;
678 * Fill in the default host information
680 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
681 fatalerror("Ran out of memory.");
682 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
684 hostname[MAXHOSTNAMELEN - 1] = '\0';
685 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
686 fatalerror("Ran out of memory.");
687 hrp->hostname = hostname;
688 hrp->hostinfo = NULL;
690 memset(&hints, 0, sizeof(hints));
691 hints.ai_flags = AI_CANONNAME;
692 hints.ai_family = AF_UNSPEC;
693 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
695 hrp->statfile = _PATH_FTPDSTATFILE;
696 hrp->welcome = _PATH_FTPWELCOME;
697 hrp->loginmsg = _PATH_FTPLOGINMESG;
698 hrp->anonuser = "ftp";
700 thishost = firsthost = lhrp = hrp;
701 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
702 int addrsize, gothost;
706 while ((line = fgetln(fp, &len)) != NULL) {
712 if (line[len - 1] == '\n') {
713 line[len - 1] = '\0';
716 if ((mp = malloc(len + 1)) == NULL)
717 fatalerror("Ran out of memory.");
718 memcpy(mp, line, len);
722 cp = strtok(line, " \t");
723 /* skip empty lines */
730 statfile = _PATH_FTPDSTATFILE;
731 welcome = _PATH_FTPWELCOME;
732 loginmsg = _PATH_FTPLOGINMESG;
735 * Preparse the line so we can use its info
736 * for all the addresses associated with
737 * the virtual host name.
738 * Field 0, the virtual host name, is special:
739 * it's already parsed off and will be strdup'ed
740 * later, after we know its canonical form.
742 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
743 if (*cp != '-' && (cp = strdup(cp)))
745 case 1: /* anon user permissions */
748 case 2: /* statistics file */
751 case 3: /* welcome message */
754 case 4: /* login message */
757 default: /* programming error */
763 hints.ai_family = AF_UNSPEC;
764 hints.ai_flags = AI_PASSIVE;
765 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
767 for (ai = res; ai != NULL && ai->ai_addr != NULL;
771 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
774 for (hi = hrp->hostinfo; hi != NULL;
776 if (hi->ai_addrlen == ai->ai_addrlen &&
779 ai->ai_addr->sa_len) == 0) {
787 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
789 hrp->hostname = NULL;
792 if (hrp->hostinfo && hrp->hostinfo != res)
793 freeaddrinfo(hrp->hostinfo);
794 insert = 0; /* host already in the chain */
799 * determine hostname to use.
800 * force defined name if there is a valid alias
801 * otherwise fallback to primary hostname
803 /* XXX: getaddrinfo() can't do alias check */
804 switch(hrp->hostinfo->ai_family) {
806 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
807 addrsize = sizeof(struct in_addr);
810 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
811 addrsize = sizeof(struct in6_addr);
814 /* should not reach here */
815 freeaddrinfo(hrp->hostinfo);
817 free(hrp); /*not in chain, can free*/
819 hrp->hostinfo = NULL; /*mark as blank*/
823 if ((hp = getipnodebyaddr(addr, addrsize,
824 hrp->hostinfo->ai_family,
825 &hp_error)) != NULL) {
826 if (strcmp(vhost, hp->h_name) != 0) {
827 if (hp->h_aliases == NULL)
831 while (hp->h_aliases[i] &&
832 strcmp(vhost, hp->h_aliases[i]) != 0)
834 if (hp->h_aliases[i] == NULL)
840 strcmp(hrp->hostname, vhost) != 0) {
842 hrp->hostname = NULL;
844 if (hrp->hostname == NULL &&
845 (hrp->hostname = strdup(vhost)) == NULL) {
846 freeaddrinfo(hrp->hostinfo);
847 hrp->hostinfo = NULL; /* mark as blank */
852 hrp->anonuser = anonuser;
853 hrp->statfile = statfile;
854 hrp->welcome = welcome;
855 hrp->loginmsg = loginmsg;
873 selecthost(union sockunion *su)
878 struct in6_addr *mapped_in6 = NULL;
884 * XXX IPv4 mapped IPv6 addr consideraton,
885 * specified in rfc2373.
887 if (su->su_family == AF_INET6 &&
888 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
889 mapped_in6 = &su->su_sin6.sin6_addr;
892 hrp = thishost = firsthost; /* default */
895 while (hrp != NULL) {
896 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
897 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
902 /* XXX IPv4 mapped IPv6 addr consideraton */
903 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
904 (memcmp(&mapped_in6->s6_addr[12],
905 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
906 sizeof(struct in_addr)) == 0)) {
916 /* setup static variables as appropriate */
917 hostname = thishost->hostname;
918 ftpuser = thishost->anonuser;
923 * Helper function for sgetpwnam().
928 char *new = malloc(strlen(s) + 1);
931 reply(421, "Ran out of memory.");
935 (void) strcpy(new, s);
940 * Save the result of a getpwnam. Used for USER command, since
941 * the data returned must not be clobbered by any other command
943 * NB: The data returned by sgetpwnam() will remain valid until
944 * the next call to this function. Its difference from getpwnam()
945 * is that sgetpwnam() is known to be called from ftpd code only.
947 static struct passwd *
948 sgetpwnam(char *name)
950 static struct passwd save;
953 if ((p = getpwnam(name)) == NULL)
957 free(save.pw_passwd);
963 save.pw_name = sgetsave(p->pw_name);
964 save.pw_passwd = sgetsave(p->pw_passwd);
965 save.pw_gecos = sgetsave(p->pw_gecos);
966 save.pw_dir = sgetsave(p->pw_dir);
967 save.pw_shell = sgetsave(p->pw_shell);
971 static int login_attempts; /* number of failed login attempts */
972 static int askpasswd; /* had user command, ask for passwd */
973 static char curname[MAXLOGNAME]; /* current USER name */
977 * Sets global passwd pointer pw if named account exists and is acceptable;
978 * sets askpasswd if a PASS command is expected. If logged in previously,
979 * need to reset state. If name is "ftp" or "anonymous", the name is not in
980 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
981 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
982 * requesting login privileges. Disallow anyone who does not have a standard
983 * shell as returned by getusershell(). Disallow anyone mentioned in the file
984 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
993 reply(530, "Can't change user from guest login.");
995 } else if (dochroot) {
996 reply(530, "Can't change user from chroot user.");
1003 #ifdef VIRTUAL_HOSTING
1004 pw = sgetpwnam(thishost->anonuser);
1006 pw = sgetpwnam("ftp");
1008 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1009 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL) ||
1010 checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL))
1011 reply(530, "User %s access denied.", name);
1012 else if (pw != NULL) {
1016 "Guest login ok, send your email address as password.");
1018 reply(530, "User %s unknown.", name);
1019 if (!askpasswd && logging)
1021 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1024 if (anon_only != 0) {
1025 reply(530, "Sorry, only anonymous ftp allowed.");
1029 if ((pw = sgetpwnam(name))) {
1030 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1031 shell = _PATH_BSHELL;
1033 while ((cp = getusershell()) != NULL)
1034 if (strcmp(cp, shell) == 0)
1038 if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1, NULL)) {
1039 reply(530, "User %s access denied.", name);
1042 "FTP LOGIN REFUSED FROM %s, %s",
1049 strncpy(curname, name, sizeof(curname)-1);
1053 /* XXX Kluge! The conversation mechanism needs to be fixed. */
1055 if (opiechallenge(&opiedata, name, opieprompt) == 0) {
1056 pwok = (pw != NULL) &&
1057 opieaccessfile(remotehost) &&
1058 opiealways(pw->pw_dir);
1059 reply(331, "Response to %s %s for %s.",
1060 opieprompt, pwok ? "requested" : "required", name);
1063 reply(331, "Password required for %s.", name);
1067 * Delay before reading passwd after first failed
1068 * attempt to slow down passwd-guessing programs.
1071 sleep(login_attempts);
1075 * Check if a user is in the file "fname",
1076 * return a pointer to a malloc'd string with the rest
1077 * of the matching line in "residue" if not NULL.
1080 checkuser(char *fname, char *name, int pwset, char **residue)
1085 char *line, *mp, *p;
1087 if ((fd = fopen(fname, "r")) != NULL) {
1088 while (!found && (line = fgetln(fd, &len)) != NULL) {
1092 if (line[len - 1] == '\n') {
1093 line[len - 1] = '\0';
1096 if ((mp = malloc(len + 1)) == NULL)
1097 fatalerror("Ran out of memory.");
1098 memcpy(mp, line, len);
1102 /* avoid possible leading and trailing whitespace */
1103 p = strtok(line, " \t");
1104 /* skip empty lines */
1108 * if first chr is '@', check group membership
1114 if (p[1] == '\0') /* single @ matches anyone */
1117 if ((grp = getgrnam(p+1)) == NULL)
1120 * Check user's default group
1122 if (pwset && grp->gr_gid == pw->pw_gid)
1125 * Check supplementary groups
1127 while (!found && grp->gr_mem[i])
1128 found = strcmp(name,
1134 * Otherwise, just check for username match
1137 found = strcmp(p, name) == 0;
1139 * Save the rest of line to "residue" if matched
1141 if (found && residue) {
1142 if ((p = strtok(NULL, "")) != NULL)
1143 p += strspn(p, " \t");
1145 if ((*residue = strdup(p)) == NULL)
1146 fatalerror("Ran out of memory.");
1160 * Terminate login as previous user, if any, resetting state;
1161 * used when USER command is given or login fails.
1171 if (logged_in && dowtmp)
1172 ftpd_logwtmp(ttyline, "", NULL);
1175 setusercontext(NULL, getpwuid(0), 0,
1176 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK|
1181 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1182 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1183 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1184 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1185 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1186 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1198 * the following code is stolen from imap-uw PAM authentication module and
1201 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1204 const char *uname; /* user name */
1205 const char *pass; /* password */
1207 typedef struct cred_t cred_t;
1210 auth_conv(int num_msg, const struct pam_message **msg,
1211 struct pam_response **resp, void *appdata)
1214 cred_t *cred = (cred_t *) appdata;
1215 struct pam_response *reply;
1217 reply = calloc(num_msg, sizeof *reply);
1221 for (i = 0; i < num_msg; i++) {
1222 switch (msg[i]->msg_style) {
1223 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1224 reply[i].resp_retcode = PAM_SUCCESS;
1225 reply[i].resp = COPY_STRING(cred->uname);
1226 /* PAM frees resp. */
1228 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1229 reply[i].resp_retcode = PAM_SUCCESS;
1230 reply[i].resp = COPY_STRING(cred->pass);
1231 /* PAM frees resp. */
1235 reply[i].resp_retcode = PAM_SUCCESS;
1236 reply[i].resp = NULL;
1238 default: /* unknown message style */
1240 return PAM_CONV_ERR;
1249 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1250 * authenticated, or 1 if not authenticated. If some sort of PAM system
1251 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1252 * function returns -1. This can be used as an indication that we should
1253 * fall back to a different authentication mechanism.
1256 auth_pam(struct passwd **ppw, const char *pass)
1258 const char *tmpl_user;
1262 cred_t auth_cred = { (*ppw)->pw_name, pass };
1263 struct pam_conv conv = { &auth_conv, &auth_cred };
1265 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1266 if (e != PAM_SUCCESS) {
1268 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1269 * if context creation has failed in the first place.
1271 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
1275 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1276 if (e != PAM_SUCCESS) {
1277 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1278 pam_strerror(pamh, e));
1279 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1280 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1286 e = pam_authenticate(pamh, 0);
1290 * With PAM we support the concept of a "template"
1291 * user. The user enters a login name which is
1292 * authenticated by PAM, usually via a remote service
1293 * such as RADIUS or TACACS+. If authentication
1294 * succeeds, a different but related "template" name
1295 * is used for setting the credentials, shell, and
1296 * home directory. The name the user enters need only
1297 * exist on the remote authentication server, but the
1298 * template name must be present in the local password
1301 * This is supported by two various mechanisms in the
1302 * individual modules. However, from the application's
1303 * point of view, the template user is always passed
1304 * back as a changed value of the PAM_USER item.
1306 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1308 tmpl_user = (const char *) item;
1309 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1310 *ppw = getpwnam(tmpl_user);
1312 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1313 pam_strerror(pamh, e));
1318 case PAM_USER_UNKNOWN:
1324 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1330 e = pam_acct_mgmt(pamh, 0);
1331 if (e != PAM_SUCCESS) {
1332 syslog(LOG_ERR, "pam_acct_mgmt: %s",
1333 pam_strerror(pamh, e));
1339 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1340 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1347 #endif /* USE_PAM */
1355 login_cap_t *lc = NULL;
1360 char *residue = NULL;
1363 if (logged_in || askpasswd == 0) {
1364 reply(503, "Login with USER first.");
1368 if (!guest) { /* "ftp" is only account allowed no password */
1370 rval = 1; /* failure below */
1374 rval = auth_pam(&pw, passwd);
1380 if (opieverify(&opiedata, passwd) == 0)
1381 xpasswd = pw->pw_passwd;
1383 xpasswd = crypt(passwd, pw->pw_passwd);
1384 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1390 rval = strcmp(pw->pw_passwd, xpasswd);
1391 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1392 rval = 1; /* failure */
1395 * If rval == 1, the user failed the authentication check
1396 * above. If rval == 0, either PAM or local authentication
1400 reply(530, "Login incorrect.");
1403 "FTP LOGIN FAILED FROM %s",
1405 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1406 "FTP LOGIN FAILED FROM %s, %s",
1407 remotehost, curname);
1410 if (login_attempts++ >= 5) {
1412 "repeated login failures from %s",
1419 login_attempts = 0; /* this time successful */
1420 if (setegid(pw->pw_gid) < 0) {
1421 reply(550, "Can't set gid.");
1424 /* May be overridden by login.conf */
1425 (void) umask(defumask);
1427 if ((lc = login_getpwclass(pw)) != NULL) {
1428 char remote_ip[NI_MAXHOST];
1430 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1431 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1434 remote_ip[sizeof(remote_ip) - 1] = 0;
1435 if (!auth_hostok(lc, remotehost, remote_ip)) {
1436 syslog(LOG_INFO|LOG_AUTH,
1437 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1439 reply(530, "Permission denied.");
1443 if (!auth_timeok(lc, time(NULL))) {
1444 reply(530, "Login not available right now.");
1449 setusercontext(lc, pw, 0,
1450 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1451 LOGIN_SETRESOURCES|LOGIN_SETUMASK|LOGIN_SETMAC);
1453 setlogin(pw->pw_name);
1454 (void) initgroups(pw->pw_name, pw->pw_gid);
1459 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1460 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1461 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1462 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1467 /* open wtmp before chroot */
1469 ftpd_logwtmp(ttyline, pw->pw_name,
1470 (struct sockaddr *)&his_addr);
1473 if (guest && stats && statfd < 0)
1474 #ifdef VIRTUAL_HOSTING
1475 statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1477 statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1483 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue)
1484 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1485 || login_getcapbool(lc, "ftp-chroot", 0)
1490 * For a chrooted local user,
1491 * a) see whether ftpchroot(5) specifies a chroot directory,
1492 * b) extract the directory pathname from the line,
1493 * c) expand it to the absolute pathname if necessary.
1495 if (dochroot && residue &&
1496 (chrootdir = strtok(residue, " \t")) != NULL) {
1497 if (chrootdir[0] != '/')
1498 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1500 chrootdir = strdup(chrootdir); /* make it permanent */
1501 if (chrootdir == NULL)
1502 fatalerror("Ran out of memory.");
1504 if (guest || dochroot) {
1506 * If no chroot directory set yet, use the login directory.
1507 * Copy it so it can be modified while pw->pw_dir stays intact.
1509 if (chrootdir == NULL &&
1510 (chrootdir = strdup(pw->pw_dir)) == NULL)
1511 fatalerror("Ran out of memory.");
1513 * Check for the "/chroot/./home" syntax,
1514 * separate the chroot and home directory pathnames.
1516 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1517 *(homedir++) = '\0'; /* wipe '/' */
1518 homedir++; /* skip '.' */
1521 * We MUST do a chdir() after the chroot. Otherwise
1522 * the old current directory will be accessible as "."
1523 * outside the new root!
1528 * Finally, do chroot()
1530 if (chroot(chrootdir) < 0) {
1531 reply(550, "Can't change root.");
1534 } else /* real user w/o chroot */
1535 homedir = pw->pw_dir;
1537 * Set euid *before* doing chdir() so
1538 * a) the user won't be carried to a directory that he couldn't reach
1539 * on his own due to no permission to upper path components,
1540 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1541 * (uid 0 has no root power over NFS if not mapped explicitly.)
1543 if (seteuid(pw->pw_uid) < 0) {
1544 reply(550, "Can't set uid.");
1547 if (chdir(homedir) < 0) {
1548 if (guest || dochroot) {
1549 reply(550, "Can't change to base directory.");
1552 if (chdir("/") < 0) {
1553 reply(550, "Root is inaccessible.");
1556 lreply(230, "No directory! Logging in with home=/.");
1561 * Display a login message, if it exists.
1562 * N.B. reply(230,) must follow the message.
1564 #ifdef VIRTUAL_HOSTING
1565 fd = fopen(thishost->loginmsg, "r");
1567 fd = fopen(_PATH_FTPLOGINMESG, "r");
1570 char *cp, line[LINE_MAX];
1572 while (fgets(line, sizeof(line), fd) != NULL) {
1573 if ((cp = strchr(line, '\n')) != NULL)
1575 lreply(230, "%s", line);
1577 (void) fflush(stdout);
1583 ident = strdup(passwd);
1585 fatalerror("Ran out of memory.");
1587 reply(230, "Guest login ok, access restrictions apply.");
1589 #ifdef VIRTUAL_HOSTING
1590 if (thishost != firsthost)
1591 snprintf(proctitle, sizeof(proctitle),
1592 "%s: anonymous(%s)/%s", remotehost, hostname,
1596 snprintf(proctitle, sizeof(proctitle),
1597 "%s: anonymous/%s", remotehost, passwd);
1598 setproctitle("%s", proctitle);
1599 #endif /* SETPROCTITLE */
1601 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1602 remotehost, passwd);
1605 reply(230, "User %s logged in, "
1606 "access restrictions apply.", pw->pw_name);
1608 reply(230, "User %s logged in.", pw->pw_name);
1611 snprintf(proctitle, sizeof(proctitle),
1612 "%s: user/%s", remotehost, pw->pw_name);
1613 setproctitle("%s", proctitle);
1614 #endif /* SETPROCTITLE */
1616 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1617 remotehost, pw->pw_name);
1619 if (logging && (guest || dochroot))
1620 syslog(LOG_INFO, "session root changed to %s", chrootdir);
1628 /* Forget all about it... */
1638 retrieve(char *cmd, char *name)
1642 int (*closefunc)(FILE *);
1646 fin = fopen(name, "r"), closefunc = fclose;
1651 (void) snprintf(line, sizeof(line), cmd, name), name = line;
1652 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1654 st.st_blksize = BUFSIZ;
1658 perror_reply(550, name);
1660 LOGCMD("get", name);
1667 if (fstat(fileno(fin), &st) < 0) {
1668 perror_reply(550, name);
1671 if (!S_ISREG(st.st_mode)) {
1673 * Never sending a raw directory is a workaround
1674 * for buggy clients that will attempt to RETR
1675 * a directory before listing it, e.g., Mozilla.
1676 * Preventing a guest from getting irregular files
1677 * is a simple security measure.
1679 if (S_ISDIR(st.st_mode) || guest) {
1680 reply(550, "%s: not a plain file.", name);
1684 /* st.st_blksize is set for all descriptor types */
1687 if (restart_point) {
1688 if (type == TYPE_A) {
1695 if ((c=getc(fin)) == EOF) {
1696 perror_reply(550, name);
1702 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1703 perror_reply(550, name);
1707 dout = dataconn(name, st.st_size, "w");
1711 send_data(fin, dout, st.st_blksize, st.st_size,
1712 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1713 if (cmd == 0 && guest && stats && byte_count > 0)
1714 logxfer(name, byte_count, start);
1715 (void) fclose(dout);
1720 LOGBYTES("get", name, byte_count);
1725 store(char *name, char *mode, int unique)
1729 int (*closefunc)(FILE *);
1731 if (*mode == 'a') { /* APPE */
1733 /* Programming error */
1734 syslog(LOG_ERR, "Internal: unique flag to APPE");
1737 if (guest && noguestmod) {
1738 reply(550, "Appending to existing file denied.");
1741 restart_point = 0; /* not affected by preceding REST */
1743 if (unique) /* STOU overrides REST */
1745 if (guest && noguestmod) {
1746 if (restart_point) { /* guest STOR w/REST */
1747 reply(550, "Modifying existing file denied.");
1749 } else /* treat guest STOR as STOU */
1754 mode = "r+"; /* so ASCII manual seek can work */
1756 if ((fd = guniquefd(name, &name)) < 0)
1758 fout = fdopen(fd, mode);
1760 fout = fopen(name, mode);
1763 perror_reply(553, name);
1767 if (restart_point) {
1768 if (type == TYPE_A) {
1775 if ((c=getc(fout)) == EOF) {
1776 perror_reply(550, name);
1783 * We must do this seek to "current" position
1784 * because we are changing from reading to
1787 if (fseeko(fout, 0, SEEK_CUR) < 0) {
1788 perror_reply(550, name);
1791 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1792 perror_reply(550, name);
1796 din = dataconn(name, -1, "r");
1799 if (receive_data(din, fout) == 0) {
1801 reply(226, "Transfer complete (unique file name:%s).",
1804 reply(226, "Transfer complete.");
1810 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1814 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1819 getdatasock(char *mode)
1821 int on = 1, s, t, tries;
1824 return (fdopen(data, mode));
1826 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1829 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1830 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1831 /* anchor socket to avoid multi-homing problems */
1832 data_source = ctrl_addr;
1833 data_source.su_port = htons(dataport);
1835 for (tries = 1; ; tries++) {
1837 * We should loop here since it's possible that
1838 * another ftpd instance has passed this point and is
1839 * trying to open a data connection in active mode now.
1840 * Until the other connection is opened, we'll be getting
1841 * EADDRINUSE because no SOCK_STREAM sockets in the system
1842 * can share both local and remote addresses, localIP:20
1843 * and *:* in this case.
1845 if (bind(s, (struct sockaddr *)&data_source,
1846 data_source.su_len) >= 0)
1848 if (errno != EADDRINUSE || tries > 10)
1852 (void) seteuid(pw->pw_uid);
1854 if (data_source.su_family == AF_INET)
1856 on = IPTOS_THROUGHPUT;
1857 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1858 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1863 * Turn off push flag to keep sender TCP from sending short packets
1864 * at the boundaries of each write(). Should probably do a SO_SNDBUF
1865 * to set the send buffer size as well, but that may not be desirable
1866 * in heavy-load situations.
1869 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1870 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1874 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &on, sizeof on) < 0)
1875 syslog(LOG_WARNING, "data setsockopt (SO_SNDBUF): %m");
1878 return (fdopen(s, mode));
1880 /* Return the real value of errno (close may change it) */
1882 (void) seteuid(pw->pw_uid);
1889 dataconn(char *name, off_t size, char *mode)
1893 int retry = 0, tos, conerrno;
1898 (void) snprintf(sizebuf, sizeof(sizebuf),
1899 " (%jd bytes)", (intmax_t)size);
1903 union sockunion from;
1904 socklen_t fromlen = ctrl_addr.su_len;
1906 struct timeval timeout;
1910 FD_SET(pdata, &set);
1912 timeout.tv_usec = 0;
1913 timeout.tv_sec = 120;
1916 * Granted a socket is in the blocking I/O mode,
1917 * accept() will block after a successful select()
1918 * if the selected connection dies in between.
1919 * Therefore set the non-blocking I/O flag here.
1921 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1922 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1924 if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
1925 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1927 (void) close(pdata);
1930 * Unset the inherited non-blocking I/O flag
1931 * on the child socket so stdio can work on it.
1933 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1934 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1937 if (from.su_family == AF_INET)
1939 tos = IPTOS_THROUGHPUT;
1940 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1941 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1944 reply(150, "Opening %s mode data connection for '%s'%s.",
1945 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1946 return (fdopen(pdata, mode));
1948 reply(425, "Can't open data connection.");
1949 (void) close(pdata);
1954 reply(125, "Using existing data connection for '%s'%s.",
1957 return (fdopen(data, mode));
1960 data_dest = his_addr;
1963 file = getdatasock(mode);
1965 char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
1967 if (getnameinfo((struct sockaddr *)&data_source,
1969 hostbuf, sizeof(hostbuf) - 1,
1970 portbuf, sizeof(portbuf) - 1,
1971 NI_NUMERICHOST|NI_NUMERICSERV))
1972 *hostbuf = *portbuf = 0;
1973 hostbuf[sizeof(hostbuf) - 1] = 0;
1974 portbuf[sizeof(portbuf) - 1] = 0;
1975 reply(425, "Can't create data socket (%s,%s): %s.",
1976 hostbuf, portbuf, strerror(errno));
1979 data = fileno(file);
1981 if (connect(data, (struct sockaddr *)&data_dest,
1982 data_dest.su_len) == 0)
1985 (void) fclose(file);
1987 if (conerrno == EADDRINUSE) {
1993 } while (retry <= swaitmax);
1994 if (conerrno != 0) {
1995 reply(425, "Can't build data connection: %s.",
1996 strerror(conerrno));
1999 reply(150, "Opening %s mode data connection for '%s'%s.",
2000 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2005 * A helper macro to avoid code duplication
2006 * in send_data() and receive_data().
2008 * XXX We have to block SIGURG during putc() because BSD stdio
2009 * is unable to restart interrupted write operations and hence
2010 * the entire buffer contents will be lost as soon as a write()
2011 * call indicates EINTR to stdio.
2013 #define FTPD_PUTC(ch, file, label) \
2019 ret = putc((ch), (file)); \
2021 CHECKOOB(return (-1)) \
2022 else if (ferror(file)) \
2025 } while (ret == EOF); \
2029 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
2030 * encapsulation of the data subject to Mode, Structure, and Type.
2032 * NB: Form isn't handled.
2035 send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2037 int c, cp, filefd, netfd;
2048 CHECKOOB(return (-1))
2049 else if (c == EOF && ferror(instr))
2052 if (ferror(instr)) { /* resume after OOB */
2056 if (feof(instr)) /* EOF */
2058 syslog(LOG_ERR, "Internal: impossible condition"
2059 " on file after getc()");
2062 if (c == '\n' && cp != '\r') {
2063 FTPD_PUTC('\r', outstr, data_err);
2066 FTPD_PUTC(c, outstr, data_err);
2070 #ifdef notyet /* BSD stdio isn't ready for that */
2071 while (fflush(outstr) == EOF) {
2072 CHECKOOB(return (-1))
2080 if (fflush(outstr) == EOF)
2083 reply(226, "Transfer complete.");
2089 * isreg is only set if we are not doing restart and we
2090 * are sending a regular file
2092 netfd = fileno(outstr);
2093 filefd = fileno(instr);
2096 char *msg = "Transfer complete.";
2102 while (filesize > 0) {
2103 err = sendfile(filefd, netfd, offset, 0,
2106 * Calculate byte_count before OOB processing.
2107 * It can be used in myoob() later.
2112 CHECKOOB(return (-1))
2113 else if (err == -1) {
2114 if (errno != EINTR &&
2115 cnt == 0 && offset == 0)
2119 if (err == -1) /* resume after OOB */
2122 * We hit the EOF prematurely.
2123 * Perhaps the file was externally truncated.
2126 msg = "Transfer finished due to "
2127 "premature end of file.";
2137 if ((buf = malloc(blksize)) == NULL) {
2139 reply(451, "Ran out of memory.");
2147 cnt = read(filefd, buf, blksize);
2148 CHECKOOB(free(buf); return (-1))
2153 if (cnt < 0) /* resume after OOB */
2155 if (cnt == 0) /* EOF */
2157 for (len = cnt, bp = buf; len > 0;) {
2158 cnt = write(netfd, bp, len);
2159 CHECKOOB(free(buf); return (-1))
2173 reply(226, "Transfer complete.");
2177 reply(550, "Unimplemented TYPE %d in send_data.", type);
2183 perror_reply(426, "Data connection");
2188 perror_reply(551, "Error on input file");
2193 * Transfer data from peer to "outstr" using the appropriate encapulation of
2194 * the data subject to Mode, Structure, and Type.
2196 * N.B.: Form isn't handled.
2199 receive_data(FILE *instr, FILE *outstr)
2215 cnt = read(fileno(instr), buf, sizeof(buf));
2216 CHECKOOB(return (-1))
2219 if (cnt < 0) /* resume after OOB */
2221 if (cnt == 0) /* EOF */
2223 for (len = cnt, bp = buf; len > 0;) {
2224 cnt = write(fileno(outstr), bp, len);
2225 CHECKOOB(return (-1))
2240 reply(553, "TYPE E not implemented.");
2247 CHECKOOB(return (-1))
2248 else if (c == EOF && ferror(instr))
2250 if (c == EOF && ferror(instr)) { /* resume after OOB */
2257 FTPD_PUTC('\r', outstr, file_err);
2267 /* Check for EOF here in order not to lose last \r. */
2269 if (feof(instr)) /* EOF */
2271 syslog(LOG_ERR, "Internal: impossible condition"
2272 " on data stream after getc()");
2277 FTPD_PUTC(c, outstr, file_err);
2280 #ifdef notyet /* BSD stdio isn't ready for that */
2281 while (fflush(outstr) == EOF) {
2282 CHECKOOB(return (-1))
2290 if (fflush(outstr) == EOF)
2295 "WARNING! %d bare linefeeds received in ASCII mode.",
2297 (void)printf(" File may not have transferred correctly.\r\n");
2302 reply(550, "Unimplemented TYPE %d in receive_data.", type);
2308 perror_reply(426, "Data connection");
2313 perror_reply(452, "Error writing to file");
2318 statfilecmd(char *filename)
2323 char line[LINE_MAX];
2326 code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2327 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2328 fin = ftpd_popen(line, "r");
2329 lreply(code, "Status of %s:", filename);
2331 while ((c = getc(fin)) != EOF) {
2333 if (ferror(stdout)){
2334 perror_reply(421, "Control connection");
2335 (void) ftpd_pclose(fin);
2340 perror_reply(551, filename);
2341 (void) ftpd_pclose(fin);
2344 (void) putc('\r', stdout);
2347 * RFC 959 says neutral text should be prepended before
2348 * a leading 3-digit number followed by whitespace, but
2349 * many ftp clients can be confused by any leading digits,
2350 * as a matter of fact.
2352 if (atstart && isdigit(c))
2353 (void) putc(' ', stdout);
2354 (void) putc(c, stdout);
2355 atstart = (c == '\n');
2357 (void) ftpd_pclose(fin);
2358 reply(code, "End of status.");
2364 union sockunion *su;
2366 char hname[NI_MAXHOST];
2370 lreply(211, "%s FTP server status:", hostname);
2371 printf(" %s\r\n", version);
2373 lreply(211, "FTP server status:");
2374 printf(" Connected to %s", remotehost);
2375 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2376 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2377 hname[sizeof(hname) - 1] = 0;
2378 if (strcmp(hname, remotehost) != 0)
2379 printf(" (%s)", hname);
2384 printf(" Logged in anonymously\r\n");
2386 printf(" Logged in as %s\r\n", pw->pw_name);
2387 } else if (askpasswd)
2388 printf(" Waiting for password\r\n");
2390 printf(" Waiting for user name\r\n");
2391 printf(" TYPE: %s", typenames[type]);
2392 if (type == TYPE_A || type == TYPE_E)
2393 printf(", FORM: %s", formnames[form]);
2396 printf(" %d", CHAR_BIT);
2398 printf(" %d", bytesize); /* need definition! */
2400 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2401 strunames[stru], modenames[mode]);
2403 printf(" Data connection open\r\n");
2404 else if (pdata != -1) {
2408 } else if (usedefault == 0) {
2412 #define UC(b) (((int) b) & 0xff)
2414 printf(" EPSV only mode (EPSV ALL)\r\n");
2419 if (su->su_family == AF_INET) {
2420 a = (u_char *) &su->su_sin.sin_addr;
2421 p = (u_char *) &su->su_sin.sin_port;
2422 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2423 ispassive ? "PASV" : "PORT",
2424 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2425 UC(p[0]), UC(p[1]));
2432 switch (su->su_family) {
2434 a = (u_char *) &su->su_sin.sin_addr;
2435 p = (u_char *) &su->su_sin.sin_port;
2436 alen = sizeof(su->su_sin.sin_addr);
2440 a = (u_char *) &su->su_sin6.sin6_addr;
2441 p = (u_char *) &su->su_sin6.sin6_port;
2442 alen = sizeof(su->su_sin6.sin6_addr);
2450 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2452 for (i = 0; i < alen; i++)
2453 printf("%d,", UC(a[i]));
2454 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2463 switch (su->su_family) {
2475 union sockunion tmp;
2478 if (tmp.su_family == AF_INET6)
2479 tmp.su_sin6.sin6_scope_id = 0;
2480 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2481 hname, sizeof(hname) - 1, NULL, 0,
2483 hname[sizeof(hname) - 1] = 0;
2484 printf(" %s |%d|%s|%d|\r\n",
2485 ispassive ? "EPSV" : "EPRT",
2486 af, hname, htons(tmp.su_port));
2492 printf(" No data connection\r\n");
2493 reply(211, "End of status.");
2500 reply(451, "Error in server: %s", s);
2501 reply(221, "Closing connection due to server error.");
2507 reply(int n, const char *fmt, ...)
2511 (void)printf("%d ", n);
2513 (void)vprintf(fmt, ap);
2515 (void)printf("\r\n");
2516 (void)fflush(stdout);
2518 syslog(LOG_DEBUG, "<--- %d ", n);
2520 vsyslog(LOG_DEBUG, fmt, ap);
2526 lreply(int n, const char *fmt, ...)
2530 (void)printf("%d- ", n);
2532 (void)vprintf(fmt, ap);
2534 (void)printf("\r\n");
2535 (void)fflush(stdout);
2537 syslog(LOG_DEBUG, "<--- %d- ", n);
2539 vsyslog(LOG_DEBUG, fmt, ap);
2548 reply(250, "%s command successful.", s);
2555 reply(502, "%s command not implemented.", s);
2564 if ((cp = strchr(cbuf,'\n')))
2566 reply(500, "%s: command not understood.", cbuf);
2574 LOGCMD("delete", name);
2575 if (lstat(name, &st) < 0) {
2576 perror_reply(550, name);
2579 if (S_ISDIR(st.st_mode)) {
2580 if (rmdir(name) < 0) {
2581 perror_reply(550, name);
2586 if (guest && noguestmod) {
2587 reply(550, "Operation not permitted.");
2590 if (unlink(name) < 0) {
2591 perror_reply(550, name);
2602 if (chdir(path) < 0)
2603 perror_reply(550, path);
2613 LOGCMD("mkdir", name);
2614 if (guest && noguestmkd)
2615 reply(550, "Operation not permitted.");
2616 else if (mkdir(name, 0777) < 0)
2617 perror_reply(550, name);
2619 if ((s = doublequote(name)) == NULL)
2620 fatalerror("Ran out of memory.");
2621 reply(257, "\"%s\" directory created.", s);
2627 removedir(char *name)
2630 LOGCMD("rmdir", name);
2631 if (rmdir(name) < 0)
2632 perror_reply(550, name);
2640 char *s, path[MAXPATHLEN + 1];
2642 if (getcwd(path, sizeof(path)) == NULL)
2643 perror_reply(550, "Get current directory");
2645 if ((s = doublequote(path)) == NULL)
2646 fatalerror("Ran out of memory.");
2647 reply(257, "\"%s\" is current directory.", s);
2653 renamefrom(char *name)
2657 if (guest && noguestmod) {
2658 reply(550, "Operation not permitted.");
2661 if (lstat(name, &st) < 0) {
2662 perror_reply(550, name);
2665 reply(350, "File exists, ready for destination name.");
2670 renamecmd(char *from, char *to)
2674 LOGCMD2("rename", from, to);
2676 if (guest && (stat(to, &st) == 0)) {
2677 reply(550, "%s: permission denied.", to);
2681 if (rename(from, to) < 0)
2682 perror_reply(550, "rename");
2688 dolog(struct sockaddr *who)
2690 char who_name[NI_MAXHOST];
2692 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2693 remotehost[sizeof(remotehost) - 1] = 0;
2694 if (getnameinfo(who, who->sa_len,
2695 who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
2697 who_name[sizeof(who_name) - 1] = 0;
2700 #ifdef VIRTUAL_HOSTING
2701 if (thishost != firsthost)
2702 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2703 remotehost, hostname);
2706 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2708 setproctitle("%s", proctitle);
2709 #endif /* SETPROCTITLE */
2712 #ifdef VIRTUAL_HOSTING
2713 if (thishost != firsthost)
2714 syslog(LOG_INFO, "connection from %s (%s) to %s",
2715 remotehost, who_name, hostname);
2718 syslog(LOG_INFO, "connection from %s (%s)",
2719 remotehost, who_name);
2724 * Record logout in wtmp file
2725 * and exit with supplied status.
2728 dologout(int status)
2731 if (logged_in && dowtmp) {
2733 ftpd_logwtmp(ttyline, "", NULL);
2735 /* beware of flushing buffers after a SIGPIPE */
2753 syslog(LOG_ERR, "Internal: maskurg() while no transfer");
2758 sigaddset(&sset, SIGURG);
2759 sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
2769 syslog(LOG_ERR, "Internal: flagxfer(1): "
2770 "transfer already under way");
2776 syslog(LOG_ERR, "Internal: flagxfer(0): "
2777 "no active transfer");
2784 * Returns 0 if OK to resume or -1 if abort requested.
2792 syslog(LOG_ERR, "Internal: myoob() while no transfer");
2796 if (getline(cp, 7, stdin) == NULL) {
2797 reply(221, "You could at least say goodbye.");
2801 if (strcmp(cp, "ABOR\r\n") == 0) {
2803 reply(426, "Transfer aborted. Data connection closed.");
2804 reply(226, "Abort successful.");
2807 if (strcmp(cp, "STAT\r\n") == 0) {
2809 if (file_size != -1)
2810 reply(213, "Status: %jd of %jd bytes transferred.",
2811 (intmax_t)byte_count, (intmax_t)file_size);
2813 reply(213, "Status: %jd bytes transferred.",
2814 (intmax_t)byte_count);
2820 * Note: a response of 425 is not mentioned as a possible response to
2821 * the PASV command in RFC959. However, it has been blessed as
2822 * a legitimate response by Jon Postel in a telephone conversation
2823 * with Rick Adams on 25 Jan 89.
2832 if (pdata >= 0) /* close old port if one set */
2835 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2837 perror_reply(425, "Can't open passive connection");
2841 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2842 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2847 if (ctrl_addr.su_family == AF_INET) {
2848 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2849 : IP_PORTRANGE_DEFAULT;
2851 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2852 &on, sizeof(on)) < 0)
2856 #ifdef IPV6_PORTRANGE
2857 if (ctrl_addr.su_family == AF_INET6) {
2858 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2859 : IPV6_PORTRANGE_DEFAULT;
2861 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2862 &on, sizeof(on)) < 0)
2867 pasv_addr = ctrl_addr;
2868 pasv_addr.su_port = 0;
2869 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2872 (void) seteuid(pw->pw_uid);
2874 len = sizeof(pasv_addr);
2875 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2877 if (listen(pdata, 1) < 0)
2879 if (pasv_addr.su_family == AF_INET)
2880 a = (char *) &pasv_addr.su_sin.sin_addr;
2881 else if (pasv_addr.su_family == AF_INET6 &&
2882 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2883 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2887 p = (char *) &pasv_addr.su_port;
2889 #define UC(b) (((int) b) & 0xff)
2891 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2892 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2896 (void) seteuid(pw->pw_uid);
2897 (void) close(pdata);
2899 perror_reply(425, "Can't open passive connection");
2904 * Long Passive defined in RFC 1639.
2905 * 228 Entering Long Passive Mode
2906 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2910 long_passive(char *cmd, int pf)
2916 if (pdata >= 0) /* close old port if one set */
2919 if (pf != PF_UNSPEC) {
2920 if (ctrl_addr.su_family != pf) {
2921 switch (ctrl_addr.su_family) {
2934 * only EPRT/EPSV ready clients will understand this
2936 if (strcmp(cmd, "EPSV") == 0 && pf) {
2937 reply(522, "Network protocol mismatch, "
2940 reply(501, "Network protocol mismatch."); /*XXX*/
2946 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2948 perror_reply(425, "Can't open passive connection");
2952 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2953 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2957 pasv_addr = ctrl_addr;
2958 pasv_addr.su_port = 0;
2959 len = pasv_addr.su_len;
2962 if (ctrl_addr.su_family == AF_INET) {
2963 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2964 : IP_PORTRANGE_DEFAULT;
2966 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2967 &on, sizeof(on)) < 0)
2971 #ifdef IPV6_PORTRANGE
2972 if (ctrl_addr.su_family == AF_INET6) {
2973 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2974 : IPV6_PORTRANGE_DEFAULT;
2976 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2977 &on, sizeof(on)) < 0)
2982 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2985 (void) seteuid(pw->pw_uid);
2987 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2989 if (listen(pdata, 1) < 0)
2992 #define UC(b) (((int) b) & 0xff)
2994 if (strcmp(cmd, "LPSV") == 0) {
2995 p = (char *)&pasv_addr.su_port;
2996 switch (pasv_addr.su_family) {
2998 a = (char *) &pasv_addr.su_sin.sin_addr;
3001 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3002 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3003 2, UC(p[0]), UC(p[1]));
3006 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
3007 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
3010 a = (char *) &pasv_addr.su_sin6.sin6_addr;
3012 "Entering Long Passive Mode "
3013 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3014 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3015 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3016 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3017 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3018 2, UC(p[0]), UC(p[1]));
3021 } else if (strcmp(cmd, "EPSV") == 0) {
3022 switch (pasv_addr.su_family) {
3025 reply(229, "Entering Extended Passive Mode (|||%d|)",
3026 ntohs(pasv_addr.su_port));
3030 /* more proper error code? */
3034 (void) seteuid(pw->pw_uid);
3035 (void) close(pdata);
3037 perror_reply(425, "Can't open passive connection");
3042 * Generate unique name for file with basename "local"
3043 * and open the file in order to avoid possible races.
3044 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3045 * Return descriptor to the file, set "name" to its name.
3047 * Generates failure reply on error.
3050 guniquefd(char *local, char **name)
3052 static char new[MAXPATHLEN];
3058 cp = strrchr(local, '/');
3061 if (stat(cp ? local : ".", &st) < 0) {
3062 perror_reply(553, cp ? local : ".");
3067 * Let not overwrite dirname with counter suffix.
3069 * In this extreme case dot won't be put in front of suffix.
3071 if (strlen(local) > sizeof(new) - 4) {
3072 reply(553, "Pathname too long.");
3077 /* -4 is for the .nn<null> we put on the end below */
3078 (void) snprintf(new, sizeof(new) - 4, "%s", local);
3079 cp = new + strlen(new);
3081 * Don't generate dotfile unless requested explicitly.
3082 * This covers the case when basename gets truncated off
3085 if (cp > new && cp[-1] != '/')
3087 for (count = 0; count < 100; count++) {
3088 /* At count 0 try unmodified name */
3090 (void)sprintf(cp, "%d", count);
3091 if ((fd = open(count ? new : local,
3092 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3093 *name = count ? new : local;
3096 if (errno != EEXIST) {
3097 perror_reply(553, count ? new : local);
3101 reply(452, "Unique file name cannot be created.");
3106 * Format and send reply containing system error number.
3109 perror_reply(int code, char *string)
3112 reply(code, "%s: %s.", string, strerror(errno));
3115 static char *onefile[] = {
3121 send_file_list(char *whichf)
3127 char **dirlist, *dirname;
3132 if (strpbrk(whichf, "~{[*?") != NULL) {
3133 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3135 memset(&gl, 0, sizeof(gl));
3136 gl.gl_matchc = MAXGLOBARGS;
3137 flags |= GLOB_LIMIT;
3139 if (glob(whichf, flags, 0, &gl)) {
3140 reply(550, "No matching files found.");
3142 } else if (gl.gl_pathc == 0) {
3144 perror_reply(550, whichf);
3147 dirlist = gl.gl_pathv;
3149 onefile[0] = whichf;
3154 while ((dirname = *dirlist++)) {
3155 if (stat(dirname, &st) < 0) {
3157 * If user typed "ls -l", etc, and the client
3158 * used NLST, do what the user meant.
3160 if (dirname[0] == '-' && *dirlist == NULL &&
3162 retrieve(_PATH_LS " %s", dirname);
3164 perror_reply(550, whichf);
3168 if (S_ISREG(st.st_mode)) {
3170 dout = dataconn("file list", -1, "w");
3176 fprintf(dout, "%s%s\n", dirname,
3177 type == TYPE_A ? "\r" : "");
3181 byte_count += strlen(dirname) +
3182 (type == TYPE_A ? 2 : 1);
3183 CHECKOOB(goto abrt);
3185 } else if (!S_ISDIR(st.st_mode))
3188 if ((dirp = opendir(dirname)) == NULL)
3191 while ((dir = readdir(dirp)) != NULL) {
3192 char nbuf[MAXPATHLEN];
3194 CHECKOOB(goto abrt);
3196 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
3198 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3202 snprintf(nbuf, sizeof(nbuf),
3203 "%s/%s", dirname, dir->d_name);
3206 * We have to do a stat to insure it's
3207 * not a directory or special file.
3209 if (simple || (stat(nbuf, &st) == 0 &&
3210 S_ISREG(st.st_mode))) {
3212 dout = dataconn("file list", -1, "w");
3218 if (nbuf[0] == '.' && nbuf[1] == '/')
3219 fprintf(dout, "%s%s\n", &nbuf[2],
3220 type == TYPE_A ? "\r" : "");
3222 fprintf(dout, "%s%s\n", nbuf,
3223 type == TYPE_A ? "\r" : "");
3227 byte_count += strlen(nbuf) +
3228 (type == TYPE_A ? 2 : 1);
3229 CHECKOOB(goto abrt);
3232 (void) closedir(dirp);
3237 reply(550, "No files found.");
3238 else if (ferror(dout))
3239 data_err: perror_reply(550, "Data connection");
3241 reply(226, "Transfer complete.");
3246 (void) fclose(dout);
3251 (void) closedir(dirp);
3259 reapchild(int signo)
3261 while (waitpid(-1, NULL, WNOHANG) > 0);
3264 #ifdef OLD_SETPROCTITLE
3266 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.)
3267 * Warning, since this is usually started from inetd.conf, it often doesn't
3268 * have much of an environment or arglist to overwrite.
3271 setproctitle(const char *fmt, ...)
3279 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
3281 /* make ps print our process name */
3286 if (i > LastArgv - p - 2) {
3287 i = LastArgv - p - 2;
3292 if (ch != '\n' && ch != '\r')
3294 while (p < LastArgv)
3297 #endif /* OLD_SETPROCTITLE */
3300 appendf(char **strp, char *fmt, ...)
3306 vasprintf(&p, fmt, ap);
3309 fatalerror("Ran out of memory.");
3314 asprintf(strp, "%s%s", ostr, p);
3316 fatalerror("Ran out of memory.");
3322 logcmd(char *cmd, char *file1, char *file2, off_t cnt)
3325 char wd[MAXPATHLEN + 1];
3330 if (getcwd(wd, sizeof(wd) - 1) == NULL)
3331 strcpy(wd, strerror(errno));
3333 appendf(&msg, "%s", cmd);
3335 appendf(&msg, " %s", file1);
3337 appendf(&msg, " %s", file2);
3339 appendf(&msg, " = %jd bytes", (intmax_t)cnt);
3340 appendf(&msg, " (wd: %s", wd);
3341 if (guest || dochroot)
3342 appendf(&msg, "; chrooted");
3344 syslog(LOG_INFO, "%s", msg);
3349 logxfer(char *name, off_t size, time_t start)
3351 char buf[MAXPATHLEN + 1024];
3352 char path[MAXPATHLEN + 1];
3357 if (realpath(name, path) == NULL) {
3358 syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
3361 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n",
3362 ctime(&now)+4, ident, remotehost,
3363 path, (intmax_t)size,
3364 (long)(now - start + (now == start)));
3365 write(statfd, buf, strlen(buf));
3370 doublequote(char *s)
3375 for (p = s, n = 0; *p; p++)
3379 if ((s2 = malloc(p - s + n + 1)) == NULL)
3382 for (p = s2; *s; s++, p++) {
3383 if ((*p = *s) == '"')
3391 /* setup server socket for specified address family */
3392 /* if af is PF_UNSPEC more than one socket may be returned */
3393 /* the returned list is dynamically allocated, so caller needs to free it */
3395 socksetup(int af, char *bindname, const char *bindport)
3397 struct addrinfo hints, *res, *r;
3398 int error, maxs, *s, *socks;
3401 memset(&hints, 0, sizeof(hints));
3402 hints.ai_flags = AI_PASSIVE;
3403 hints.ai_family = af;
3404 hints.ai_socktype = SOCK_STREAM;
3405 error = getaddrinfo(bindname, bindport, &hints, &res);
3407 syslog(LOG_ERR, "%s", gai_strerror(error));
3408 if (error == EAI_SYSTEM)
3409 syslog(LOG_ERR, "%s", strerror(errno));
3413 /* Count max number of sockets we may open */
3414 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3416 socks = malloc((maxs + 1) * sizeof(int));
3419 syslog(LOG_ERR, "couldn't allocate memory for sockets");
3423 *socks = 0; /* num of sockets counter at start of array */
3425 for (r = res; r; r = r->ai_next) {
3426 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3428 syslog(LOG_DEBUG, "control socket: %m");
3431 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3432 &on, sizeof(on)) < 0)
3434 "control setsockopt (SO_REUSEADDR): %m");
3435 if (r->ai_family == AF_INET6) {
3436 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3437 &on, sizeof(on)) < 0)
3439 "control setsockopt (IPV6_V6ONLY): %m");
3441 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3442 syslog(LOG_DEBUG, "control bind: %m");
3454 syslog(LOG_ERR, "control socket: Couldn't bind to any socket");