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
33 * @(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994 The Regents of the University of California. All rights reserved.
34 * @(#)ftpd.c 8.4 (Berkeley) 4/16/94
38 static const char rcsid[] =
39 "$FreeBSD: src/libexec/ftpd/ftpd.c,v 1.62.2.48 2003/02/14 12:42:42 yar Exp $";
40 "$DragonFly: src/libexec/ftpd/ftpd.c,v 1.6 2005/08/08 16:17:04 joerg Exp $";
46 #include <sys/param.h>
47 #include <sys/ioctl.h>
49 #include <sys/socket.h>
54 #include <netinet/in.h>
55 #include <netinet/in_systm.h>
56 #include <netinet/ip.h>
57 #include <netinet/tcp.h>
61 #include <arpa/inet.h>
62 #include <arpa/telnet.h>
83 #include <login_cap.h>
91 #include <security/pam_appl.h>
94 #include "pathnames.h"
103 static char version[] = "Version 6.00LS";
106 extern off_t restart_point;
109 union sockunion server_addr;
110 union sockunion ctrl_addr;
111 union sockunion data_source;
112 union sockunion data_dest;
113 union sockunion his_addr;
114 union sockunion pasv_addr;
119 int hostinfo = 1; /* print host-specific info in messages */
124 int timeout = 900; /* timeout after 15 minutes of inactivity */
125 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
127 int restricted_data_ports = 1;
128 int paranoid = 1; /* be extra careful about security */
129 int anon_only = 0; /* Only anonymous ftp allowed */
137 int stru; /* avoid C keyword */
139 int usedefault = 1; /* for data transfers */
140 int pdata = -1; /* for passive mode */
141 int readonly=0; /* Server is in readonly mode. */
142 int noepsv=0; /* EPSV command is disabled. */
143 int noretr=0; /* RETR command is disabled. */
144 int noguestretr=0; /* RETR command is disabled for anon users. */
145 int noguestmkd=0; /* MKD command is disabled for anon users. */
146 int noguestmod=1; /* anon users may not modify existing files. */
148 static volatile sig_atomic_t recvurg;
149 sig_atomic_t transflag;
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[MAXHOSTNAMELEN];
178 static char ttyline[20];
179 char *tty = ttyline; /* for klogin */
182 static int auth_pam (struct passwd**, const char*);
185 char *pid_file = NULL;
188 * Limit number of pathnames that glob can return.
189 * A limit of 0 indicates the number of pathnames is unlimited.
191 #define MAXGLOBARGS 16384
195 * Timeout intervals for retrying connections
196 * to hosts that don't accept PORT cmds. This
197 * is a kludge, but given the problems with TCP...
199 #define SWAITMAX 90 /* wait at most 90 seconds */
200 #define SWAITINT 5 /* interval between retries */
202 int swaitmax = SWAITMAX;
203 int swaitint = SWAITINT;
206 #ifdef OLD_SETPROCTITLE
207 char **Argv = NULL; /* pointer to argument vector */
208 char *LastArgv = NULL; /* end of argv */
209 #endif /* OLD_SETPROCTITLE */
210 char proctitle[LINE_MAX]; /* initial part of title */
211 #endif /* SETPROCTITLE */
217 #define LOGCMD(cmd, file) \
219 syslog(LOG_INFO,"%s %s%s", cmd, \
220 *(file) == '/' ? "" : curdir(), file);
221 #define LOGCMD2(cmd, file1, file2) \
223 syslog(LOG_INFO,"%s %s%s %s%s", cmd, \
224 *(file1) == '/' ? "" : curdir(), file1, \
225 *(file2) == '/' ? "" : curdir(), file2);
226 #define LOGBYTES(cmd, file, cnt) \
228 if (cnt == (off_t)-1) \
229 syslog(LOG_INFO,"%s %s%s", cmd, \
230 *(file) == '/' ? "" : curdir(), file); \
232 syslog(LOG_INFO, "%s %s%s = %qd bytes", \
233 cmd, (*(file) == '/') ? "" : curdir(), file, cnt); \
236 #ifdef VIRTUAL_HOSTING
237 static void inithosts (void);
238 static void selecthost (union sockunion *);
240 static void ack (char *);
241 static void sigurg (int);
242 static void myoob (void);
243 static int checkuser (char *, char *, int, char **);
244 static FILE *dataconn (char *, off_t, char *);
245 static void dolog (struct sockaddr *);
246 static char *curdir (void);
247 static void end_login (void);
248 static FILE *getdatasock (char *);
249 static int guniquefd (char *, char **);
250 static void lostconn (int);
251 static void sigquit (int);
252 static int receive_data (FILE *, FILE *);
253 static int send_data (FILE *, FILE *, off_t, off_t, int);
254 static struct passwd *
256 static char *sgetsave (char *);
257 static void reapchild (int);
258 static void logxfer (char *, off_t, time_t);
259 static char *doublequote (char *);
264 static char path[MAXPATHLEN+1+1]; /* path + '/' + '\0' */
266 if (getcwd(path, sizeof(path)-2) == NULL)
268 if (path[1] != '\0') /* special case for root dir. */
270 /* For guest account, skip / since it's chrooted */
271 return (guest ? path+1 : path);
275 main(argc, argv, envp)
280 int addrlen, ch, on = 1, tos;
281 char *cp, line[LINE_MAX];
284 char *bindname = NULL;
285 const char *bindport = "ftp";
286 int family = AF_UNSPEC;
290 tzset(); /* in case no timezone database in ~ftp */
291 sigemptyset(&sa.sa_mask);
292 sa.sa_flags = SA_RESTART;
294 #ifdef OLD_SETPROCTITLE
296 * Save start and extent of argv for setproctitle.
301 LastArgv = envp[-1] + strlen(envp[-1]);
302 #endif /* OLD_SETPROCTITLE */
305 while ((ch = getopt(argc, argv,
306 "46a:AdDEhlmMoOp:P:rRSt:T:u:UvW")) != -1) {
310 if (family == AF_UNSPEC)
343 logging++; /* > 1 == extra logging */
383 timeout = atoi(optarg);
384 if (maxtimeout < timeout)
385 maxtimeout = timeout;
389 maxtimeout = atoi(optarg);
390 if (timeout > maxtimeout)
391 timeout = maxtimeout;
398 val = strtol(optarg, &optarg, 8);
399 if (*optarg != '\0' || val < 0)
400 warnx("bad value for -u");
406 restricted_data_ports = 0;
418 warnx("unknown flag -%c ignored", optopt);
423 #ifdef VIRTUAL_HOSTING
426 (void) freopen(_PATH_DEVNULL, "w", stderr);
429 * LOG_NDELAY sets up the logging connection immediately,
430 * necessary for anonymous ftp's that chroot and can't do it later.
432 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
436 struct addrinfo hints, *res;
439 * Detach from parent.
441 if (daemon(1, 1) < 0) {
442 syslog(LOG_ERR, "failed to become a daemon");
445 sa.sa_handler = reapchild;
446 (void)sigaction(SIGCHLD, &sa, NULL);
448 memset(&hints, 0, sizeof(hints));
450 hints.ai_family = family == AF_UNSPEC ? AF_INET : family;
451 hints.ai_socktype = SOCK_STREAM;
452 hints.ai_protocol = 0;
453 hints.ai_flags = AI_PASSIVE;
454 error = getaddrinfo(bindname, bindport, &hints, &res);
456 if (family == AF_UNSPEC) {
457 hints.ai_family = AF_UNSPEC;
458 error = getaddrinfo(bindname, bindport, &hints,
463 syslog(LOG_ERR, "%s", gai_strerror(error));
464 if (error == EAI_SYSTEM)
465 syslog(LOG_ERR, "%s", strerror(errno));
468 if (res->ai_addr == NULL) {
469 syslog(LOG_ERR, "-a %s: getaddrinfo failed", hostname);
472 family = res->ai_addr->sa_family;
474 * Open a socket, bind it to the FTP port, and start
477 ctl_sock = socket(family, SOCK_STREAM, 0);
479 syslog(LOG_ERR, "control socket: %m");
482 if (setsockopt(ctl_sock, SOL_SOCKET, SO_REUSEADDR,
483 &on, sizeof(on)) < 0)
485 "control setsockopt (SO_REUSEADDR): %m");
486 if (family == AF_INET6 && enable_v4 == 0) {
487 if (setsockopt(ctl_sock, IPPROTO_IPV6, IPV6_V6ONLY,
488 &on, sizeof (on)) < 0)
490 "control setsockopt (IPV6_V6ONLY): %m");
492 memcpy(&server_addr, res->ai_addr, res->ai_addr->sa_len);
493 if (bind(ctl_sock, (struct sockaddr *)&server_addr,
494 server_addr.su_len) < 0) {
495 syslog(LOG_ERR, "control bind: %m");
498 if (listen(ctl_sock, 32) < 0) {
499 syslog(LOG_ERR, "control listen: %m");
503 * Atomically write process ID
510 fd = open(pid_file, O_CREAT | O_WRONLY | O_TRUNC
511 | O_NONBLOCK | O_EXLOCK, 0644);
514 errx(1, "%s: file locked", pid_file);
516 err(1, "%s", pid_file);
518 snprintf(buf, sizeof(buf),
519 "%lu\n", (unsigned long) getpid());
520 if (write(fd, buf, strlen(buf)) < 0)
521 err(1, "%s: write", pid_file);
522 /* Leave the pid file open and locked */
525 * Loop forever accepting connection requests and forking off
526 * children to handle them.
529 addrlen = server_addr.su_len;
530 fd = accept(ctl_sock, (struct sockaddr *)&his_addr, &addrlen);
544 addrlen = sizeof(his_addr);
545 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
546 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
551 sa.sa_handler = SIG_DFL;
552 (void)sigaction(SIGCHLD, &sa, NULL);
554 sa.sa_handler = sigurg;
555 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
556 (void)sigaction(SIGURG, &sa, NULL);
558 sigfillset(&sa.sa_mask); /* block all signals in handler */
559 sa.sa_flags = SA_RESTART;
560 sa.sa_handler = sigquit;
561 (void)sigaction(SIGHUP, &sa, NULL);
562 (void)sigaction(SIGINT, &sa, NULL);
563 (void)sigaction(SIGQUIT, &sa, NULL);
564 (void)sigaction(SIGTERM, &sa, NULL);
566 sa.sa_handler = lostconn;
567 (void)sigaction(SIGPIPE, &sa, NULL);
569 addrlen = sizeof(ctrl_addr);
570 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
571 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
574 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
575 #ifdef VIRTUAL_HOSTING
576 /* select our identity from virtual host table */
577 selecthost(&ctrl_addr);
580 if (ctrl_addr.su_family == AF_INET)
582 tos = IPTOS_LOWDELAY;
583 if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
584 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
588 * Disable Nagle on the control channel so that we don't have to wait
589 * for peer's ACK before issuing our next reply.
591 if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
592 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
594 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
596 /* set this here so klogin can use it... */
597 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
599 /* Try to handle urgent data inline */
601 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
602 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
606 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
607 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
609 dolog((struct sockaddr *)&his_addr);
611 * Set up default state
620 /* If logins are disabled, print out the message. */
621 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
622 while (fgets(line, sizeof(line), fd) != NULL) {
623 if ((cp = strchr(line, '\n')) != NULL)
625 lreply(530, "%s", line);
627 (void) fflush(stdout);
629 reply(530, "System not available.");
632 #ifdef VIRTUAL_HOSTING
633 if ((fd = fopen(thishost->welcome, "r")) != NULL) {
635 if ((fd = fopen(_PATH_FTPWELCOME, "r")) != NULL) {
637 while (fgets(line, sizeof(line), fd) != NULL) {
638 if ((cp = strchr(line, '\n')) != NULL)
640 lreply(220, "%s", line);
642 (void) fflush(stdout);
644 /* reply(220,) must follow */
646 #ifndef VIRTUAL_HOSTING
647 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
648 fatalerror("Ran out of memory.");
649 (void) gethostname(hostname, MAXHOSTNAMELEN - 1);
650 hostname[MAXHOSTNAMELEN - 1] = '\0';
653 reply(220, "%s FTP server (%s) ready.", hostname, version);
655 reply(220, "FTP server ready.");
667 syslog(LOG_DEBUG, "lost connection");
676 syslog(LOG_ERR, "got signal %d", signo);
680 #ifdef VIRTUAL_HOSTING
682 * read in virtual host tables (if they exist)
691 char *cp, *mp, *line;
693 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
694 struct ftphost *hrp, *lhrp;
695 struct addrinfo hints, *res, *ai;
698 * Fill in the default host information
700 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
701 fatalerror("Ran out of memory.");
702 if (gethostname(hostname, MAXHOSTNAMELEN) < 0)
704 hostname[MAXHOSTNAMELEN - 1] = '\0';
705 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
706 fatalerror("Ran out of memory.");
707 hrp->hostname = hostname;
708 hrp->hostinfo = NULL;
710 memset(&hints, 0, sizeof(hints));
711 hints.ai_flags = AI_CANONNAME;
712 hints.ai_family = AF_UNSPEC;
713 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
715 hrp->statfile = _PATH_FTPDSTATFILE;
716 hrp->welcome = _PATH_FTPWELCOME;
717 hrp->loginmsg = _PATH_FTPLOGINMESG;
718 hrp->anonuser = "ftp";
720 thishost = firsthost = lhrp = hrp;
721 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
722 int addrsize, gothost;
726 while ((line = fgetln(fp, &len)) != NULL) {
732 if (line[len - 1] == '\n') {
733 line[len - 1] = '\0';
736 if ((mp = malloc(len + 1)) == NULL)
737 fatalerror("Ran out of memory.");
738 memcpy(mp, line, len);
742 cp = strtok(line, " \t");
743 /* skip empty lines */
750 statfile = _PATH_FTPDSTATFILE;
751 welcome = _PATH_FTPWELCOME;
752 loginmsg = _PATH_FTPLOGINMESG;
755 * Preparse the line so we can use its info
756 * for all the addresses associated with
757 * the virtual host name.
758 * Field 0, the virtual host name, is special:
759 * it's already parsed off and will be strdup'ed
760 * later, after we know its canonical form.
762 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
763 if (*cp != '-' && (cp = strdup(cp)))
765 case 1: /* anon user permissions */
768 case 2: /* statistics file */
771 case 3: /* welcome message */
774 case 4: /* login message */
777 default: /* programming error */
783 hints.ai_family = AF_UNSPEC;
784 hints.ai_flags = AI_PASSIVE;
785 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
787 for (ai = res; ai != NULL && ai->ai_addr != NULL;
791 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
794 for (hi = hrp->hostinfo; hi != NULL;
796 if (hi->ai_addrlen == ai->ai_addrlen &&
799 ai->ai_addr->sa_len) == 0) {
807 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
809 hrp->hostname = NULL;
812 if (hrp->hostinfo && hrp->hostinfo != res)
813 freeaddrinfo(hrp->hostinfo);
814 insert = 0; /* host already in the chain */
819 * determine hostname to use.
820 * force defined name if there is a valid alias
821 * otherwise fallback to primary hostname
823 /* XXX: getaddrinfo() can't do alias check */
824 switch(hrp->hostinfo->ai_family) {
826 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
827 addrsize = sizeof(struct in_addr);
830 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
831 addrsize = sizeof(struct in6_addr);
834 /* should not reach here */
835 freeaddrinfo(hrp->hostinfo);
837 free(hrp); /*not in chain, can free*/
839 hrp->hostinfo = NULL; /*mark as blank*/
843 if ((hp = getipnodebyaddr(addr, addrsize,
844 hrp->hostinfo->ai_family,
845 &hp_error)) != NULL) {
846 if (strcmp(vhost, hp->h_name) != 0) {
847 if (hp->h_aliases == NULL)
851 while (hp->h_aliases[i] &&
852 strcmp(vhost, hp->h_aliases[i]) != 0)
854 if (hp->h_aliases[i] == NULL)
860 strcmp(hrp->hostname, vhost) != 0) {
862 hrp->hostname = NULL;
864 if (hrp->hostname == NULL &&
865 (hrp->hostname = strdup(vhost)) == NULL) {
866 freeaddrinfo(hrp->hostinfo);
867 hrp->hostinfo = NULL; /* mark as blank */
872 hrp->anonuser = anonuser;
873 hrp->statfile = statfile;
874 hrp->welcome = welcome;
875 hrp->loginmsg = loginmsg;
899 struct in6_addr *mapped_in6 = NULL;
905 * XXX IPv4 mapped IPv6 addr consideraton,
906 * specified in rfc2373.
908 if (su->su_family == AF_INET6 &&
909 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
910 mapped_in6 = &su->su_sin6.sin6_addr;
913 hrp = thishost = firsthost; /* default */
916 while (hrp != NULL) {
917 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
918 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
923 /* XXX IPv4 mapped IPv6 addr consideraton */
924 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
925 (memcmp(&mapped_in6->s6_addr[12],
926 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
927 sizeof(struct in_addr)) == 0)) {
936 /* setup static variables as appropriate */
937 hostname = thishost->hostname;
938 ftpuser = thishost->anonuser;
943 * Helper function for sgetpwnam().
949 char *new = malloc((unsigned) strlen(s) + 1);
952 perror_reply(421, "Local resource failure: malloc");
956 (void) strcpy(new, s);
961 * Save the result of a getpwnam. Used for USER command, since
962 * the data returned must not be clobbered by any other command
965 static struct passwd *
969 static struct passwd save;
972 if ((p = getpwnam(name)) == NULL)
976 free(save.pw_passwd);
982 save.pw_name = sgetsave(p->pw_name);
983 save.pw_passwd = sgetsave(p->pw_passwd);
984 save.pw_gecos = sgetsave(p->pw_gecos);
985 save.pw_dir = sgetsave(p->pw_dir);
986 save.pw_shell = sgetsave(p->pw_shell);
990 static int login_attempts; /* number of failed login attempts */
991 static int askpasswd; /* had user command, ask for passwd */
992 static char curname[MAXLOGNAME]; /* current USER name */
996 * Sets global passwd pointer pw if named account exists and is acceptable;
997 * sets askpasswd if a PASS command is expected. If logged in previously,
998 * need to reset state. If name is "ftp" or "anonymous", the name is not in
999 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
1000 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
1001 * requesting login privileges. Disallow anyone who does not have a standard
1002 * shell as returned by getusershell(). Disallow anyone mentioned in the file
1003 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
1013 reply(530, "Can't change user from guest login.");
1015 } else if (dochroot) {
1016 reply(530, "Can't change user from chroot user.");
1023 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1024 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL) ||
1025 checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL))
1026 reply(530, "User %s access denied.", name);
1027 #ifdef VIRTUAL_HOSTING
1028 else if ((pw = sgetpwnam(thishost->anonuser)) != NULL) {
1030 else if ((pw = sgetpwnam("ftp")) != NULL) {
1035 "Guest login ok, send your email address as password.");
1037 reply(530, "User %s unknown.", name);
1038 if (!askpasswd && logging)
1040 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1043 if (anon_only != 0) {
1044 reply(530, "Sorry, only anonymous ftp allowed.");
1048 if ((pw = sgetpwnam(name))) {
1049 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1050 shell = _PATH_BSHELL;
1051 while ((cp = getusershell()) != NULL)
1052 if (strcmp(cp, shell) == 0)
1056 if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1, NULL)) {
1057 reply(530, "User %s access denied.", name);
1060 "FTP LOGIN REFUSED FROM %s, %s",
1062 pw = (struct passwd *) NULL;
1067 strncpy(curname, name, sizeof(curname)-1);
1069 pwok = skeyaccess(name, NULL, remotehost, remotehost);
1070 reply(331, "%s", skey_challenge(name, pw, pwok));
1072 reply(331, "Password required for %s.", name);
1076 * Delay before reading passwd after first failed
1077 * attempt to slow down passwd-guessing programs.
1080 sleep((unsigned) login_attempts);
1084 * Check if a user is in the file "fname",
1085 * return a pointer to a malloc'd string with the rest
1086 * of the matching line in "residue" if not NULL.
1089 checkuser(fname, name, pwset, residue)
1098 char *line, *mp, *p;
1100 if ((fd = fopen(fname, "r")) != NULL) {
1101 while (!found && (line = fgetln(fd, &len)) != NULL) {
1105 if (line[len - 1] == '\n') {
1106 line[len - 1] = '\0';
1109 if ((mp = malloc(len + 1)) == NULL)
1110 fatalerror("Ran out of memory.");
1111 memcpy(mp, line, len);
1115 /* avoid possible leading and trailing whitespace */
1116 p = strtok(line, " \t");
1117 /* skip empty lines */
1121 * if first chr is '@', check group membership
1127 if (p[1] == '\0') /* single @ matches anyone */
1130 if ((grp = getgrnam(p+1)) == NULL)
1133 * Check user's default group
1135 if (pwset && grp->gr_gid == pw->pw_gid)
1138 * Check supplementary groups
1140 while (!found && grp->gr_mem[i])
1141 found = strcmp(name,
1147 * Otherwise, just check for username match
1150 found = strcmp(p, name) == 0;
1152 * Save the rest of line to "residue" if matched
1154 if (found && residue) {
1155 if ((p = strtok(NULL, "")) != NULL)
1156 p += strspn(p, " \t");
1158 if ((*residue = strdup(p)) == NULL)
1159 fatalerror("Ran out of memory.");
1173 * Terminate login as previous user, if any, resetting state;
1174 * used when USER command is given or login fails.
1180 (void) seteuid((uid_t)0);
1181 if (logged_in && dowtmp)
1182 ftpd_logwtmp(ttyline, "", NULL);
1185 setusercontext(NULL, getpwuid(0), (uid_t)0,
1186 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1196 * the following code is stolen from imap-uw PAM authentication module and
1199 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1202 const char *uname; /* user name */
1203 const char *pass; /* password */
1205 typedef struct cred_t cred_t;
1208 auth_conv(int num_msg, const struct pam_message **msg,
1209 struct pam_response **resp, void *appdata)
1212 cred_t *cred = (cred_t *) appdata;
1213 struct pam_response *reply =
1214 malloc(sizeof(struct pam_response) * num_msg);
1216 for (i = 0; i < num_msg; i++) {
1217 switch (msg[i]->msg_style) {
1218 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1219 reply[i].resp_retcode = PAM_SUCCESS;
1220 reply[i].resp = COPY_STRING(cred->uname);
1221 /* PAM frees resp. */
1223 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1224 reply[i].resp_retcode = PAM_SUCCESS;
1225 reply[i].resp = COPY_STRING(cred->pass);
1226 /* PAM frees resp. */
1230 reply[i].resp_retcode = PAM_SUCCESS;
1231 reply[i].resp = NULL;
1233 default: /* unknown message style */
1235 return PAM_CONV_ERR;
1244 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1245 * authenticated, or 1 if not authenticated. If some sort of PAM system
1246 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1247 * function returns -1. This can be used as an indication that we should
1248 * fall back to a different authentication mechanism.
1251 auth_pam(struct passwd **ppw, const char *pass)
1253 pam_handle_t *pamh = NULL;
1254 const char *tmpl_user;
1258 cred_t auth_cred = { (*ppw)->pw_name, pass };
1259 struct pam_conv conv = { &auth_conv, &auth_cred };
1261 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1262 if (e != PAM_SUCCESS) {
1263 syslog(LOG_ERR, "pam_start: %s", pam_strerror(pamh, e));
1267 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1268 if (e != PAM_SUCCESS) {
1269 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1270 pam_strerror(pamh, e));
1274 e = pam_authenticate(pamh, 0);
1278 * With PAM we support the concept of a "template"
1279 * user. The user enters a login name which is
1280 * authenticated by PAM, usually via a remote service
1281 * such as RADIUS or TACACS+. If authentication
1282 * succeeds, a different but related "template" name
1283 * is used for setting the credentials, shell, and
1284 * home directory. The name the user enters need only
1285 * exist on the remote authentication server, but the
1286 * template name must be present in the local password
1289 * This is supported by two various mechanisms in the
1290 * individual modules. However, from the application's
1291 * point of view, the template user is always passed
1292 * back as a changed value of the PAM_USER item.
1294 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1296 tmpl_user = (const char *) item;
1297 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1298 *ppw = getpwnam(tmpl_user);
1300 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1301 pam_strerror(pamh, e));
1306 case PAM_USER_UNKNOWN:
1312 syslog(LOG_ERR, "auth_pam: %s", pam_strerror(pamh, e));
1317 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1318 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1324 #endif /* !defined(NOPAM) */
1333 login_cap_t *lc = NULL;
1336 char *residue = NULL;
1338 if (logged_in || askpasswd == 0) {
1339 reply(503, "Login with USER first.");
1343 if (!guest) { /* "ftp" is only account allowed no password */
1345 rval = 1; /* failure below */
1349 rval = auth_pam(&pw, passwd);
1355 rval = strcmp(pw->pw_passwd,
1356 crypt(passwd, pw->pw_passwd));
1358 rval = strcmp(pw->pw_passwd,
1359 skey_crypt(passwd, pw->pw_passwd, pw, pwok));
1361 rval = strcmp(pw->pw_passwd, crypt(passwd, pw->pw_passwd));
1363 /* The strcmp does not catch null passwords! */
1364 if (*pw->pw_passwd == '\0' ||
1365 (pw->pw_expire && time(NULL) >= pw->pw_expire))
1366 rval = 1; /* failure */
1369 * If rval == 1, the user failed the authentication check
1370 * above. If rval == 0, either PAM or local authentication
1374 reply(530, "Login incorrect.");
1377 "FTP LOGIN FAILED FROM %s",
1379 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1380 "FTP LOGIN FAILED FROM %s, %s",
1381 remotehost, curname);
1384 if (login_attempts++ >= 5) {
1386 "repeated login failures from %s",
1396 login_attempts = 0; /* this time successful */
1397 if (setegid((gid_t)pw->pw_gid) < 0) {
1398 reply(550, "Can't set gid.");
1401 /* May be overridden by login.conf */
1402 (void) umask(defumask);
1404 if ((lc = login_getpwclass(pw)) != NULL) {
1405 char remote_ip[MAXHOSTNAMELEN];
1407 getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1408 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1410 remote_ip[sizeof(remote_ip) - 1] = 0;
1411 if (!auth_hostok(lc, remotehost, remote_ip)) {
1412 syslog(LOG_INFO|LOG_AUTH,
1413 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1415 reply(530, "Permission denied.\n");
1419 if (!auth_timeok(lc, time(NULL))) {
1420 reply(530, "Login not available right now.\n");
1425 setusercontext(lc, pw, (uid_t)0,
1426 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1427 LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1429 setlogin(pw->pw_name);
1430 (void) initgroups(pw->pw_name, pw->pw_gid);
1433 /* open wtmp before chroot */
1435 ftpd_logwtmp(ttyline, pw->pw_name,
1436 (struct sockaddr *)&his_addr);
1439 if (guest && stats && statfd < 0)
1440 #ifdef VIRTUAL_HOSTING
1441 if ((statfd = open(thishost->statfile, O_WRONLY|O_APPEND)) < 0)
1443 if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0)
1448 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue)
1449 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1450 || login_getcapbool(lc, "ftp-chroot", 0)
1455 * For a chrooted local user,
1456 * a) see whether ftpchroot(5) specifies a chroot directory,
1457 * b) extract the directory pathname from the line,
1458 * c) expand it to the absolute pathname if necessary.
1460 if (dochroot && residue &&
1461 (chrootdir = strtok(residue, " \t")) != NULL &&
1462 chrootdir[0] != '/') {
1463 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1464 if (chrootdir == NULL)
1465 fatalerror("Ran out of memory.");
1467 if (guest || dochroot) {
1469 * If no chroot directory set yet, use the login directory.
1470 * Copy it so it can be modified while pw->pw_dir stays intact.
1472 if (chrootdir == NULL &&
1473 (chrootdir = strdup(pw->pw_dir)) == NULL)
1474 fatalerror("Ran out of memory.");
1476 * Check for the "/chroot/./home" syntax,
1477 * separate the chroot and home directory pathnames.
1479 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1480 *(homedir++) = '\0'; /* wipe '/' */
1481 homedir++; /* skip '.' */
1482 /* so chrootdir can be freed later */
1483 if ((homedir = strdup(homedir)) == NULL)
1484 fatalerror("Ran out of memory.");
1487 * We MUST do a chdir() after the chroot. Otherwise
1488 * the old current directory will be accessible as "."
1489 * outside the new root!
1494 * Finally, do chroot()
1496 if (chroot(chrootdir) < 0) {
1497 reply(550, "Can't change root.");
1500 } else /* real user w/o chroot */
1501 homedir = pw->pw_dir;
1503 * Set euid *before* doing chdir() so
1504 * a) the user won't be carried to a directory that he couldn't reach
1505 * on his own due to no permission to upper path components,
1506 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1507 * (uid 0 has no root power over NFS if not mapped explicitly.)
1509 if (seteuid((uid_t)pw->pw_uid) < 0) {
1510 reply(550, "Can't set uid.");
1513 if (chdir(homedir) < 0) {
1514 if (guest || dochroot) {
1515 reply(550, "Can't change to base directory.");
1518 if (chdir("/") < 0) {
1519 reply(550, "Root is inaccessible.");
1522 lreply(230, "No directory! Logging in with home=/");
1527 * Display a login message, if it exists.
1528 * N.B. reply(230,) must follow the message.
1530 #ifdef VIRTUAL_HOSTING
1531 if ((fd = fopen(thishost->loginmsg, "r")) != NULL) {
1533 if ((fd = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) {
1535 char *cp, line[LINE_MAX];
1537 while (fgets(line, sizeof(line), fd) != NULL) {
1538 if ((cp = strchr(line, '\n')) != NULL)
1540 lreply(230, "%s", line);
1542 (void) fflush(stdout);
1548 ident = strdup(passwd);
1550 fatalerror("Ran out of memory.");
1552 reply(230, "Guest login ok, access restrictions apply.");
1554 #ifdef VIRTUAL_HOSTING
1555 if (thishost != firsthost)
1556 snprintf(proctitle, sizeof(proctitle),
1557 "%s: anonymous(%s)/%s", remotehost, hostname,
1561 snprintf(proctitle, sizeof(proctitle),
1562 "%s: anonymous/%s", remotehost, passwd);
1563 setproctitle("%s", proctitle);
1564 #endif /* SETPROCTITLE */
1566 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1567 remotehost, passwd);
1570 reply(230, "User %s logged in, "
1571 "access restrictions apply.", pw->pw_name);
1573 reply(230, "User %s logged in.", pw->pw_name);
1576 snprintf(proctitle, sizeof(proctitle),
1577 "%s: user/%s", remotehost, pw->pw_name);
1578 setproctitle("%s", proctitle);
1579 #endif /* SETPROCTITLE */
1581 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1582 remotehost, pw->pw_name);
1593 /* Forget all about it... */
1610 int (*closefunc) (FILE *);
1614 fin = fopen(name, "r"), closefunc = fclose;
1619 (void) snprintf(line, sizeof(line), cmd, name), name = line;
1620 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1622 st.st_blksize = BUFSIZ;
1626 perror_reply(550, name);
1628 LOGCMD("get", name);
1635 if (fstat(fileno(fin), &st) < 0) {
1636 perror_reply(550, name);
1639 if (!S_ISREG(st.st_mode)) {
1641 reply(550, "%s: not a plain file.", name);
1645 /* st.st_blksize is set for all descriptor types */
1648 if (restart_point) {
1649 if (type == TYPE_A) {
1656 if ((c=getc(fin)) == EOF) {
1657 perror_reply(550, name);
1663 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1664 perror_reply(550, name);
1668 dout = dataconn(name, st.st_size, "w");
1672 send_data(fin, dout, st.st_blksize, st.st_size,
1673 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1674 if (cmd == 0 && guest && stats)
1675 logxfer(name, st.st_size, start);
1676 (void) fclose(dout);
1681 LOGBYTES("get", name, byte_count);
1686 store(name, mode, unique)
1692 int (*closefunc) (FILE *);
1694 if (*mode == 'a') { /* APPE */
1696 /* Programming error */
1697 syslog(LOG_ERR, "Internal: unique flag to APPE");
1700 if (guest && noguestmod) {
1701 reply(550, "Appending to existing file denied");
1704 restart_point = 0; /* not affected by preceding REST */
1706 if (unique) /* STOU overrides REST */
1708 if (guest && noguestmod) {
1709 if (restart_point) { /* guest STOR w/REST */
1710 reply(550, "Modifying existing file denied");
1712 } else /* treat guest STOR as STOU */
1717 mode = "r+"; /* so ASCII manual seek can work */
1719 if ((fd = guniquefd(name, &name)) < 0)
1721 fout = fdopen(fd, mode);
1723 fout = fopen(name, mode);
1726 perror_reply(553, name);
1730 if (restart_point) {
1731 if (type == TYPE_A) {
1738 if ((c=getc(fout)) == EOF) {
1739 perror_reply(550, name);
1746 * We must do this seek to "current" position
1747 * because we are changing from reading to
1750 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1751 perror_reply(550, name);
1754 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1755 perror_reply(550, name);
1759 din = dataconn(name, (off_t)-1, "r");
1762 if (receive_data(din, fout) == 0) {
1764 reply(226, "Transfer complete (unique file name:%s).",
1767 reply(226, "Transfer complete.");
1773 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1777 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1785 int on = 1, s, t, tries;
1788 return (fdopen(data, mode));
1790 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1793 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1794 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1795 /* anchor socket to avoid multi-homing problems */
1796 data_source = ctrl_addr;
1797 data_source.su_port = htons(dataport);
1798 (void) seteuid((uid_t)0);
1799 for (tries = 1; ; tries++) {
1800 if (bind(s, (struct sockaddr *)&data_source,
1801 data_source.su_len) >= 0)
1803 if (errno != EADDRINUSE || tries > 10)
1807 (void) seteuid((uid_t)pw->pw_uid);
1809 if (data_source.su_family == AF_INET)
1811 on = IPTOS_THROUGHPUT;
1812 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1813 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1818 * Turn off push flag to keep sender TCP from sending short packets
1819 * at the boundaries of each write(). Should probably do a SO_SNDBUF
1820 * to set the send buffer size as well, but that may not be desirable
1821 * in heavy-load situations.
1824 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1825 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1829 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &on, sizeof on) < 0)
1830 syslog(LOG_WARNING, "data setsockopt (SO_SNDBUF): %m");
1833 return (fdopen(s, mode));
1835 /* Return the real value of errno (close may change it) */
1837 (void) seteuid((uid_t)pw->pw_uid);
1844 dataconn(name, size, mode)
1851 int retry = 0, tos, conerrno;
1855 if (size != (off_t) -1)
1856 (void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)", size);
1860 union sockunion from;
1862 int s, fromlen = ctrl_addr.su_len;
1863 struct timeval timeout;
1867 FD_SET(pdata, &set);
1869 timeout.tv_usec = 0;
1870 timeout.tv_sec = 120;
1873 * Granted a socket is in the blocking I/O mode,
1874 * accept() will block after a successful select()
1875 * if the selected connection dies in between.
1876 * Therefore set the non-blocking I/O flag here.
1878 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1879 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1881 if (select(pdata+1, &set, (fd_set *) 0, (fd_set *) 0, &timeout) <= 0 ||
1882 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1884 (void) close(pdata);
1887 * Unset the inherited non-blocking I/O flag
1888 * on the child socket so stdio can work on it.
1890 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1891 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1894 if (from.su_family == AF_INET)
1896 tos = IPTOS_THROUGHPUT;
1897 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1898 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1901 reply(150, "Opening %s mode data connection for '%s'%s.",
1902 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1903 return (fdopen(pdata, mode));
1905 reply(425, "Can't open data connection.");
1906 (void) close(pdata);
1911 reply(125, "Using existing data connection for '%s'%s.",
1914 return (fdopen(data, mode));
1917 data_dest = his_addr;
1920 file = getdatasock(mode);
1922 char hostbuf[BUFSIZ], portbuf[BUFSIZ];
1923 getnameinfo((struct sockaddr *)&data_source,
1924 data_source.su_len, hostbuf, sizeof(hostbuf) - 1,
1925 portbuf, sizeof(portbuf),
1926 NI_NUMERICHOST|NI_NUMERICSERV);
1927 reply(425, "Can't create data socket (%s,%s): %s.",
1928 hostbuf, portbuf, strerror(errno));
1931 data = fileno(file);
1933 if (connect(data, (struct sockaddr *)&data_dest,
1934 data_dest.su_len) == 0)
1937 (void) fclose(file);
1939 if (conerrno == EADDRINUSE) {
1940 sleep((unsigned) swaitint);
1945 } while (retry <= swaitmax);
1946 if (conerrno != 0) {
1947 perror_reply(425, "Can't build data connection");
1950 reply(150, "Opening %s mode data connection for '%s'%s.",
1951 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1956 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1957 * encapsulation of the data subject to Mode, Structure, and Type.
1959 * NB: Form isn't handled.
1962 send_data(instr, outstr, blksize, filesize, isreg)
1963 FILE *instr, *outstr;
1968 int c, filefd, netfd;
1976 while ((c = getc(instr)) != EOF) {
1983 (void) putc('\r', outstr);
1985 (void) putc(c, outstr);
1995 reply(226, "Transfer complete.");
2001 * isreg is only set if we are not doing restart and we
2002 * are sending a regular file
2004 netfd = fileno(outstr);
2005 filefd = fileno(instr);
2012 err = cnt = offset = 0;
2014 while (err != -1 && filesize > 0) {
2015 err = sendfile(filefd, netfd, offset, 0,
2016 (struct sf_hdtr *) NULL, &cnt, 0);
2018 * Calculate byte_count before OOB processing.
2019 * It can be used in myoob() later.
2036 reply(226, "Transfer complete.");
2041 if ((buf = malloc((u_int)blksize)) == NULL) {
2043 perror_reply(451, "Local resource failure: malloc");
2047 while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
2048 write(netfd, buf, cnt) == cnt)
2057 reply(226, "Transfer complete.");
2061 reply(550, "Unimplemented TYPE %d in send_data", type);
2067 perror_reply(426, "Data connection");
2072 perror_reply(551, "Error on input file");
2083 * Transfer data from peer to "outstr" using the appropriate encapulation of
2084 * the data subject to Mode, Structure, and Type.
2086 * N.B.: Form isn't handled.
2089 receive_data(instr, outstr)
2090 FILE *instr, *outstr;
2103 while ((cnt = read(fileno(instr), buf, sizeof(buf))) > 0) {
2106 if (write(fileno(outstr), buf, cnt) != cnt)
2118 reply(553, "TYPE E not implemented.");
2123 while ((c = getc(instr)) != EOF) {
2132 if ((c = getc(instr)) != '\n') {
2133 (void) putc ('\r', outstr);
2134 if (c == '\0' || c == EOF)
2138 (void) putc(c, outstr);
2151 "WARNING! %d bare linefeeds received in ASCII mode",
2153 (void)printf(" File may not have transferred correctly.\r\n");
2157 reply(550, "Unimplemented TYPE %d in receive_data", type);
2164 perror_reply(426, "Data Connection");
2169 perror_reply(452, "Error writing file");
2180 statfilecmd(filename)
2186 char line[LINE_MAX];
2188 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2189 fin = ftpd_popen(line, "r");
2190 lreply(211, "status of %s:", filename);
2192 while ((c = getc(fin)) != EOF) {
2194 if (ferror(stdout)){
2195 perror_reply(421, "control connection");
2196 (void) ftpd_pclose(fin);
2201 perror_reply(551, filename);
2202 (void) ftpd_pclose(fin);
2205 (void) putc('\r', stdout);
2208 * RFC 959 says neutral text should be prepended before
2209 * a leading 3-digit number followed by whitespace, but
2210 * many ftp clients can be confused by any leading digits,
2211 * as a matter of fact.
2213 if (atstart && isdigit(c))
2214 (void) putc(' ', stdout);
2215 (void) putc(c, stdout);
2216 atstart = (c == '\n');
2218 (void) ftpd_pclose(fin);
2219 reply(211, "End of Status");
2225 union sockunion *su;
2227 char hname[NI_MAXHOST];
2231 lreply(211, "%s FTP server status:", hostname);
2232 printf(" %s\r\n", version);
2234 lreply(211, "FTP server status:");
2235 printf(" Connected to %s", remotehost);
2236 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2237 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2238 if (strcmp(hname, remotehost) != 0)
2239 printf(" (%s)", hname);
2244 printf(" Logged in anonymously\r\n");
2246 printf(" Logged in as %s\r\n", pw->pw_name);
2247 } else if (askpasswd)
2248 printf(" Waiting for password\r\n");
2250 printf(" Waiting for user name\r\n");
2251 printf(" TYPE: %s", typenames[type]);
2252 if (type == TYPE_A || type == TYPE_E)
2253 printf(", FORM: %s", formnames[form]);
2256 printf(" %d", NBBY);
2258 printf(" %d", bytesize); /* need definition! */
2260 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2261 strunames[stru], modenames[mode]);
2263 printf(" Data connection open\r\n");
2264 else if (pdata != -1) {
2268 } else if (usedefault == 0) {
2272 #define UC(b) (((int) b) & 0xff)
2274 printf(" EPSV only mode (EPSV ALL)\r\n");
2279 if (su->su_family == AF_INET) {
2280 a = (u_char *) &su->su_sin.sin_addr;
2281 p = (u_char *) &su->su_sin.sin_port;
2282 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2283 ispassive ? "PASV" : "PORT",
2284 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2285 UC(p[0]), UC(p[1]));
2292 switch (su->su_family) {
2294 a = (u_char *) &su->su_sin.sin_addr;
2295 p = (u_char *) &su->su_sin.sin_port;
2296 alen = sizeof(su->su_sin.sin_addr);
2300 a = (u_char *) &su->su_sin6.sin6_addr;
2301 p = (u_char *) &su->su_sin6.sin6_port;
2302 alen = sizeof(su->su_sin6.sin6_addr);
2310 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2312 for (i = 0; i < alen; i++)
2313 printf("%d,", UC(a[i]));
2314 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2323 switch (su->su_family) {
2335 union sockunion tmp;
2338 if (tmp.su_family == AF_INET6)
2339 tmp.su_sin6.sin6_scope_id = 0;
2340 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2341 hname, sizeof(hname) - 1, NULL, 0,
2343 printf(" %s |%d|%s|%d|\r\n",
2344 ispassive ? "EPSV" : "EPRT",
2345 af, hname, htons(tmp.su_port));
2351 printf(" No data connection\r\n");
2352 reply(211, "End of status");
2360 reply(451, "Error in server: %s\n", s);
2361 reply(221, "Closing connection due to server error.");
2368 reply(int n, const char *fmt, ...)
2370 reply(n, fmt, va_alist)
2382 (void)printf("%d ", n);
2383 (void)vprintf(fmt, ap);
2384 (void)printf("\r\n");
2385 (void)fflush(stdout);
2387 syslog(LOG_DEBUG, "<--- %d ", n);
2388 vsyslog(LOG_DEBUG, fmt, ap);
2394 lreply(int n, const char *fmt, ...)
2396 lreply(n, fmt, va_alist)
2408 (void)printf("%d- ", n);
2409 (void)vprintf(fmt, ap);
2410 (void)printf("\r\n");
2411 (void)fflush(stdout);
2413 syslog(LOG_DEBUG, "<--- %d- ", n);
2414 vsyslog(LOG_DEBUG, fmt, ap);
2423 reply(250, "%s command successful.", s);
2431 reply(502, "%s command not implemented.", s);
2441 if ((cp = strchr(cbuf,'\n')))
2443 reply(500, "'%s': command not understood.", cbuf);
2452 LOGCMD("delete", name);
2453 if (lstat(name, &st) < 0) {
2454 perror_reply(550, name);
2457 if ((st.st_mode&S_IFMT) == S_IFDIR) {
2458 if (rmdir(name) < 0) {
2459 perror_reply(550, name);
2464 if (unlink(name) < 0) {
2465 perror_reply(550, name);
2477 if (chdir(path) < 0)
2478 perror_reply(550, path);
2489 LOGCMD("mkdir", name);
2490 if (guest && noguestmkd)
2491 reply(550, "%s: permission denied", name);
2492 else if (mkdir(name, 0777) < 0)
2493 perror_reply(550, name);
2495 if ((s = doublequote(name)) == NULL)
2496 fatalerror("Ran out of memory.");
2497 reply(257, "\"%s\" directory created.", s);
2507 LOGCMD("rmdir", name);
2508 if (rmdir(name) < 0)
2509 perror_reply(550, name);
2517 char *s, path[MAXPATHLEN + 1];
2519 if (getwd(path) == (char *)NULL)
2520 reply(550, "%s.", path);
2522 if ((s = doublequote(path)) == NULL)
2523 fatalerror("Ran out of memory.");
2524 reply(257, "\"%s\" is current directory.", s);
2535 if (lstat(name, &st) < 0) {
2536 perror_reply(550, name);
2539 reply(350, "File exists, ready for destination name");
2549 LOGCMD2("rename", from, to);
2551 if (guest && (stat(to, &st) == 0)) {
2552 reply(550, "%s: permission denied", to);
2556 if (rename(from, to) < 0)
2557 perror_reply(550, "rename");
2564 struct sockaddr *who;
2568 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2571 #ifdef VIRTUAL_HOSTING
2572 if (thishost != firsthost)
2573 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2574 remotehost, hostname);
2577 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2579 setproctitle("%s", proctitle);
2580 #endif /* SETPROCTITLE */
2583 #ifdef VIRTUAL_HOSTING
2584 if (thishost != firsthost)
2585 syslog(LOG_INFO, "connection from %s (to %s)",
2586 remotehost, hostname);
2590 char who_name[MAXHOSTNAMELEN];
2592 error = getnameinfo(who, who->sa_len,
2593 who_name, sizeof(who_name) - 1,
2594 NULL, 0, NI_NUMERICHOST);
2595 syslog(LOG_INFO, "connection from %s (%s)", remotehost,
2596 error == 0 ? who_name : "");
2602 * Record logout in wtmp file
2603 * and exit with supplied status.
2610 * Prevent reception of SIGURG from resulting in a resumption
2611 * back to the main program loop.
2615 if (logged_in && dowtmp) {
2616 (void) seteuid((uid_t)0);
2617 ftpd_logwtmp(ttyline, "", NULL);
2619 /* beware of flushing buffers after a SIGPIPE */
2636 /* only process if transfer occurring */
2640 if (getline(cp, 7, stdin) == NULL) {
2641 reply(221, "You could at least say goodbye.");
2645 if (strcmp(cp, "ABOR\r\n") == 0) {
2647 reply(426, "Transfer aborted. Data connection closed.");
2648 reply(226, "Abort successful");
2650 if (strcmp(cp, "STAT\r\n") == 0) {
2652 if (file_size != (off_t) -1)
2653 reply(213, "Status: %qd of %qd bytes transferred",
2654 byte_count, file_size);
2656 reply(213, "Status: %qd bytes transferred", byte_count);
2661 * Note: a response of 425 is not mentioned as a possible response to
2662 * the PASV command in RFC959. However, it has been blessed as
2663 * a legitimate response by Jon Postel in a telephone conversation
2664 * with Rick Adams on 25 Jan 89.
2672 if (pdata >= 0) /* close old port if one set */
2675 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2677 perror_reply(425, "Can't open passive connection");
2681 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2682 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2684 (void) seteuid((uid_t)0);
2687 if (ctrl_addr.su_family == AF_INET) {
2688 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2689 : IP_PORTRANGE_DEFAULT;
2691 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2692 &on, sizeof(on)) < 0)
2696 #ifdef IPV6_PORTRANGE
2697 if (ctrl_addr.su_family == AF_INET6) {
2698 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2699 : IPV6_PORTRANGE_DEFAULT;
2701 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2702 &on, sizeof(on)) < 0)
2707 pasv_addr = ctrl_addr;
2708 pasv_addr.su_port = 0;
2709 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2712 (void) seteuid((uid_t)pw->pw_uid);
2714 len = sizeof(pasv_addr);
2715 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2717 if (listen(pdata, 1) < 0)
2719 if (pasv_addr.su_family == AF_INET)
2720 a = (char *) &pasv_addr.su_sin.sin_addr;
2721 else if (pasv_addr.su_family == AF_INET6 &&
2722 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2723 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2727 p = (char *) &pasv_addr.su_port;
2729 #define UC(b) (((int) b) & 0xff)
2731 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2732 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2736 (void) seteuid((uid_t)pw->pw_uid);
2737 (void) close(pdata);
2739 perror_reply(425, "Can't open passive connection");
2744 * Long Passive defined in RFC 1639.
2745 * 228 Entering Long Passive Mode
2746 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2750 long_passive(cmd, pf)
2757 if (pdata >= 0) /* close old port if one set */
2760 if (pf != PF_UNSPEC) {
2761 if (ctrl_addr.su_family != pf) {
2762 switch (ctrl_addr.su_family) {
2775 * only EPRT/EPSV ready clients will understand this
2777 if (strcmp(cmd, "EPSV") == 0 && pf) {
2778 reply(522, "Network protocol mismatch, "
2781 reply(501, "Network protocol mismatch"); /*XXX*/
2787 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2789 perror_reply(425, "Can't open passive connection");
2793 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2794 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2796 (void) seteuid((uid_t)0);
2798 pasv_addr = ctrl_addr;
2799 pasv_addr.su_port = 0;
2800 len = pasv_addr.su_len;
2803 if (ctrl_addr.su_family == AF_INET) {
2804 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2805 : IP_PORTRANGE_DEFAULT;
2807 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2808 &on, sizeof(on)) < 0)
2812 #ifdef IPV6_PORTRANGE
2813 if (ctrl_addr.su_family == AF_INET6) {
2814 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2815 : IPV6_PORTRANGE_DEFAULT;
2817 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2818 &on, sizeof(on)) < 0)
2823 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2826 (void) seteuid((uid_t)pw->pw_uid);
2828 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2830 if (listen(pdata, 1) < 0)
2833 #define UC(b) (((int) b) & 0xff)
2835 if (strcmp(cmd, "LPSV") == 0) {
2836 p = (char *)&pasv_addr.su_port;
2837 switch (pasv_addr.su_family) {
2839 a = (char *) &pasv_addr.su_sin.sin_addr;
2842 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2843 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2844 2, UC(p[0]), UC(p[1]));
2847 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
2848 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2851 a = (char *) &pasv_addr.su_sin6.sin6_addr;
2853 "Entering Long Passive Mode "
2854 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2855 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2856 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2857 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2858 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2859 2, UC(p[0]), UC(p[1]));
2862 } else if (strcmp(cmd, "EPSV") == 0) {
2863 switch (pasv_addr.su_family) {
2866 reply(229, "Entering Extended Passive Mode (|||%d|)",
2867 ntohs(pasv_addr.su_port));
2871 /* more proper error code? */
2875 (void) seteuid((uid_t)pw->pw_uid);
2876 (void) close(pdata);
2878 perror_reply(425, "Can't open passive connection");
2883 * Generate unique name for file with basename "local"
2884 * and open the file in order to avoid possible races.
2885 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
2886 * Return descriptor to the file, set "name" to its name.
2888 * Generates failure reply on error.
2891 guniquefd(local, name)
2895 static char new[MAXPATHLEN];
2901 cp = strrchr(local, '/');
2904 if (stat(cp ? local : ".", &st) < 0) {
2905 perror_reply(553, cp ? local : ".");
2910 * Let not overwrite dirname with counter suffix.
2912 * In this extreme case dot won't be put in front of suffix.
2914 if (strlen(local) > sizeof(new) - 4) {
2915 reply(553, "Pathname too long");
2920 /* -4 is for the .nn<null> we put on the end below */
2921 (void) snprintf(new, sizeof(new) - 4, "%s", local);
2922 cp = new + strlen(new);
2924 * Don't generate dotfile unless requested explicitly.
2925 * This covers the case when basename gets truncated off
2928 if (cp > new && cp[-1] != '/')
2930 for (count = 0; count < 100; count++) {
2931 /* At count 0 try unmodified name */
2933 (void)sprintf(cp, "%d", count);
2934 if ((fd = open(count ? new : local,
2935 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
2936 *name = count ? new : local;
2939 if (errno != EEXIST) {
2940 perror_reply(553, count ? new : local);
2944 reply(452, "Unique file name cannot be created.");
2949 * Format and send reply containing system error number.
2952 perror_reply(code, string)
2957 reply(code, "%s: %s.", string, strerror(errno));
2960 static char *onefile[] = {
2966 send_file_list(whichf)
2973 char **dirlist, *dirname;
2978 if (strpbrk(whichf, "~{[*?") != NULL) {
2979 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
2981 memset(&gl, 0, sizeof(gl));
2982 gl.gl_matchc = MAXGLOBARGS;
2983 flags |= GLOB_LIMIT;
2985 if (glob(whichf, flags, 0, &gl)) {
2986 reply(550, "not found");
2988 } else if (gl.gl_pathc == 0) {
2990 perror_reply(550, whichf);
2993 dirlist = gl.gl_pathv;
2995 onefile[0] = whichf;
3000 while ((dirname = *dirlist++)) {
3001 if (stat(dirname, &st) < 0) {
3003 * If user typed "ls -l", etc, and the client
3004 * used NLST, do what the user meant.
3006 if (dirname[0] == '-' && *dirlist == NULL &&
3008 retrieve(_PATH_LS " %s", dirname);
3011 perror_reply(550, whichf);
3013 (void) fclose(dout);
3021 if (S_ISREG(st.st_mode)) {
3023 dout = dataconn("file list", (off_t)-1, "w");
3028 fprintf(dout, "%s%s\n", dirname,
3029 type == TYPE_A ? "\r" : "");
3030 byte_count += strlen(dirname) + 1;
3032 } else if (!S_ISDIR(st.st_mode))
3035 if ((dirp = opendir(dirname)) == NULL)
3038 while ((dir = readdir(dirp)) != NULL) {
3039 char nbuf[MAXPATHLEN];
3048 if (strcmp(dir->d_name, ".") == 0)
3050 if (strcmp(dir->d_name, "..") == 0)
3053 snprintf(nbuf, sizeof(nbuf),
3054 "%s/%s", dirname, dir->d_name);
3057 * We have to do a stat to insure it's
3058 * not a directory or special file.
3060 if (simple || (stat(nbuf, &st) == 0 &&
3061 S_ISREG(st.st_mode))) {
3063 dout = dataconn("file list", (off_t)-1,
3069 if (nbuf[0] == '.' && nbuf[1] == '/')
3070 fprintf(dout, "%s%s\n", &nbuf[2],
3071 type == TYPE_A ? "\r" : "");
3073 fprintf(dout, "%s%s\n", nbuf,
3074 type == TYPE_A ? "\r" : "");
3075 byte_count += strlen(nbuf) + 1;
3078 (void) closedir(dirp);
3082 reply(550, "No files found.");
3083 else if (ferror(dout) != 0)
3084 perror_reply(550, "Data connection");
3086 reply(226, "Transfer complete.");
3090 (void) fclose(dout);
3104 while (wait3(NULL, WNOHANG, NULL) > 0);
3107 #ifdef OLD_SETPROCTITLE
3109 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.)
3110 * Warning, since this is usually started from inetd.conf, it often doesn't
3111 * have much of an environment or arglist to overwrite.
3115 setproctitle(const char *fmt, ...)
3117 setproctitle(fmt, va_alist)
3132 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
3134 /* make ps print our process name */
3139 if (i > LastArgv - p - 2) {
3140 i = LastArgv - p - 2;
3145 if (ch != '\n' && ch != '\r')
3147 while (p < LastArgv)
3150 #endif /* OLD_SETPROCTITLE */
3153 logxfer(name, size, start)
3159 char path[MAXPATHLEN + 1];
3162 if (statfd >= 0 && getwd(path) != NULL) {
3164 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s/%s!%qd!%ld\n",
3165 ctime(&now)+4, ident, remotehost,
3166 path, name, (long long)size,
3167 (long)(now - start + (now == start)));
3168 write(statfd, buf, strlen(buf));
3179 for (p = s, n = 0; *p; p++)
3183 if ((s2 = malloc(p - s + n + 1)) == NULL)
3186 for (p = s2; *s; s++, p++) {
3187 if ((*p = *s) == '"')