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.2 2003/06/17 04:27:07 dillon 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 __P((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 __P((void));
238 static void selecthost __P((union sockunion *));
240 static void ack __P((char *));
241 static void sigurg __P((int));
242 static void myoob __P((void));
243 static int checkuser __P((char *, char *, int, char **));
244 static FILE *dataconn __P((char *, off_t, char *));
245 static void dolog __P((struct sockaddr *));
246 static char *curdir __P((void));
247 static void end_login __P((void));
248 static FILE *getdatasock __P((char *));
249 static int guniquefd __P((char *, char **));
250 static void lostconn __P((int));
251 static void sigquit __P((int));
252 static int receive_data __P((FILE *, FILE *));
253 static int send_data __P((FILE *, FILE *, off_t, off_t, int));
254 static struct passwd *
255 sgetpwnam __P((char *));
256 static char *sgetsave __P((char *));
257 static void reapchild __P((int));
258 static void logxfer __P((char *, off_t, time_t));
259 static char *doublequote __P((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);
541 addrlen = sizeof(his_addr);
542 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
543 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
548 sa.sa_handler = SIG_DFL;
549 (void)sigaction(SIGCHLD, &sa, NULL);
551 sa.sa_handler = sigurg;
552 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
553 (void)sigaction(SIGURG, &sa, NULL);
555 sigfillset(&sa.sa_mask); /* block all signals in handler */
556 sa.sa_flags = SA_RESTART;
557 sa.sa_handler = sigquit;
558 (void)sigaction(SIGHUP, &sa, NULL);
559 (void)sigaction(SIGINT, &sa, NULL);
560 (void)sigaction(SIGQUIT, &sa, NULL);
561 (void)sigaction(SIGTERM, &sa, NULL);
563 sa.sa_handler = lostconn;
564 (void)sigaction(SIGPIPE, &sa, NULL);
566 addrlen = sizeof(ctrl_addr);
567 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
568 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
571 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
572 #ifdef VIRTUAL_HOSTING
573 /* select our identity from virtual host table */
574 selecthost(&ctrl_addr);
577 if (ctrl_addr.su_family == AF_INET)
579 tos = IPTOS_LOWDELAY;
580 if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
581 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
585 * Disable Nagle on the control channel so that we don't have to wait
586 * for peer's ACK before issuing our next reply.
588 if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
589 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
591 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
593 /* set this here so klogin can use it... */
594 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
596 /* Try to handle urgent data inline */
598 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
599 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
603 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
604 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
606 dolog((struct sockaddr *)&his_addr);
608 * Set up default state
617 /* If logins are disabled, print out the message. */
618 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
619 while (fgets(line, sizeof(line), fd) != NULL) {
620 if ((cp = strchr(line, '\n')) != NULL)
622 lreply(530, "%s", line);
624 (void) fflush(stdout);
626 reply(530, "System not available.");
629 #ifdef VIRTUAL_HOSTING
630 if ((fd = fopen(thishost->welcome, "r")) != NULL) {
632 if ((fd = fopen(_PATH_FTPWELCOME, "r")) != NULL) {
634 while (fgets(line, sizeof(line), fd) != NULL) {
635 if ((cp = strchr(line, '\n')) != NULL)
637 lreply(220, "%s", line);
639 (void) fflush(stdout);
641 /* reply(220,) must follow */
643 #ifndef VIRTUAL_HOSTING
644 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
645 fatalerror("Ran out of memory.");
646 (void) gethostname(hostname, MAXHOSTNAMELEN - 1);
647 hostname[MAXHOSTNAMELEN - 1] = '\0';
650 reply(220, "%s FTP server (%s) ready.", hostname, version);
652 reply(220, "FTP server ready.");
664 syslog(LOG_DEBUG, "lost connection");
673 syslog(LOG_ERR, "got signal %d", signo);
677 #ifdef VIRTUAL_HOSTING
679 * read in virtual host tables (if they exist)
688 char *cp, *mp, *line;
690 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
691 struct ftphost *hrp, *lhrp;
692 struct addrinfo hints, *res, *ai;
695 * Fill in the default host information
697 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
698 fatalerror("Ran out of memory.");
699 if (gethostname(hostname, MAXHOSTNAMELEN) < 0)
701 hostname[MAXHOSTNAMELEN - 1] = '\0';
702 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
703 fatalerror("Ran out of memory.");
704 hrp->hostname = hostname;
705 hrp->hostinfo = NULL;
707 memset(&hints, 0, sizeof(hints));
708 hints.ai_flags = AI_CANONNAME;
709 hints.ai_family = AF_UNSPEC;
710 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
712 hrp->statfile = _PATH_FTPDSTATFILE;
713 hrp->welcome = _PATH_FTPWELCOME;
714 hrp->loginmsg = _PATH_FTPLOGINMESG;
715 hrp->anonuser = "ftp";
717 thishost = firsthost = lhrp = hrp;
718 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
719 int addrsize, gothost;
723 while ((line = fgetln(fp, &len)) != NULL) {
729 if (line[len - 1] == '\n') {
730 line[len - 1] = '\0';
733 if ((mp = malloc(len + 1)) == NULL)
734 fatalerror("Ran out of memory.");
735 memcpy(mp, line, len);
739 cp = strtok(line, " \t");
740 /* skip empty lines */
747 statfile = _PATH_FTPDSTATFILE;
748 welcome = _PATH_FTPWELCOME;
749 loginmsg = _PATH_FTPLOGINMESG;
752 * Preparse the line so we can use its info
753 * for all the addresses associated with
754 * the virtual host name.
755 * Field 0, the virtual host name, is special:
756 * it's already parsed off and will be strdup'ed
757 * later, after we know its canonical form.
759 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
760 if (*cp != '-' && (cp = strdup(cp)))
762 case 1: /* anon user permissions */
765 case 2: /* statistics file */
768 case 3: /* welcome message */
771 case 4: /* login message */
774 default: /* programming error */
780 hints.ai_family = AF_UNSPEC;
781 hints.ai_flags = AI_PASSIVE;
782 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
784 for (ai = res; ai != NULL && ai->ai_addr != NULL;
788 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
791 for (hi = hrp->hostinfo; hi != NULL;
793 if (hi->ai_addrlen == ai->ai_addrlen &&
796 ai->ai_addr->sa_len) == 0) {
804 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
806 hrp->hostname = NULL;
809 if (hrp->hostinfo && hrp->hostinfo != res)
810 freeaddrinfo(hrp->hostinfo);
811 insert = 0; /* host already in the chain */
816 * determine hostname to use.
817 * force defined name if there is a valid alias
818 * otherwise fallback to primary hostname
820 /* XXX: getaddrinfo() can't do alias check */
821 switch(hrp->hostinfo->ai_family) {
823 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
824 addrsize = sizeof(struct in_addr);
827 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
828 addrsize = sizeof(struct in6_addr);
831 /* should not reach here */
832 freeaddrinfo(hrp->hostinfo);
834 free(hrp); /*not in chain, can free*/
836 hrp->hostinfo = NULL; /*mark as blank*/
840 if ((hp = getipnodebyaddr(addr, addrsize,
841 hrp->hostinfo->ai_family,
842 &hp_error)) != NULL) {
843 if (strcmp(vhost, hp->h_name) != 0) {
844 if (hp->h_aliases == NULL)
848 while (hp->h_aliases[i] &&
849 strcmp(vhost, hp->h_aliases[i]) != 0)
851 if (hp->h_aliases[i] == NULL)
857 strcmp(hrp->hostname, vhost) != 0) {
859 hrp->hostname = NULL;
861 if (hrp->hostname == NULL &&
862 (hrp->hostname = strdup(vhost)) == NULL) {
863 freeaddrinfo(hrp->hostinfo);
864 hrp->hostinfo = NULL; /* mark as blank */
869 hrp->anonuser = anonuser;
870 hrp->statfile = statfile;
871 hrp->welcome = welcome;
872 hrp->loginmsg = loginmsg;
896 struct in6_addr *mapped_in6 = NULL;
902 * XXX IPv4 mapped IPv6 addr consideraton,
903 * specified in rfc2373.
905 if (su->su_family == AF_INET6 &&
906 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
907 mapped_in6 = &su->su_sin6.sin6_addr;
910 hrp = thishost = firsthost; /* default */
913 while (hrp != NULL) {
914 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
915 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
920 /* XXX IPv4 mapped IPv6 addr consideraton */
921 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
922 (memcmp(&mapped_in6->s6_addr[12],
923 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
924 sizeof(struct in_addr)) == 0)) {
933 /* setup static variables as appropriate */
934 hostname = thishost->hostname;
935 ftpuser = thishost->anonuser;
940 * Helper function for sgetpwnam().
946 char *new = malloc((unsigned) strlen(s) + 1);
949 perror_reply(421, "Local resource failure: malloc");
953 (void) strcpy(new, s);
958 * Save the result of a getpwnam. Used for USER command, since
959 * the data returned must not be clobbered by any other command
962 static struct passwd *
966 static struct passwd save;
969 if ((p = getpwnam(name)) == NULL)
973 free(save.pw_passwd);
979 save.pw_name = sgetsave(p->pw_name);
980 save.pw_passwd = sgetsave(p->pw_passwd);
981 save.pw_gecos = sgetsave(p->pw_gecos);
982 save.pw_dir = sgetsave(p->pw_dir);
983 save.pw_shell = sgetsave(p->pw_shell);
987 static int login_attempts; /* number of failed login attempts */
988 static int askpasswd; /* had user command, ask for passwd */
989 static char curname[MAXLOGNAME]; /* current USER name */
993 * Sets global passwd pointer pw if named account exists and is acceptable;
994 * sets askpasswd if a PASS command is expected. If logged in previously,
995 * need to reset state. If name is "ftp" or "anonymous", the name is not in
996 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
997 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
998 * requesting login privileges. Disallow anyone who does not have a standard
999 * shell as returned by getusershell(). Disallow anyone mentioned in the file
1000 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
1010 reply(530, "Can't change user from guest login.");
1012 } else if (dochroot) {
1013 reply(530, "Can't change user from chroot user.");
1020 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1021 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL) ||
1022 checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL))
1023 reply(530, "User %s access denied.", name);
1024 #ifdef VIRTUAL_HOSTING
1025 else if ((pw = sgetpwnam(thishost->anonuser)) != NULL) {
1027 else if ((pw = sgetpwnam("ftp")) != NULL) {
1032 "Guest login ok, send your email address as password.");
1034 reply(530, "User %s unknown.", name);
1035 if (!askpasswd && logging)
1037 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1040 if (anon_only != 0) {
1041 reply(530, "Sorry, only anonymous ftp allowed.");
1045 if ((pw = sgetpwnam(name))) {
1046 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1047 shell = _PATH_BSHELL;
1048 while ((cp = getusershell()) != NULL)
1049 if (strcmp(cp, shell) == 0)
1053 if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1, NULL)) {
1054 reply(530, "User %s access denied.", name);
1057 "FTP LOGIN REFUSED FROM %s, %s",
1059 pw = (struct passwd *) NULL;
1064 strncpy(curname, name, sizeof(curname)-1);
1066 pwok = skeyaccess(name, NULL, remotehost, remotehost);
1067 reply(331, "%s", skey_challenge(name, pw, pwok));
1069 reply(331, "Password required for %s.", name);
1073 * Delay before reading passwd after first failed
1074 * attempt to slow down passwd-guessing programs.
1077 sleep((unsigned) login_attempts);
1081 * Check if a user is in the file "fname",
1082 * return a pointer to a malloc'd string with the rest
1083 * of the matching line in "residue" if not NULL.
1086 checkuser(fname, name, pwset, residue)
1095 char *line, *mp, *p;
1097 if ((fd = fopen(fname, "r")) != NULL) {
1098 while (!found && (line = fgetln(fd, &len)) != NULL) {
1102 if (line[len - 1] == '\n') {
1103 line[len - 1] = '\0';
1106 if ((mp = malloc(len + 1)) == NULL)
1107 fatalerror("Ran out of memory.");
1108 memcpy(mp, line, len);
1112 /* avoid possible leading and trailing whitespace */
1113 p = strtok(line, " \t");
1114 /* skip empty lines */
1118 * if first chr is '@', check group membership
1124 if (p[1] == '\0') /* single @ matches anyone */
1127 if ((grp = getgrnam(p+1)) == NULL)
1130 * Check user's default group
1132 if (pwset && grp->gr_gid == pw->pw_gid)
1135 * Check supplementary groups
1137 while (!found && grp->gr_mem[i])
1138 found = strcmp(name,
1144 * Otherwise, just check for username match
1147 found = strcmp(p, name) == 0;
1149 * Save the rest of line to "residue" if matched
1151 if (found && residue) {
1152 if ((p = strtok(NULL, "")) != NULL)
1153 p += strspn(p, " \t");
1155 if ((*residue = strdup(p)) == NULL)
1156 fatalerror("Ran out of memory.");
1170 * Terminate login as previous user, if any, resetting state;
1171 * used when USER command is given or login fails.
1177 (void) seteuid((uid_t)0);
1178 if (logged_in && dowtmp)
1179 ftpd_logwtmp(ttyline, "", NULL);
1182 setusercontext(NULL, getpwuid(0), (uid_t)0,
1183 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1193 * the following code is stolen from imap-uw PAM authentication module and
1196 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1199 const char *uname; /* user name */
1200 const char *pass; /* password */
1202 typedef struct cred_t cred_t;
1205 auth_conv(int num_msg, const struct pam_message **msg,
1206 struct pam_response **resp, void *appdata)
1209 cred_t *cred = (cred_t *) appdata;
1210 struct pam_response *reply =
1211 malloc(sizeof(struct pam_response) * num_msg);
1213 for (i = 0; i < num_msg; i++) {
1214 switch (msg[i]->msg_style) {
1215 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1216 reply[i].resp_retcode = PAM_SUCCESS;
1217 reply[i].resp = COPY_STRING(cred->uname);
1218 /* PAM frees resp. */
1220 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1221 reply[i].resp_retcode = PAM_SUCCESS;
1222 reply[i].resp = COPY_STRING(cred->pass);
1223 /* PAM frees resp. */
1227 reply[i].resp_retcode = PAM_SUCCESS;
1228 reply[i].resp = NULL;
1230 default: /* unknown message style */
1232 return PAM_CONV_ERR;
1241 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1242 * authenticated, or 1 if not authenticated. If some sort of PAM system
1243 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1244 * function returns -1. This can be used as an indication that we should
1245 * fall back to a different authentication mechanism.
1248 auth_pam(struct passwd **ppw, const char *pass)
1250 pam_handle_t *pamh = NULL;
1251 const char *tmpl_user;
1255 cred_t auth_cred = { (*ppw)->pw_name, pass };
1256 struct pam_conv conv = { &auth_conv, &auth_cred };
1258 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1259 if (e != PAM_SUCCESS) {
1260 syslog(LOG_ERR, "pam_start: %s", pam_strerror(pamh, e));
1264 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1265 if (e != PAM_SUCCESS) {
1266 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1267 pam_strerror(pamh, e));
1271 e = pam_authenticate(pamh, 0);
1275 * With PAM we support the concept of a "template"
1276 * user. The user enters a login name which is
1277 * authenticated by PAM, usually via a remote service
1278 * such as RADIUS or TACACS+. If authentication
1279 * succeeds, a different but related "template" name
1280 * is used for setting the credentials, shell, and
1281 * home directory. The name the user enters need only
1282 * exist on the remote authentication server, but the
1283 * template name must be present in the local password
1286 * This is supported by two various mechanisms in the
1287 * individual modules. However, from the application's
1288 * point of view, the template user is always passed
1289 * back as a changed value of the PAM_USER item.
1291 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1293 tmpl_user = (const char *) item;
1294 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1295 *ppw = getpwnam(tmpl_user);
1297 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1298 pam_strerror(pamh, e));
1303 case PAM_USER_UNKNOWN:
1309 syslog(LOG_ERR, "auth_pam: %s", pam_strerror(pamh, e));
1314 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1315 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1321 #endif /* !defined(NOPAM) */
1330 login_cap_t *lc = NULL;
1333 char *residue = NULL;
1335 if (logged_in || askpasswd == 0) {
1336 reply(503, "Login with USER first.");
1340 if (!guest) { /* "ftp" is only account allowed no password */
1342 rval = 1; /* failure below */
1346 rval = auth_pam(&pw, passwd);
1352 rval = strcmp(pw->pw_passwd,
1353 crypt(passwd, pw->pw_passwd));
1355 rval = strcmp(pw->pw_passwd,
1356 skey_crypt(passwd, pw->pw_passwd, pw, pwok));
1358 rval = strcmp(pw->pw_passwd, crypt(passwd, pw->pw_passwd));
1360 /* The strcmp does not catch null passwords! */
1361 if (*pw->pw_passwd == '\0' ||
1362 (pw->pw_expire && time(NULL) >= pw->pw_expire))
1363 rval = 1; /* failure */
1366 * If rval == 1, the user failed the authentication check
1367 * above. If rval == 0, either PAM or local authentication
1371 reply(530, "Login incorrect.");
1374 "FTP LOGIN FAILED FROM %s",
1376 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1377 "FTP LOGIN FAILED FROM %s, %s",
1378 remotehost, curname);
1381 if (login_attempts++ >= 5) {
1383 "repeated login failures from %s",
1393 login_attempts = 0; /* this time successful */
1394 if (setegid((gid_t)pw->pw_gid) < 0) {
1395 reply(550, "Can't set gid.");
1398 /* May be overridden by login.conf */
1399 (void) umask(defumask);
1401 if ((lc = login_getpwclass(pw)) != NULL) {
1402 char remote_ip[MAXHOSTNAMELEN];
1404 getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1405 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1407 remote_ip[sizeof(remote_ip) - 1] = 0;
1408 if (!auth_hostok(lc, remotehost, remote_ip)) {
1409 syslog(LOG_INFO|LOG_AUTH,
1410 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1412 reply(530, "Permission denied.\n");
1416 if (!auth_timeok(lc, time(NULL))) {
1417 reply(530, "Login not available right now.\n");
1422 setusercontext(lc, pw, (uid_t)0,
1423 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1424 LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1426 setlogin(pw->pw_name);
1427 (void) initgroups(pw->pw_name, pw->pw_gid);
1430 /* open wtmp before chroot */
1432 ftpd_logwtmp(ttyline, pw->pw_name,
1433 (struct sockaddr *)&his_addr);
1436 if (guest && stats && statfd < 0)
1437 #ifdef VIRTUAL_HOSTING
1438 if ((statfd = open(thishost->statfile, O_WRONLY|O_APPEND)) < 0)
1440 if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0)
1445 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue)
1446 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1447 || login_getcapbool(lc, "ftp-chroot", 0)
1452 * For a chrooted local user,
1453 * a) see whether ftpchroot(5) specifies a chroot directory,
1454 * b) extract the directory pathname from the line,
1455 * c) expand it to the absolute pathname if necessary.
1457 if (dochroot && residue &&
1458 (chrootdir = strtok(residue, " \t")) != NULL &&
1459 chrootdir[0] != '/') {
1460 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1461 if (chrootdir == NULL)
1462 fatalerror("Ran out of memory.");
1464 if (guest || dochroot) {
1466 * If no chroot directory set yet, use the login directory.
1467 * Copy it so it can be modified while pw->pw_dir stays intact.
1469 if (chrootdir == NULL &&
1470 (chrootdir = strdup(pw->pw_dir)) == NULL)
1471 fatalerror("Ran out of memory.");
1473 * Check for the "/chroot/./home" syntax,
1474 * separate the chroot and home directory pathnames.
1476 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1477 *(homedir++) = '\0'; /* wipe '/' */
1478 homedir++; /* skip '.' */
1479 /* so chrootdir can be freed later */
1480 if ((homedir = strdup(homedir)) == NULL)
1481 fatalerror("Ran out of memory.");
1484 * We MUST do a chdir() after the chroot. Otherwise
1485 * the old current directory will be accessible as "."
1486 * outside the new root!
1491 * Finally, do chroot()
1493 if (chroot(chrootdir) < 0) {
1494 reply(550, "Can't change root.");
1497 } else /* real user w/o chroot */
1498 homedir = pw->pw_dir;
1500 * Set euid *before* doing chdir() so
1501 * a) the user won't be carried to a directory that he couldn't reach
1502 * on his own due to no permission to upper path components,
1503 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1504 * (uid 0 has no root power over NFS if not mapped explicitly.)
1506 if (seteuid((uid_t)pw->pw_uid) < 0) {
1507 reply(550, "Can't set uid.");
1510 if (chdir(homedir) < 0) {
1511 if (guest || dochroot) {
1512 reply(550, "Can't change to base directory.");
1515 if (chdir("/") < 0) {
1516 reply(550, "Root is inaccessible.");
1519 lreply(230, "No directory! Logging in with home=/");
1524 * Display a login message, if it exists.
1525 * N.B. reply(230,) must follow the message.
1527 #ifdef VIRTUAL_HOSTING
1528 if ((fd = fopen(thishost->loginmsg, "r")) != NULL) {
1530 if ((fd = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) {
1532 char *cp, line[LINE_MAX];
1534 while (fgets(line, sizeof(line), fd) != NULL) {
1535 if ((cp = strchr(line, '\n')) != NULL)
1537 lreply(230, "%s", line);
1539 (void) fflush(stdout);
1545 ident = strdup(passwd);
1547 fatalerror("Ran out of memory.");
1549 reply(230, "Guest login ok, access restrictions apply.");
1551 #ifdef VIRTUAL_HOSTING
1552 if (thishost != firsthost)
1553 snprintf(proctitle, sizeof(proctitle),
1554 "%s: anonymous(%s)/%s", remotehost, hostname,
1558 snprintf(proctitle, sizeof(proctitle),
1559 "%s: anonymous/%s", remotehost, passwd);
1560 setproctitle("%s", proctitle);
1561 #endif /* SETPROCTITLE */
1563 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1564 remotehost, passwd);
1567 reply(230, "User %s logged in, "
1568 "access restrictions apply.", pw->pw_name);
1570 reply(230, "User %s logged in.", pw->pw_name);
1573 snprintf(proctitle, sizeof(proctitle),
1574 "%s: user/%s", remotehost, pw->pw_name);
1575 setproctitle("%s", proctitle);
1576 #endif /* SETPROCTITLE */
1578 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1579 remotehost, pw->pw_name);
1590 /* Forget all about it... */
1607 int (*closefunc) __P((FILE *));
1611 fin = fopen(name, "r"), closefunc = fclose;
1616 (void) snprintf(line, sizeof(line), cmd, name), name = line;
1617 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1619 st.st_blksize = BUFSIZ;
1623 perror_reply(550, name);
1625 LOGCMD("get", name);
1632 if (fstat(fileno(fin), &st) < 0) {
1633 perror_reply(550, name);
1636 if (!S_ISREG(st.st_mode)) {
1638 reply(550, "%s: not a plain file.", name);
1642 /* st.st_blksize is set for all descriptor types */
1645 if (restart_point) {
1646 if (type == TYPE_A) {
1653 if ((c=getc(fin)) == EOF) {
1654 perror_reply(550, name);
1660 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1661 perror_reply(550, name);
1665 dout = dataconn(name, st.st_size, "w");
1669 send_data(fin, dout, st.st_blksize, st.st_size,
1670 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1671 if (cmd == 0 && guest && stats)
1672 logxfer(name, st.st_size, start);
1673 (void) fclose(dout);
1678 LOGBYTES("get", name, byte_count);
1683 store(name, mode, unique)
1689 int (*closefunc) __P((FILE *));
1691 if (*mode == 'a') { /* APPE */
1693 /* Programming error */
1694 syslog(LOG_ERR, "Internal: unique flag to APPE");
1697 if (guest && noguestmod) {
1698 reply(550, "Appending to existing file denied");
1701 restart_point = 0; /* not affected by preceding REST */
1703 if (unique) /* STOU overrides REST */
1705 if (guest && noguestmod) {
1706 if (restart_point) { /* guest STOR w/REST */
1707 reply(550, "Modifying existing file denied");
1709 } else /* treat guest STOR as STOU */
1714 mode = "r+"; /* so ASCII manual seek can work */
1716 if ((fd = guniquefd(name, &name)) < 0)
1718 fout = fdopen(fd, mode);
1720 fout = fopen(name, mode);
1723 perror_reply(553, name);
1727 if (restart_point) {
1728 if (type == TYPE_A) {
1735 if ((c=getc(fout)) == EOF) {
1736 perror_reply(550, name);
1743 * We must do this seek to "current" position
1744 * because we are changing from reading to
1747 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1748 perror_reply(550, name);
1751 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1752 perror_reply(550, name);
1756 din = dataconn(name, (off_t)-1, "r");
1759 if (receive_data(din, fout) == 0) {
1761 reply(226, "Transfer complete (unique file name:%s).",
1764 reply(226, "Transfer complete.");
1770 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1774 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1782 int on = 1, s, t, tries;
1785 return (fdopen(data, mode));
1786 (void) seteuid((uid_t)0);
1788 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1791 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1792 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1793 /* anchor socket to avoid multi-homing problems */
1794 data_source = ctrl_addr;
1795 data_source.su_port = htons(dataport);
1796 for (tries = 1; ; tries++) {
1797 if (bind(s, (struct sockaddr *)&data_source,
1798 data_source.su_len) >= 0)
1800 if (errno != EADDRINUSE || tries > 10)
1804 (void) seteuid((uid_t)pw->pw_uid);
1806 if (data_source.su_family == AF_INET)
1808 on = IPTOS_THROUGHPUT;
1809 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1810 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1815 * Turn off push flag to keep sender TCP from sending short packets
1816 * at the boundaries of each write(). Should probably do a SO_SNDBUF
1817 * to set the send buffer size as well, but that may not be desirable
1818 * in heavy-load situations.
1821 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1822 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1826 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &on, sizeof on) < 0)
1827 syslog(LOG_WARNING, "data setsockopt (SO_SNDBUF): %m");
1830 return (fdopen(s, mode));
1832 /* Return the real value of errno (close may change it) */
1834 (void) seteuid((uid_t)pw->pw_uid);
1841 dataconn(name, size, mode)
1848 int retry = 0, tos, conerrno;
1852 if (size != (off_t) -1)
1853 (void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)", size);
1857 union sockunion from;
1859 int s, fromlen = ctrl_addr.su_len;
1860 struct timeval timeout;
1864 FD_SET(pdata, &set);
1866 timeout.tv_usec = 0;
1867 timeout.tv_sec = 120;
1870 * Granted a socket is in the blocking I/O mode,
1871 * accept() will block after a successful select()
1872 * if the selected connection dies in between.
1873 * Therefore set the non-blocking I/O flag here.
1875 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1876 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1878 if (select(pdata+1, &set, (fd_set *) 0, (fd_set *) 0, &timeout) <= 0 ||
1879 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1881 (void) close(pdata);
1884 * Unset the inherited non-blocking I/O flag
1885 * on the child socket so stdio can work on it.
1887 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1888 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1891 if (from.su_family == AF_INET)
1893 tos = IPTOS_THROUGHPUT;
1894 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1895 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1898 reply(150, "Opening %s mode data connection for '%s'%s.",
1899 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1900 return (fdopen(pdata, mode));
1902 reply(425, "Can't open data connection.");
1903 (void) close(pdata);
1908 reply(125, "Using existing data connection for '%s'%s.",
1911 return (fdopen(data, mode));
1914 data_dest = his_addr;
1917 file = getdatasock(mode);
1919 char hostbuf[BUFSIZ], portbuf[BUFSIZ];
1920 getnameinfo((struct sockaddr *)&data_source,
1921 data_source.su_len, hostbuf, sizeof(hostbuf) - 1,
1922 portbuf, sizeof(portbuf),
1923 NI_NUMERICHOST|NI_NUMERICSERV);
1924 reply(425, "Can't create data socket (%s,%s): %s.",
1925 hostbuf, portbuf, strerror(errno));
1928 data = fileno(file);
1930 if (connect(data, (struct sockaddr *)&data_dest,
1931 data_dest.su_len) == 0)
1934 (void) fclose(file);
1936 if (conerrno == EADDRINUSE) {
1937 sleep((unsigned) swaitint);
1942 } while (retry <= swaitmax);
1943 if (conerrno != 0) {
1944 perror_reply(425, "Can't build data connection");
1947 reply(150, "Opening %s mode data connection for '%s'%s.",
1948 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1953 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1954 * encapsulation of the data subject to Mode, Structure, and Type.
1956 * NB: Form isn't handled.
1959 send_data(instr, outstr, blksize, filesize, isreg)
1960 FILE *instr, *outstr;
1965 int c, filefd, netfd;
1973 while ((c = getc(instr)) != EOF) {
1980 (void) putc('\r', outstr);
1982 (void) putc(c, outstr);
1992 reply(226, "Transfer complete.");
1998 * isreg is only set if we are not doing restart and we
1999 * are sending a regular file
2001 netfd = fileno(outstr);
2002 filefd = fileno(instr);
2009 err = cnt = offset = 0;
2011 while (err != -1 && filesize > 0) {
2012 err = sendfile(filefd, netfd, offset, 0,
2013 (struct sf_hdtr *) NULL, &cnt, 0);
2015 * Calculate byte_count before OOB processing.
2016 * It can be used in myoob() later.
2033 reply(226, "Transfer complete.");
2038 if ((buf = malloc((u_int)blksize)) == NULL) {
2040 perror_reply(451, "Local resource failure: malloc");
2044 while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
2045 write(netfd, buf, cnt) == cnt)
2054 reply(226, "Transfer complete.");
2058 reply(550, "Unimplemented TYPE %d in send_data", type);
2064 perror_reply(426, "Data connection");
2069 perror_reply(551, "Error on input file");
2080 * Transfer data from peer to "outstr" using the appropriate encapulation of
2081 * the data subject to Mode, Structure, and Type.
2083 * N.B.: Form isn't handled.
2086 receive_data(instr, outstr)
2087 FILE *instr, *outstr;
2100 while ((cnt = read(fileno(instr), buf, sizeof(buf))) > 0) {
2103 if (write(fileno(outstr), buf, cnt) != cnt)
2115 reply(553, "TYPE E not implemented.");
2120 while ((c = getc(instr)) != EOF) {
2129 if ((c = getc(instr)) != '\n') {
2130 (void) putc ('\r', outstr);
2131 if (c == '\0' || c == EOF)
2135 (void) putc(c, outstr);
2148 "WARNING! %d bare linefeeds received in ASCII mode",
2150 (void)printf(" File may not have transferred correctly.\r\n");
2154 reply(550, "Unimplemented TYPE %d in receive_data", type);
2161 perror_reply(426, "Data Connection");
2166 perror_reply(452, "Error writing file");
2177 statfilecmd(filename)
2183 char line[LINE_MAX];
2185 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2186 fin = ftpd_popen(line, "r");
2187 lreply(211, "status of %s:", filename);
2189 while ((c = getc(fin)) != EOF) {
2191 if (ferror(stdout)){
2192 perror_reply(421, "control connection");
2193 (void) ftpd_pclose(fin);
2198 perror_reply(551, filename);
2199 (void) ftpd_pclose(fin);
2202 (void) putc('\r', stdout);
2205 * RFC 959 says neutral text should be prepended before
2206 * a leading 3-digit number followed by whitespace, but
2207 * many ftp clients can be confused by any leading digits,
2208 * as a matter of fact.
2210 if (atstart && isdigit(c))
2211 (void) putc(' ', stdout);
2212 (void) putc(c, stdout);
2213 atstart = (c == '\n');
2215 (void) ftpd_pclose(fin);
2216 reply(211, "End of Status");
2222 union sockunion *su;
2224 char hname[NI_MAXHOST];
2228 lreply(211, "%s FTP server status:", hostname);
2229 printf(" %s\r\n", version);
2231 lreply(211, "FTP server status:");
2232 printf(" Connected to %s", remotehost);
2233 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2234 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2235 if (strcmp(hname, remotehost) != 0)
2236 printf(" (%s)", hname);
2241 printf(" Logged in anonymously\r\n");
2243 printf(" Logged in as %s\r\n", pw->pw_name);
2244 } else if (askpasswd)
2245 printf(" Waiting for password\r\n");
2247 printf(" Waiting for user name\r\n");
2248 printf(" TYPE: %s", typenames[type]);
2249 if (type == TYPE_A || type == TYPE_E)
2250 printf(", FORM: %s", formnames[form]);
2253 printf(" %d", NBBY);
2255 printf(" %d", bytesize); /* need definition! */
2257 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2258 strunames[stru], modenames[mode]);
2260 printf(" Data connection open\r\n");
2261 else if (pdata != -1) {
2265 } else if (usedefault == 0) {
2269 #define UC(b) (((int) b) & 0xff)
2271 printf(" EPSV only mode (EPSV ALL)\r\n");
2276 if (su->su_family == AF_INET) {
2277 a = (u_char *) &su->su_sin.sin_addr;
2278 p = (u_char *) &su->su_sin.sin_port;
2279 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2280 ispassive ? "PASV" : "PORT",
2281 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2282 UC(p[0]), UC(p[1]));
2289 switch (su->su_family) {
2291 a = (u_char *) &su->su_sin.sin_addr;
2292 p = (u_char *) &su->su_sin.sin_port;
2293 alen = sizeof(su->su_sin.sin_addr);
2297 a = (u_char *) &su->su_sin6.sin6_addr;
2298 p = (u_char *) &su->su_sin6.sin6_port;
2299 alen = sizeof(su->su_sin6.sin6_addr);
2307 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2309 for (i = 0; i < alen; i++)
2310 printf("%d,", UC(a[i]));
2311 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2320 switch (su->su_family) {
2332 union sockunion tmp;
2335 if (tmp.su_family == AF_INET6)
2336 tmp.su_sin6.sin6_scope_id = 0;
2337 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2338 hname, sizeof(hname) - 1, NULL, 0,
2340 printf(" %s |%d|%s|%d|\r\n",
2341 ispassive ? "EPSV" : "EPRT",
2342 af, hname, htons(tmp.su_port));
2348 printf(" No data connection\r\n");
2349 reply(211, "End of status");
2357 reply(451, "Error in server: %s\n", s);
2358 reply(221, "Closing connection due to server error.");
2365 reply(int n, const char *fmt, ...)
2367 reply(n, fmt, va_alist)
2379 (void)printf("%d ", n);
2380 (void)vprintf(fmt, ap);
2381 (void)printf("\r\n");
2382 (void)fflush(stdout);
2384 syslog(LOG_DEBUG, "<--- %d ", n);
2385 vsyslog(LOG_DEBUG, fmt, ap);
2391 lreply(int n, const char *fmt, ...)
2393 lreply(n, fmt, va_alist)
2405 (void)printf("%d- ", n);
2406 (void)vprintf(fmt, ap);
2407 (void)printf("\r\n");
2408 (void)fflush(stdout);
2410 syslog(LOG_DEBUG, "<--- %d- ", n);
2411 vsyslog(LOG_DEBUG, fmt, ap);
2420 reply(250, "%s command successful.", s);
2428 reply(502, "%s command not implemented.", s);
2438 if ((cp = strchr(cbuf,'\n')))
2440 reply(500, "'%s': command not understood.", cbuf);
2449 LOGCMD("delete", name);
2450 if (lstat(name, &st) < 0) {
2451 perror_reply(550, name);
2454 if ((st.st_mode&S_IFMT) == S_IFDIR) {
2455 if (rmdir(name) < 0) {
2456 perror_reply(550, name);
2461 if (unlink(name) < 0) {
2462 perror_reply(550, name);
2474 if (chdir(path) < 0)
2475 perror_reply(550, path);
2486 LOGCMD("mkdir", name);
2487 if (guest && noguestmkd)
2488 reply(550, "%s: permission denied", name);
2489 else if (mkdir(name, 0777) < 0)
2490 perror_reply(550, name);
2492 if ((s = doublequote(name)) == NULL)
2493 fatalerror("Ran out of memory.");
2494 reply(257, "\"%s\" directory created.", s);
2504 LOGCMD("rmdir", name);
2505 if (rmdir(name) < 0)
2506 perror_reply(550, name);
2514 char *s, path[MAXPATHLEN + 1];
2516 if (getwd(path) == (char *)NULL)
2517 reply(550, "%s.", path);
2519 if ((s = doublequote(path)) == NULL)
2520 fatalerror("Ran out of memory.");
2521 reply(257, "\"%s\" is current directory.", s);
2532 if (lstat(name, &st) < 0) {
2533 perror_reply(550, name);
2536 reply(350, "File exists, ready for destination name");
2546 LOGCMD2("rename", from, to);
2548 if (guest && (stat(to, &st) == 0)) {
2549 reply(550, "%s: permission denied", to);
2553 if (rename(from, to) < 0)
2554 perror_reply(550, "rename");
2561 struct sockaddr *who;
2565 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2568 #ifdef VIRTUAL_HOSTING
2569 if (thishost != firsthost)
2570 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2571 remotehost, hostname);
2574 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2576 setproctitle("%s", proctitle);
2577 #endif /* SETPROCTITLE */
2580 #ifdef VIRTUAL_HOSTING
2581 if (thishost != firsthost)
2582 syslog(LOG_INFO, "connection from %s (to %s)",
2583 remotehost, hostname);
2587 char who_name[MAXHOSTNAMELEN];
2589 error = getnameinfo(who, who->sa_len,
2590 who_name, sizeof(who_name) - 1,
2591 NULL, 0, NI_NUMERICHOST);
2592 syslog(LOG_INFO, "connection from %s (%s)", remotehost,
2593 error == 0 ? who_name : "");
2599 * Record logout in wtmp file
2600 * and exit with supplied status.
2607 * Prevent reception of SIGURG from resulting in a resumption
2608 * back to the main program loop.
2612 if (logged_in && dowtmp) {
2613 (void) seteuid((uid_t)0);
2614 ftpd_logwtmp(ttyline, "", NULL);
2616 /* beware of flushing buffers after a SIGPIPE */
2633 /* only process if transfer occurring */
2637 if (getline(cp, 7, stdin) == NULL) {
2638 reply(221, "You could at least say goodbye.");
2642 if (strcmp(cp, "ABOR\r\n") == 0) {
2644 reply(426, "Transfer aborted. Data connection closed.");
2645 reply(226, "Abort successful");
2647 if (strcmp(cp, "STAT\r\n") == 0) {
2649 if (file_size != (off_t) -1)
2650 reply(213, "Status: %qd of %qd bytes transferred",
2651 byte_count, file_size);
2653 reply(213, "Status: %qd bytes transferred", byte_count);
2658 * Note: a response of 425 is not mentioned as a possible response to
2659 * the PASV command in RFC959. However, it has been blessed as
2660 * a legitimate response by Jon Postel in a telephone conversation
2661 * with Rick Adams on 25 Jan 89.
2669 if (pdata >= 0) /* close old port if one set */
2672 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2674 perror_reply(425, "Can't open passive connection");
2678 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2679 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2681 (void) seteuid((uid_t)0);
2684 if (ctrl_addr.su_family == AF_INET) {
2685 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2686 : IP_PORTRANGE_DEFAULT;
2688 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2689 &on, sizeof(on)) < 0)
2693 #ifdef IPV6_PORTRANGE
2694 if (ctrl_addr.su_family == AF_INET6) {
2695 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2696 : IPV6_PORTRANGE_DEFAULT;
2698 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2699 &on, sizeof(on)) < 0)
2704 pasv_addr = ctrl_addr;
2705 pasv_addr.su_port = 0;
2706 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2709 (void) seteuid((uid_t)pw->pw_uid);
2711 len = sizeof(pasv_addr);
2712 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2714 if (listen(pdata, 1) < 0)
2716 if (pasv_addr.su_family == AF_INET)
2717 a = (char *) &pasv_addr.su_sin.sin_addr;
2718 else if (pasv_addr.su_family == AF_INET6 &&
2719 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2720 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2724 p = (char *) &pasv_addr.su_port;
2726 #define UC(b) (((int) b) & 0xff)
2728 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2729 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2733 (void) seteuid((uid_t)pw->pw_uid);
2734 (void) close(pdata);
2736 perror_reply(425, "Can't open passive connection");
2741 * Long Passive defined in RFC 1639.
2742 * 228 Entering Long Passive Mode
2743 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2747 long_passive(cmd, pf)
2754 if (pdata >= 0) /* close old port if one set */
2757 if (pf != PF_UNSPEC) {
2758 if (ctrl_addr.su_family != pf) {
2759 switch (ctrl_addr.su_family) {
2772 * only EPRT/EPSV ready clients will understand this
2774 if (strcmp(cmd, "EPSV") == 0 && pf) {
2775 reply(522, "Network protocol mismatch, "
2778 reply(501, "Network protocol mismatch"); /*XXX*/
2784 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2786 perror_reply(425, "Can't open passive connection");
2790 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2791 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2793 (void) seteuid((uid_t)0);
2795 pasv_addr = ctrl_addr;
2796 pasv_addr.su_port = 0;
2797 len = pasv_addr.su_len;
2800 if (ctrl_addr.su_family == AF_INET) {
2801 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2802 : IP_PORTRANGE_DEFAULT;
2804 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2805 &on, sizeof(on)) < 0)
2809 #ifdef IPV6_PORTRANGE
2810 if (ctrl_addr.su_family == AF_INET6) {
2811 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2812 : IPV6_PORTRANGE_DEFAULT;
2814 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2815 &on, sizeof(on)) < 0)
2820 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2823 (void) seteuid((uid_t)pw->pw_uid);
2825 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2827 if (listen(pdata, 1) < 0)
2830 #define UC(b) (((int) b) & 0xff)
2832 if (strcmp(cmd, "LPSV") == 0) {
2833 p = (char *)&pasv_addr.su_port;
2834 switch (pasv_addr.su_family) {
2836 a = (char *) &pasv_addr.su_sin.sin_addr;
2839 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2840 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2841 2, UC(p[0]), UC(p[1]));
2844 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
2845 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2848 a = (char *) &pasv_addr.su_sin6.sin6_addr;
2850 "Entering Long Passive Mode "
2851 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2852 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2853 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2854 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2855 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2856 2, UC(p[0]), UC(p[1]));
2859 } else if (strcmp(cmd, "EPSV") == 0) {
2860 switch (pasv_addr.su_family) {
2863 reply(229, "Entering Extended Passive Mode (|||%d|)",
2864 ntohs(pasv_addr.su_port));
2868 /* more proper error code? */
2872 (void) seteuid((uid_t)pw->pw_uid);
2873 (void) close(pdata);
2875 perror_reply(425, "Can't open passive connection");
2880 * Generate unique name for file with basename "local"
2881 * and open the file in order to avoid possible races.
2882 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
2883 * Return descriptor to the file, set "name" to its name.
2885 * Generates failure reply on error.
2888 guniquefd(local, name)
2892 static char new[MAXPATHLEN];
2898 cp = strrchr(local, '/');
2901 if (stat(cp ? local : ".", &st) < 0) {
2902 perror_reply(553, cp ? local : ".");
2907 * Let not overwrite dirname with counter suffix.
2909 * In this extreme case dot won't be put in front of suffix.
2911 if (strlen(local) > sizeof(new) - 4) {
2912 reply(553, "Pathname too long");
2917 /* -4 is for the .nn<null> we put on the end below */
2918 (void) snprintf(new, sizeof(new) - 4, "%s", local);
2919 cp = new + strlen(new);
2921 * Don't generate dotfile unless requested explicitly.
2922 * This covers the case when basename gets truncated off
2925 if (cp > new && cp[-1] != '/')
2927 for (count = 0; count < 100; count++) {
2928 /* At count 0 try unmodified name */
2930 (void)sprintf(cp, "%d", count);
2931 if ((fd = open(count ? new : local,
2932 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
2933 *name = count ? new : local;
2936 if (errno != EEXIST) {
2937 perror_reply(553, count ? new : local);
2941 reply(452, "Unique file name cannot be created.");
2946 * Format and send reply containing system error number.
2949 perror_reply(code, string)
2954 reply(code, "%s: %s.", string, strerror(errno));
2957 static char *onefile[] = {
2963 send_file_list(whichf)
2970 char **dirlist, *dirname;
2975 if (strpbrk(whichf, "~{[*?") != NULL) {
2976 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
2978 memset(&gl, 0, sizeof(gl));
2979 gl.gl_matchc = MAXGLOBARGS;
2980 flags |= GLOB_LIMIT;
2982 if (glob(whichf, flags, 0, &gl)) {
2983 reply(550, "not found");
2985 } else if (gl.gl_pathc == 0) {
2987 perror_reply(550, whichf);
2990 dirlist = gl.gl_pathv;
2992 onefile[0] = whichf;
2997 while ((dirname = *dirlist++)) {
2998 if (stat(dirname, &st) < 0) {
3000 * If user typed "ls -l", etc, and the client
3001 * used NLST, do what the user meant.
3003 if (dirname[0] == '-' && *dirlist == NULL &&
3005 retrieve(_PATH_LS " %s", dirname);
3008 perror_reply(550, whichf);
3010 (void) fclose(dout);
3018 if (S_ISREG(st.st_mode)) {
3020 dout = dataconn("file list", (off_t)-1, "w");
3025 fprintf(dout, "%s%s\n", dirname,
3026 type == TYPE_A ? "\r" : "");
3027 byte_count += strlen(dirname) + 1;
3029 } else if (!S_ISDIR(st.st_mode))
3032 if ((dirp = opendir(dirname)) == NULL)
3035 while ((dir = readdir(dirp)) != NULL) {
3036 char nbuf[MAXPATHLEN];
3045 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
3047 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3051 snprintf(nbuf, sizeof(nbuf),
3052 "%s/%s", dirname, dir->d_name);
3055 * We have to do a stat to insure it's
3056 * not a directory or special file.
3058 if (simple || (stat(nbuf, &st) == 0 &&
3059 S_ISREG(st.st_mode))) {
3061 dout = dataconn("file list", (off_t)-1,
3067 if (nbuf[0] == '.' && nbuf[1] == '/')
3068 fprintf(dout, "%s%s\n", &nbuf[2],
3069 type == TYPE_A ? "\r" : "");
3071 fprintf(dout, "%s%s\n", nbuf,
3072 type == TYPE_A ? "\r" : "");
3073 byte_count += strlen(nbuf) + 1;
3076 (void) closedir(dirp);
3080 reply(550, "No files found.");
3081 else if (ferror(dout) != 0)
3082 perror_reply(550, "Data connection");
3084 reply(226, "Transfer complete.");
3088 (void) fclose(dout);
3102 while (wait3(NULL, WNOHANG, NULL) > 0);
3105 #ifdef OLD_SETPROCTITLE
3107 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.)
3108 * Warning, since this is usually started from inetd.conf, it often doesn't
3109 * have much of an environment or arglist to overwrite.
3113 setproctitle(const char *fmt, ...)
3115 setproctitle(fmt, va_alist)
3130 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
3132 /* make ps print our process name */
3137 if (i > LastArgv - p - 2) {
3138 i = LastArgv - p - 2;
3143 if (ch != '\n' && ch != '\r')
3145 while (p < LastArgv)
3148 #endif /* OLD_SETPROCTITLE */
3151 logxfer(name, size, start)
3157 char path[MAXPATHLEN + 1];
3160 if (statfd >= 0 && getwd(path) != NULL) {
3162 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s/%s!%qd!%ld\n",
3163 ctime(&now)+4, ident, remotehost,
3164 path, name, (long long)size,
3165 (long)(now - start + (now == start)));
3166 write(statfd, buf, strlen(buf));
3177 for (p = s, n = 0; *p; p++)
3181 if ((s2 = malloc(p - s + n + 1)) == NULL)
3184 for (p = s2; *s; s++, p++) {
3185 if ((*p = *s) == '"')