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. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#)ftpd.c 8.4 (Berkeley) 4/16/94
30 * $FreeBSD: src/libexec/ftpd/ftpd.c,v 1.213 2008/12/23 01:23:09 cperciva Exp $
36 #include <sys/param.h>
37 #include <sys/ioctl.h>
39 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <netinet/in_systm.h>
46 #include <netinet/ip.h>
47 #include <netinet/tcp.h>
51 #include <arpa/inet.h>
52 #include <arpa/telnet.h>
75 #include <login_cap.h>
79 #include <security/pam_appl.h>
82 #include "pathnames.h"
87 static char version[] = "Version 6.00LS";
90 extern off_t restart_point;
93 union sockunion ctrl_addr;
94 union sockunion data_source;
95 union sockunion data_dest;
96 union sockunion his_addr;
97 union sockunion pasv_addr;
102 int hostinfo = 1; /* print host-specific info in messages */
107 int timeout = 900; /* timeout after 15 minutes of inactivity */
108 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
110 int restricted_data_ports = 1;
111 int paranoid = 1; /* be extra careful about security */
112 int anon_only = 0; /* Only anonymous ftp allowed */
113 int assumeutf8 = 0; /* Assume that server file names are in UTF-8 */
122 int stru; /* avoid C keyword */
124 int usedefault = 1; /* for data transfers */
125 int pdata = -1; /* for passive mode */
126 int readonly = 0; /* Server is in readonly mode. */
127 int noepsv = 0; /* EPSV command is disabled. */
128 int noretr = 0; /* RETR command is disabled. */
129 int noguestretr = 0; /* RETR command is disabled for anon users. */
130 int noguestmkd = 0; /* MKD command is disabled for anon users. */
131 int noguestmod = 1; /* anon users may not modify existing files. */
135 #if !defined(CMASK) || CMASK == 0
139 int defumask = CMASK; /* default umask value */
144 #ifdef VIRTUAL_HOSTING
147 static struct ftphost {
148 struct ftphost *next;
149 struct addrinfo *hostinfo;
155 } *thishost, *firsthost;
158 char remotehost[NI_MAXHOST];
161 static char ttyline[20];
162 char *tty = ttyline; /* for klogin */
165 static int auth_pam(struct passwd**, const char*);
166 pam_handle_t *pamh = NULL;
169 static struct opie opiedata;
170 static char opieprompt[OPIE_CHALLENGE_MAX+1];
173 char *pid_file = NULL; /* means default location to pidfile(3) */
176 * Limit number of pathnames that glob can return.
177 * A limit of 0 indicates the number of pathnames is unlimited.
179 #define MAXGLOBARGS 16384
182 * Timeout intervals for retrying connections
183 * to hosts that don't accept PORT cmds. This
184 * is a kludge, but given the problems with TCP...
186 #define SWAITMAX 90 /* wait at most 90 seconds */
187 #define SWAITINT 5 /* interval between retries */
189 int swaitmax = SWAITMAX;
190 int swaitint = SWAITINT;
193 char proctitle[LINE_MAX]; /* initial part of title */
194 #endif /* SETPROCTITLE */
196 #define LOGCMD(cmd, file) logcmd((cmd), (file), NULL, -1)
197 #define LOGCMD2(cmd, file1, file2) logcmd((cmd), (file1), (file2), -1)
198 #define LOGBYTES(cmd, file, cnt) logcmd((cmd), (file), NULL, (cnt))
200 static volatile sig_atomic_t recvurg;
201 static int transflag; /* NB: for debugging only */
203 #define STARTXFER flagxfer(1)
204 #define ENDXFER flagxfer(0)
206 #define START_UNSAFE maskurg(1)
207 #define END_UNSAFE maskurg(0)
209 /* It's OK to put an `else' clause after this macro. */
210 #define CHECKOOB(action) \
219 #ifdef VIRTUAL_HOSTING
220 static void inithosts(int);
221 static void selecthost(union sockunion *);
223 static void ack(char *);
224 static void sigurg(int);
225 static void maskurg(int);
226 static void flagxfer(int);
227 static int myoob(void);
228 static int checkuser(char *, char *, int, char **);
229 static FILE *dataconn(char *, off_t, char *);
230 static void dolog(struct sockaddr *);
231 static void end_login(void);
232 static FILE *getdatasock(char *);
233 static int guniquefd(char *, char **);
234 static void lostconn(int);
235 static void sigquit(int);
236 static int receive_data(FILE *, FILE *);
237 static int send_data(FILE *, FILE *, size_t, off_t, int);
238 static struct passwd *
240 static char *sgetsave(char *);
241 static void reapchild(int);
242 static void appendf(char **, char *, ...) __printflike(2, 3);
243 static void logcmd(char *, char *, char *, off_t);
244 static void logxfer(char *, off_t, time_t);
245 static char *doublequote(char *);
246 static int *socksetup(int, char *, const char *);
249 main(int argc, char *argv[])
253 char *cp, line[LINE_MAX];
255 char *bindname = NULL;
256 const char *bindport = "ftp";
257 int family = AF_UNSPEC;
260 tzset(); /* in case no timezone database in ~ftp */
261 sigemptyset(&sa.sa_mask);
262 sa.sa_flags = SA_RESTART;
265 * Prevent diagnostic messages from appearing on stderr.
266 * We run as a daemon or from inetd; in both cases, there's
267 * more reason in logging to syslog.
269 freopen(_PATH_DEVNULL, "w", stderr);
273 * LOG_NDELAY sets up the logging connection immediately,
274 * necessary for anonymous ftp's that chroot and can't do it later.
276 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
278 while ((ch = getopt(argc, argv,
279 "468a:AdDEH:hlmMoOp:P:rRSt:T:u:UvW")) != -1) {
282 family = (family == AF_INET6) ? AF_UNSPEC : AF_INET;
286 family = (family == AF_INET) ? AF_UNSPEC : AF_INET6;
322 logging++; /* > 1 == extra logging */
362 timeout = atoi(optarg);
363 if (maxtimeout < timeout)
364 maxtimeout = timeout;
368 maxtimeout = atoi(optarg);
369 if (timeout > maxtimeout)
370 timeout = maxtimeout;
377 val = strtol(optarg, &optarg, 8);
378 if (*optarg != '\0' || val < 0)
379 syslog(LOG_WARNING, "bad value for -u");
385 restricted_data_ports = 0;
397 syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
403 int *ctl_sock, fd, maxfd = -1, nfds, i;
404 fd_set defreadfds, readfds;
408 if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
409 if (errno == EEXIST) {
410 syslog(LOG_ERR, "%s already running, pid %d",
411 getprogname(), (int)pid);
414 syslog(LOG_WARNING, "pidfile_open: %m");
418 * Detach from parent.
420 if (daemon(1, 1) < 0) {
421 syslog(LOG_ERR, "failed to become a daemon");
425 if (pfh != NULL && pidfile_write(pfh) == -1)
426 syslog(LOG_WARNING, "pidfile_write: %m");
428 sa.sa_handler = reapchild;
429 sigaction(SIGCHLD, &sa, NULL);
431 #ifdef VIRTUAL_HOSTING
436 * Open a socket, bind it to the FTP port, and start
439 ctl_sock = socksetup(family, bindname, bindport);
440 if (ctl_sock == NULL)
443 FD_ZERO(&defreadfds);
444 for (i = 1; i <= *ctl_sock; i++) {
445 FD_SET(ctl_sock[i], &defreadfds);
446 if (listen(ctl_sock[i], 32) < 0) {
447 syslog(LOG_ERR, "control listen: %m");
450 if (maxfd < ctl_sock[i])
455 * Loop forever accepting connection requests and forking off
456 * children to handle them.
459 FD_COPY(&defreadfds, &readfds);
460 nfds = select(maxfd + 1, &readfds, NULL, NULL, 0);
462 if (nfds < 0 && errno != EINTR)
463 syslog(LOG_WARNING, "select: %m");
468 for (i = 1; i <= *ctl_sock; i++)
469 if (FD_ISSET(ctl_sock[i], &readfds)) {
470 addrlen = sizeof(his_addr);
471 fd = accept(ctl_sock[i],
472 (struct sockaddr *)&his_addr,
479 switch (pid = fork()) {
485 for (i = 1; i <= *ctl_sock; i++)
491 syslog(LOG_WARNING, "fork: %m");
499 addrlen = sizeof(his_addr);
500 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
501 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
505 #ifdef VIRTUAL_HOSTING
506 if (his_addr.su_family == AF_INET6 &&
507 IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))
510 family = his_addr.su_family;
516 sa.sa_handler = SIG_DFL;
517 sigaction(SIGCHLD, &sa, NULL);
519 sa.sa_handler = sigurg;
520 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
521 sigaction(SIGURG, &sa, NULL);
523 sigfillset(&sa.sa_mask); /* block all signals in handler */
524 sa.sa_flags = SA_RESTART;
525 sa.sa_handler = sigquit;
526 sigaction(SIGHUP, &sa, NULL);
527 sigaction(SIGINT, &sa, NULL);
528 sigaction(SIGQUIT, &sa, NULL);
529 sigaction(SIGTERM, &sa, NULL);
531 sa.sa_handler = lostconn;
532 sigaction(SIGPIPE, &sa, NULL);
534 addrlen = sizeof(ctrl_addr);
535 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
536 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
539 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
540 #ifdef VIRTUAL_HOSTING
541 /* select our identity from virtual host table */
542 selecthost(&ctrl_addr);
545 if (ctrl_addr.su_family == AF_INET)
547 tos = IPTOS_LOWDELAY;
548 if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
549 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
553 * Disable Nagle on the control channel so that we don't have to wait
554 * for peer's ACK before issuing our next reply.
556 if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
557 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
559 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
561 /* set this here so klogin can use it... */
562 snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
564 /* Try to handle urgent data inline */
566 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
567 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
571 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
572 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
574 dolog((struct sockaddr *)&his_addr);
576 * Set up default state
585 /* If logins are disabled, print out the message. */
586 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
587 while (fgets(line, sizeof(line), fd) != NULL) {
588 if ((cp = strchr(line, '\n')) != NULL)
590 lreply(530, "%s", line);
594 reply(530, "System not available.");
597 #ifdef VIRTUAL_HOSTING
598 fd = fopen(thishost->welcome, "r");
600 fd = fopen(_PATH_FTPWELCOME, "r");
603 while (fgets(line, sizeof(line), fd) != NULL) {
604 if ((cp = strchr(line, '\n')) != NULL)
606 lreply(220, "%s", line);
610 /* reply(220,) must follow */
612 #ifndef VIRTUAL_HOSTING
613 if (hostname == NULL) {
614 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
615 fatalerror("Ran out of memory.");
616 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
618 hostname[MAXHOSTNAMELEN - 1] = '\0';
622 reply(220, "%s FTP server (%s) ready.", hostname, version);
624 reply(220, "FTP server ready.");
635 syslog(LOG_DEBUG, "lost connection");
643 syslog(LOG_ERR, "got signal %d", signo);
647 #ifdef VIRTUAL_HOSTING
649 * read in virtual host tables (if they exist)
653 inithosts(int family)
658 char *cp, *mp, *line;
659 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
660 struct ftphost *hrp, *lhrp;
661 struct addrinfo hints, *res, *ai;
664 * Fill in the default host information
666 if (hostname == NULL) {
667 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
668 fatalerror("Ran out of memory.");
669 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
671 hostname[MAXHOSTNAMELEN - 1] = '\0';
673 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
674 fatalerror("Ran out of memory.");
675 hrp->hostname = hostname;
676 hrp->hostinfo = NULL;
678 memset(&hints, 0, sizeof(hints));
679 hints.ai_flags = AI_PASSIVE;
680 hints.ai_family = family;
681 hints.ai_socktype = SOCK_STREAM;
682 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
684 hrp->statfile = _PATH_FTPDSTATFILE;
685 hrp->welcome = _PATH_FTPWELCOME;
686 hrp->loginmsg = _PATH_FTPLOGINMESG;
687 hrp->anonuser = "ftp";
689 thishost = firsthost = lhrp = hrp;
690 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
691 int addrsize, gothost;
695 while ((line = fgetln(fp, &len)) != NULL) {
701 if (line[len - 1] == '\n') {
702 line[len - 1] = '\0';
705 if ((mp = malloc(len + 1)) == NULL)
706 fatalerror("Ran out of memory.");
707 memcpy(mp, line, len);
711 cp = strtok(line, " \t");
712 /* skip empty lines */
719 statfile = _PATH_FTPDSTATFILE;
720 welcome = _PATH_FTPWELCOME;
721 loginmsg = _PATH_FTPLOGINMESG;
724 * Preparse the line so we can use its info
725 * for all the addresses associated with
726 * the virtual host name.
727 * Field 0, the virtual host name, is special:
728 * it's already parsed off and will be strdup'ed
729 * later, after we know its canonical form.
731 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
732 if (*cp != '-' && (cp = strdup(cp)))
734 case 1: /* anon user permissions */
737 case 2: /* statistics file */
740 case 3: /* welcome message */
743 case 4: /* login message */
746 default: /* programming error */
751 hints.ai_flags = AI_PASSIVE;
752 hints.ai_family = family;
753 hints.ai_socktype = SOCK_STREAM;
754 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
756 for (ai = res; ai != NULL && ai->ai_addr != NULL;
760 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
763 for (hi = hrp->hostinfo; hi != NULL;
765 if (hi->ai_addrlen == ai->ai_addrlen &&
768 ai->ai_addr->sa_len) == 0) {
776 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
778 hrp->hostname = NULL;
781 if (hrp->hostinfo && hrp->hostinfo != res)
782 freeaddrinfo(hrp->hostinfo);
783 insert = 0; /* host already in the chain */
788 * determine hostname to use.
789 * force defined name if there is a valid alias
790 * otherwise fallback to primary hostname
792 /* XXX: getaddrinfo() can't do alias check */
793 switch(hrp->hostinfo->ai_family) {
795 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
796 addrsize = sizeof(struct in_addr);
799 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
800 addrsize = sizeof(struct in6_addr);
803 /* should not reach here */
804 freeaddrinfo(hrp->hostinfo);
806 free(hrp); /*not in chain, can free*/
808 hrp->hostinfo = NULL; /*mark as blank*/
812 if ((hp = getipnodebyaddr(addr, addrsize,
813 hrp->hostinfo->ai_family,
814 &hp_error)) != NULL) {
815 if (strcmp(vhost, hp->h_name) != 0) {
816 if (hp->h_aliases == NULL)
820 while (hp->h_aliases[i] &&
821 strcmp(vhost, hp->h_aliases[i]) != 0)
823 if (hp->h_aliases[i] == NULL)
829 strcmp(hrp->hostname, vhost) != 0) {
831 hrp->hostname = NULL;
833 if (hrp->hostname == NULL &&
834 (hrp->hostname = strdup(vhost)) == NULL) {
835 freeaddrinfo(hrp->hostinfo);
836 hrp->hostinfo = NULL; /* mark as blank */
841 hrp->anonuser = anonuser;
842 hrp->statfile = statfile;
843 hrp->welcome = welcome;
844 hrp->loginmsg = loginmsg;
862 selecthost(union sockunion *su)
867 struct in6_addr *mapped_in6 = NULL;
873 * XXX IPv4 mapped IPv6 addr consideraton,
874 * specified in rfc2373.
876 if (su->su_family == AF_INET6 &&
877 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
878 mapped_in6 = &su->su_sin6.sin6_addr;
881 hrp = thishost = firsthost; /* default */
884 while (hrp != NULL) {
885 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
886 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
891 /* XXX IPv4 mapped IPv6 addr consideraton */
892 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
893 (memcmp(&mapped_in6->s6_addr[12],
894 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
895 sizeof(struct in_addr)) == 0)) {
905 /* setup static variables as appropriate */
906 hostname = thishost->hostname;
907 ftpuser = thishost->anonuser;
912 * Helper function for sgetpwnam().
917 char *new = malloc(strlen(s) + 1);
920 reply(421, "Ran out of memory.");
929 * Save the result of a getpwnam. Used for USER command, since
930 * the data returned must not be clobbered by any other command
932 * NB: The data returned by sgetpwnam() will remain valid until
933 * the next call to this function. Its difference from getpwnam()
934 * is that sgetpwnam() is known to be called from ftpd code only.
936 static struct passwd *
937 sgetpwnam(char *name)
939 static struct passwd save;
942 if ((p = getpwnam(name)) == NULL)
946 free(save.pw_passwd);
952 save.pw_name = sgetsave(p->pw_name);
953 save.pw_passwd = sgetsave(p->pw_passwd);
954 save.pw_gecos = sgetsave(p->pw_gecos);
955 save.pw_dir = sgetsave(p->pw_dir);
956 save.pw_shell = sgetsave(p->pw_shell);
960 static int login_attempts; /* number of failed login attempts */
961 static int askpasswd; /* had user command, ask for passwd */
962 static char curname[MAXLOGNAME]; /* current USER name */
966 * Sets global passwd pointer pw if named account exists and is acceptable;
967 * sets askpasswd if a PASS command is expected. If logged in previously,
968 * need to reset state. If name is "ftp" or "anonymous", the name is not in
969 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
970 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
971 * requesting login privileges. Disallow anyone who does not have a standard
972 * shell as returned by getusershell(). Disallow anyone mentioned in the file
973 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
982 reply(530, "Can't change user from guest login.");
984 } else if (dochroot) {
985 reply(530, "Can't change user from chroot user.");
992 #ifdef VIRTUAL_HOSTING
993 pw = sgetpwnam(thishost->anonuser);
995 pw = sgetpwnam("ftp");
997 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
998 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL) ||
999 checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL))
1000 reply(530, "User %s access denied.", name);
1001 else if (pw != NULL) {
1005 "Guest login ok, send your email address as password.");
1007 reply(530, "User %s unknown.", name);
1008 if (!askpasswd && logging)
1010 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1013 if (anon_only != 0) {
1014 reply(530, "Sorry, only anonymous ftp allowed.");
1018 if ((pw = sgetpwnam(name))) {
1019 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1020 shell = _PATH_BSHELL;
1022 while ((cp = getusershell()) != NULL)
1023 if (strcmp(cp, shell) == 0)
1027 if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1, NULL)) {
1028 reply(530, "User %s access denied.", name);
1031 "FTP LOGIN REFUSED FROM %s, %s",
1038 strncpy(curname, name, sizeof(curname)-1);
1042 /* XXX Kluge! The conversation mechanism needs to be fixed. */
1044 if (opiechallenge(&opiedata, name, opieprompt) == 0) {
1045 pwok = (pw != NULL) &&
1046 opieaccessfile(remotehost) &&
1047 opiealways(pw->pw_dir);
1048 reply(331, "Response to %s %s for %s.",
1049 opieprompt, pwok ? "requested" : "required", name);
1052 reply(331, "Password required for %s.", name);
1056 * Delay before reading passwd after first failed
1057 * attempt to slow down passwd-guessing programs.
1060 sleep(login_attempts);
1064 * Check if a user is in the file "fname",
1065 * return a pointer to a malloc'd string with the rest
1066 * of the matching line in "residue" if not NULL.
1069 checkuser(char *fname, char *name, int pwset, char **residue)
1074 char *line, *mp, *p;
1076 if ((fd = fopen(fname, "r")) != NULL) {
1077 while (!found && (line = fgetln(fd, &len)) != NULL) {
1081 if (line[len - 1] == '\n') {
1082 line[len - 1] = '\0';
1085 if ((mp = malloc(len + 1)) == NULL)
1086 fatalerror("Ran out of memory.");
1087 memcpy(mp, line, len);
1091 /* avoid possible leading and trailing whitespace */
1092 p = strtok(line, " \t");
1093 /* skip empty lines */
1097 * if first chr is '@', check group membership
1103 if (p[1] == '\0') /* single @ matches anyone */
1106 if ((grp = getgrnam(p+1)) == NULL)
1109 * Check user's default group
1111 if (pwset && grp->gr_gid == pw->pw_gid)
1114 * Check supplementary groups
1116 while (!found && grp->gr_mem[i])
1117 found = strcmp(name,
1123 * Otherwise, just check for username match
1126 found = strcmp(p, name) == 0;
1128 * Save the rest of line to "residue" if matched
1130 if (found && residue) {
1131 if ((p = strtok(NULL, "")) != NULL)
1132 p += strspn(p, " \t");
1134 if ((*residue = strdup(p)) == NULL)
1135 fatalerror("Ran out of memory.");
1149 * Terminate login as previous user, if any, resetting state;
1150 * used when USER command is given or login fails.
1160 if (logged_in && dowtmp)
1161 ftpd_logwtmp(ttyline, "", NULL);
1164 /* XXX Missing LOGIN_SETMAC */
1165 setusercontext(NULL, getpwuid(0), 0,
1166 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1170 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1171 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1172 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1173 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1174 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1175 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1187 * the following code is stolen from imap-uw PAM authentication module and
1190 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1193 const char *uname; /* user name */
1194 const char *pass; /* password */
1196 typedef struct cred_t cred_t;
1199 auth_conv(int num_msg, const struct pam_message **msg,
1200 struct pam_response **resp, void *appdata)
1203 cred_t *cred = (cred_t *) appdata;
1204 struct pam_response *reply;
1206 reply = calloc(num_msg, sizeof *reply);
1210 for (i = 0; i < num_msg; i++) {
1211 switch (msg[i]->msg_style) {
1212 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1213 reply[i].resp_retcode = PAM_SUCCESS;
1214 reply[i].resp = COPY_STRING(cred->uname);
1215 /* PAM frees resp. */
1217 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1218 reply[i].resp_retcode = PAM_SUCCESS;
1219 reply[i].resp = COPY_STRING(cred->pass);
1220 /* PAM frees resp. */
1224 reply[i].resp_retcode = PAM_SUCCESS;
1225 reply[i].resp = NULL;
1227 default: /* unknown message style */
1229 return PAM_CONV_ERR;
1238 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1239 * authenticated, or 1 if not authenticated. If some sort of PAM system
1240 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1241 * function returns -1. This can be used as an indication that we should
1242 * fall back to a different authentication mechanism.
1245 auth_pam(struct passwd **ppw, const char *pass)
1247 const char *tmpl_user;
1251 cred_t auth_cred = { (*ppw)->pw_name, pass };
1252 struct pam_conv conv = { &auth_conv, &auth_cred };
1254 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1255 if (e != PAM_SUCCESS) {
1257 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1258 * if context creation has failed in the first place.
1260 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, 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));
1268 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1269 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1275 e = pam_authenticate(pamh, 0);
1279 * With PAM we support the concept of a "template"
1280 * user. The user enters a login name which is
1281 * authenticated by PAM, usually via a remote service
1282 * such as RADIUS or TACACS+. If authentication
1283 * succeeds, a different but related "template" name
1284 * is used for setting the credentials, shell, and
1285 * home directory. The name the user enters need only
1286 * exist on the remote authentication server, but the
1287 * template name must be present in the local password
1290 * This is supported by two various mechanisms in the
1291 * individual modules. However, from the application's
1292 * point of view, the template user is always passed
1293 * back as a changed value of the PAM_USER item.
1295 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1297 tmpl_user = (const char *) item;
1298 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1299 *ppw = getpwnam(tmpl_user);
1301 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1302 pam_strerror(pamh, e));
1307 case PAM_USER_UNKNOWN:
1313 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1319 e = pam_acct_mgmt(pamh, 0);
1320 if (e != PAM_SUCCESS) {
1321 syslog(LOG_ERR, "pam_acct_mgmt: %s",
1322 pam_strerror(pamh, e));
1328 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1329 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1336 #endif /* USE_PAM */
1344 login_cap_t *lc = NULL;
1349 char *residue = NULL;
1352 if (logged_in || askpasswd == 0) {
1353 reply(503, "Login with USER first.");
1357 if (!guest) { /* "ftp" is only account allowed no password */
1359 rval = 1; /* failure below */
1363 rval = auth_pam(&pw, passwd);
1369 if (opieverify(&opiedata, passwd) == 0)
1370 xpasswd = pw->pw_passwd;
1372 xpasswd = crypt(passwd, pw->pw_passwd);
1373 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1379 rval = strcmp(pw->pw_passwd, xpasswd);
1380 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1381 rval = 1; /* failure */
1384 * If rval == 1, the user failed the authentication check
1385 * above. If rval == 0, either PAM or local authentication
1389 reply(530, "Login incorrect.");
1392 "FTP LOGIN FAILED FROM %s",
1394 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1395 "FTP LOGIN FAILED FROM %s, %s",
1396 remotehost, curname);
1399 if (login_attempts++ >= 5) {
1401 "repeated login failures from %s",
1408 login_attempts = 0; /* this time successful */
1409 if (setegid(pw->pw_gid) < 0) {
1410 reply(550, "Can't set gid.");
1413 /* May be overridden by login.conf */
1416 if ((lc = login_getpwclass(pw)) != NULL) {
1417 char remote_ip[NI_MAXHOST];
1419 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1420 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1423 remote_ip[sizeof(remote_ip) - 1] = 0;
1424 if (!auth_hostok(lc, remotehost, remote_ip)) {
1425 syslog(LOG_INFO|LOG_AUTH,
1426 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1428 reply(530, "Permission denied.");
1432 if (!auth_timeok(lc, time(NULL))) {
1433 reply(530, "Login not available right now.");
1438 /* XXX Missing LOGIN_SETMAC */
1439 setusercontext(lc, pw, 0,
1440 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1441 LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1443 setlogin(pw->pw_name);
1444 initgroups(pw->pw_name, pw->pw_gid);
1449 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1450 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1451 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1452 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1457 /* open wtmp before chroot */
1459 ftpd_logwtmp(ttyline, pw->pw_name,
1460 (struct sockaddr *)&his_addr);
1463 if (guest && stats && statfd < 0)
1464 #ifdef VIRTUAL_HOSTING
1465 statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1467 statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1473 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue)
1474 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1475 || login_getcapbool(lc, "ftp-chroot", 0)
1480 * For a chrooted local user,
1481 * a) see whether ftpchroot(5) specifies a chroot directory,
1482 * b) extract the directory pathname from the line,
1483 * c) expand it to the absolute pathname if necessary.
1485 if (dochroot && residue &&
1486 (chrootdir = strtok(residue, " \t")) != NULL) {
1487 if (chrootdir[0] != '/')
1488 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1490 chrootdir = strdup(chrootdir); /* make it permanent */
1491 if (chrootdir == NULL)
1492 fatalerror("Ran out of memory.");
1494 if (guest || dochroot) {
1496 * If no chroot directory set yet, use the login directory.
1497 * Copy it so it can be modified while pw->pw_dir stays intact.
1499 if (chrootdir == NULL &&
1500 (chrootdir = strdup(pw->pw_dir)) == NULL)
1501 fatalerror("Ran out of memory.");
1503 * Check for the "/chroot/./home" syntax,
1504 * separate the chroot and home directory pathnames.
1506 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1507 *(homedir++) = '\0'; /* wipe '/' */
1508 homedir++; /* skip '.' */
1511 * We MUST do a chdir() after the chroot. Otherwise
1512 * the old current directory will be accessible as "."
1513 * outside the new root!
1518 * Finally, do chroot()
1520 if (chroot(chrootdir) < 0) {
1521 reply(550, "Can't change root.");
1524 } else /* real user w/o chroot */
1525 homedir = pw->pw_dir;
1527 * Set euid *before* doing chdir() so
1528 * a) the user won't be carried to a directory that he couldn't reach
1529 * on his own due to no permission to upper path components,
1530 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1531 * (uid 0 has no root power over NFS if not mapped explicitly.)
1533 if (seteuid(pw->pw_uid) < 0) {
1534 reply(550, "Can't set uid.");
1537 if (chdir(homedir) < 0) {
1538 if (guest || dochroot) {
1539 reply(550, "Can't change to base directory.");
1542 if (chdir("/") < 0) {
1543 reply(550, "Root is inaccessible.");
1546 lreply(230, "No directory! Logging in with home=/.");
1551 * Display a login message, if it exists.
1552 * N.B. reply(230,) must follow the message.
1554 #ifdef VIRTUAL_HOSTING
1555 fd = fopen(thishost->loginmsg, "r");
1557 fd = fopen(_PATH_FTPLOGINMESG, "r");
1560 char *cp, line[LINE_MAX];
1562 while (fgets(line, sizeof(line), fd) != NULL) {
1563 if ((cp = strchr(line, '\n')) != NULL)
1565 lreply(230, "%s", line);
1573 ident = strdup(passwd);
1575 fatalerror("Ran out of memory.");
1577 reply(230, "Guest login ok, access restrictions apply.");
1579 #ifdef VIRTUAL_HOSTING
1580 if (thishost != firsthost)
1581 snprintf(proctitle, sizeof(proctitle),
1582 "%s: anonymous(%s)/%s", remotehost, hostname,
1586 snprintf(proctitle, sizeof(proctitle),
1587 "%s: anonymous/%s", remotehost, passwd);
1588 setproctitle("%s", proctitle);
1589 #endif /* SETPROCTITLE */
1591 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1592 remotehost, passwd);
1595 reply(230, "User %s logged in, "
1596 "access restrictions apply.", pw->pw_name);
1598 reply(230, "User %s logged in.", pw->pw_name);
1601 snprintf(proctitle, sizeof(proctitle),
1602 "%s: user/%s", remotehost, pw->pw_name);
1603 setproctitle("%s", proctitle);
1604 #endif /* SETPROCTITLE */
1606 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1607 remotehost, pw->pw_name);
1609 if (logging && (guest || dochroot))
1610 syslog(LOG_INFO, "session root changed to %s", chrootdir);
1618 /* Forget all about it... */
1628 retrieve(char *cmd, char *name)
1632 int (*closefunc)(FILE *);
1636 fin = fopen(name, "r"), closefunc = fclose;
1641 snprintf(line, sizeof(line), cmd, name), name = line;
1642 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1644 st.st_blksize = BUFSIZ;
1648 perror_reply(550, name);
1650 LOGCMD("get", name);
1657 if (fstat(fileno(fin), &st) < 0) {
1658 perror_reply(550, name);
1661 if (!S_ISREG(st.st_mode)) {
1663 * Never sending a raw directory is a workaround
1664 * for buggy clients that will attempt to RETR
1665 * a directory before listing it, e.g., Mozilla.
1666 * Preventing a guest from getting irregular files
1667 * is a simple security measure.
1669 if (S_ISDIR(st.st_mode) || guest) {
1670 reply(550, "%s: not a plain file.", name);
1674 /* st.st_blksize is set for all descriptor types */
1677 if (restart_point) {
1678 if (type == TYPE_A) {
1685 if ((c=getc(fin)) == EOF) {
1686 perror_reply(550, name);
1692 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1693 perror_reply(550, name);
1697 dout = dataconn(name, st.st_size, "w");
1701 send_data(fin, dout, st.st_blksize, st.st_size,
1702 restart_point == 0 && cmd == NULL && S_ISREG(st.st_mode));
1703 if (cmd == NULL && guest && stats && byte_count > 0)
1704 logxfer(name, byte_count, start);
1710 LOGBYTES("get", name, byte_count);
1715 store(char *name, char *mode, int unique)
1719 int (*closefunc)(FILE *);
1721 if (*mode == 'a') { /* APPE */
1723 /* Programming error */
1724 syslog(LOG_ERR, "Internal: unique flag to APPE");
1727 if (guest && noguestmod) {
1728 reply(550, "Appending to existing file denied.");
1731 restart_point = 0; /* not affected by preceding REST */
1733 if (unique) /* STOU overrides REST */
1735 if (guest && noguestmod) {
1736 if (restart_point) { /* guest STOR w/REST */
1737 reply(550, "Modifying existing file denied.");
1739 } else /* treat guest STOR as STOU */
1744 mode = "r+"; /* so ASCII manual seek can work */
1746 if ((fd = guniquefd(name, &name)) < 0)
1748 fout = fdopen(fd, mode);
1750 fout = fopen(name, mode);
1753 perror_reply(553, name);
1757 if (restart_point) {
1758 if (type == TYPE_A) {
1765 if ((c=getc(fout)) == EOF) {
1766 perror_reply(550, name);
1773 * We must do this seek to "current" position
1774 * because we are changing from reading to
1777 if (fseeko(fout, 0, SEEK_CUR) < 0) {
1778 perror_reply(550, name);
1781 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1782 perror_reply(550, name);
1786 din = dataconn(name, -1, "r");
1789 if (receive_data(din, fout) == 0) {
1791 reply(226, "Transfer complete (unique file name:%s).",
1794 reply(226, "Transfer complete.");
1800 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1804 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1809 getdatasock(char *mode)
1811 int on = 1, s, t, tries;
1814 return (fdopen(data, mode));
1816 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1819 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1820 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1821 /* anchor socket to avoid multi-homing problems */
1822 data_source = ctrl_addr;
1823 data_source.su_port = htons(dataport);
1825 for (tries = 1; ; tries++) {
1827 * We should loop here since it's possible that
1828 * another ftpd instance has passed this point and is
1829 * trying to open a data connection in active mode now.
1830 * Until the other connection is opened, we'll be getting
1831 * EADDRINUSE because no SOCK_STREAM sockets in the system
1832 * can share both local and remote addresses, localIP:20
1833 * and *:* in this case.
1835 if (bind(s, (struct sockaddr *)&data_source,
1836 data_source.su_len) >= 0)
1838 if (errno != EADDRINUSE || tries > 10)
1842 seteuid(pw->pw_uid);
1844 if (data_source.su_family == AF_INET)
1846 on = IPTOS_THROUGHPUT;
1847 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1848 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1853 * Turn off push flag to keep sender TCP from sending short packets
1854 * at the boundaries of each write().
1857 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1858 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1860 return (fdopen(s, mode));
1862 /* Return the real value of errno (close may change it) */
1864 seteuid(pw->pw_uid);
1871 dataconn(char *name, off_t size, char *mode)
1875 int retry = 0, tos, conerrno;
1880 snprintf(sizebuf, sizeof(sizebuf),
1881 " (%jd bytes)", (intmax_t)size);
1885 union sockunion from;
1886 socklen_t fromlen = ctrl_addr.su_len;
1888 struct timeval timeout;
1892 FD_SET(pdata, &set);
1894 timeout.tv_usec = 0;
1895 timeout.tv_sec = 120;
1898 * Granted a socket is in the blocking I/O mode,
1899 * accept() will block after a successful select()
1900 * if the selected connection dies in between.
1901 * Therefore set the non-blocking I/O flag here.
1903 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1904 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1906 if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
1907 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1912 * Unset the inherited non-blocking I/O flag
1913 * on the child socket so stdio can work on it.
1915 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1916 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1919 if (from.su_family == AF_INET)
1921 tos = IPTOS_THROUGHPUT;
1922 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1923 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1926 reply(150, "Opening %s mode data connection for '%s'%s.",
1927 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1928 return (fdopen(pdata, mode));
1930 reply(425, "Can't open data connection.");
1936 reply(125, "Using existing data connection for '%s'%s.",
1939 return (fdopen(data, mode));
1942 data_dest = his_addr;
1945 file = getdatasock(mode);
1947 char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
1949 if (getnameinfo((struct sockaddr *)&data_source,
1951 hostbuf, sizeof(hostbuf) - 1,
1952 portbuf, sizeof(portbuf) - 1,
1953 NI_NUMERICHOST|NI_NUMERICSERV))
1954 *hostbuf = *portbuf = 0;
1955 hostbuf[sizeof(hostbuf) - 1] = 0;
1956 portbuf[sizeof(portbuf) - 1] = 0;
1957 reply(425, "Can't create data socket (%s,%s): %s.",
1958 hostbuf, portbuf, strerror(errno));
1961 data = fileno(file);
1963 if (connect(data, (struct sockaddr *)&data_dest,
1964 data_dest.su_len) == 0)
1969 if (conerrno == EADDRINUSE) {
1975 } while (retry <= swaitmax);
1976 if (conerrno != 0) {
1977 reply(425, "Can't build data connection: %s.",
1978 strerror(conerrno));
1981 reply(150, "Opening %s mode data connection for '%s'%s.",
1982 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1987 * A helper macro to avoid code duplication
1988 * in send_data() and receive_data().
1990 * XXX We have to block SIGURG during putc() because BSD stdio
1991 * is unable to restart interrupted write operations and hence
1992 * the entire buffer contents will be lost as soon as a write()
1993 * call indicates EINTR to stdio.
1995 #define FTPD_PUTC(ch, file, label) \
2001 ret = putc((ch), (file)); \
2003 CHECKOOB(return (-1)) \
2004 else if (ferror(file)) \
2007 } while (ret == EOF); \
2011 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
2012 * encapsulation of the data subject to Mode, Structure, and Type.
2014 * NB: Form isn't handled.
2017 send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2019 int c, cp, filefd, netfd;
2030 CHECKOOB(return (-1))
2031 else if (c == EOF && ferror(instr))
2034 if (ferror(instr)) { /* resume after OOB */
2038 if (feof(instr)) /* EOF */
2040 syslog(LOG_ERR, "Internal: impossible condition"
2041 " on file after getc()");
2044 if (c == '\n' && cp != '\r') {
2045 FTPD_PUTC('\r', outstr, data_err);
2048 FTPD_PUTC(c, outstr, data_err);
2052 #ifdef notyet /* BSD stdio isn't ready for that */
2053 while (fflush(outstr) == EOF) {
2054 CHECKOOB(return (-1))
2062 if (fflush(outstr) == EOF)
2065 reply(226, "Transfer complete.");
2071 * isreg is only set if we are not doing restart and we
2072 * are sending a regular file
2074 netfd = fileno(outstr);
2075 filefd = fileno(instr);
2078 char *msg = "Transfer complete.";
2084 while (filesize > 0) {
2085 err = sendfile(filefd, netfd, offset, 0,
2088 * Calculate byte_count before OOB processing.
2089 * It can be used in myoob() later.
2094 CHECKOOB(return (-1))
2095 else if (err == -1) {
2096 if (errno != EINTR &&
2097 cnt == 0 && offset == 0)
2101 if (err == -1) /* resume after OOB */
2104 * We hit the EOF prematurely.
2105 * Perhaps the file was externally truncated.
2108 msg = "Transfer finished due to "
2109 "premature end of file.";
2114 reply(226, "%s", msg);
2119 if ((buf = malloc(blksize)) == NULL) {
2121 reply(451, "Ran out of memory.");
2129 cnt = read(filefd, buf, blksize);
2130 CHECKOOB(free(buf); return (-1))
2135 if (cnt < 0) /* resume after OOB */
2137 if (cnt == 0) /* EOF */
2139 for (len = cnt, bp = buf; len > 0;) {
2140 cnt = write(netfd, bp, len);
2141 CHECKOOB(free(buf); return (-1))
2155 reply(226, "Transfer complete.");
2159 reply(550, "Unimplemented TYPE %d in send_data.", type);
2165 perror_reply(426, "Data connection");
2170 perror_reply(551, "Error on input file");
2175 * Transfer data from peer to "outstr" using the appropriate encapulation of
2176 * the data subject to Mode, Structure, and Type.
2178 * N.B.: Form isn't handled.
2181 receive_data(FILE *instr, FILE *outstr)
2197 cnt = read(fileno(instr), buf, sizeof(buf));
2198 CHECKOOB(return (-1))
2201 if (cnt < 0) /* resume after OOB */
2203 if (cnt == 0) /* EOF */
2205 for (len = cnt, bp = buf; len > 0;) {
2206 cnt = write(fileno(outstr), bp, len);
2207 CHECKOOB(return (-1))
2222 reply(553, "TYPE E not implemented.");
2229 CHECKOOB(return (-1))
2230 else if (c == EOF && ferror(instr))
2232 if (c == EOF && ferror(instr)) { /* resume after OOB */
2239 FTPD_PUTC('\r', outstr, file_err);
2249 /* Check for EOF here in order not to lose last \r. */
2251 if (feof(instr)) /* EOF */
2253 syslog(LOG_ERR, "Internal: impossible condition"
2254 " on data stream after getc()");
2259 FTPD_PUTC(c, outstr, file_err);
2262 #ifdef notyet /* BSD stdio isn't ready for that */
2263 while (fflush(outstr) == EOF) {
2264 CHECKOOB(return (-1))
2272 if (fflush(outstr) == EOF)
2277 "WARNING! %d bare linefeeds received in ASCII mode.",
2279 printf(" File may not have transferred correctly.\r\n");
2284 reply(550, "Unimplemented TYPE %d in receive_data.", type);
2290 perror_reply(426, "Data connection");
2295 perror_reply(452, "Error writing to file");
2300 statfilecmd(char *filename)
2305 char line[LINE_MAX];
2308 code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2309 snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2310 fin = ftpd_popen(line, "r");
2311 lreply(code, "Status of %s:", filename);
2313 while ((c = getc(fin)) != EOF) {
2315 if (ferror(stdout)){
2316 perror_reply(421, "Control connection");
2322 perror_reply(551, filename);
2329 * RFC 959 says neutral text should be prepended before
2330 * a leading 3-digit number followed by whitespace, but
2331 * many ftp clients can be confused by any leading digits,
2332 * as a matter of fact.
2334 if (atstart && isdigit(c))
2337 atstart = (c == '\n');
2340 reply(code, "End of status.");
2346 union sockunion *su;
2348 char hname[NI_MAXHOST];
2352 lreply(211, "%s FTP server status:", hostname);
2353 printf(" %s\r\n", version);
2355 lreply(211, "FTP server status:");
2356 printf(" Connected to %s", remotehost);
2357 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2358 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2359 hname[sizeof(hname) - 1] = 0;
2360 if (strcmp(hname, remotehost) != 0)
2361 printf(" (%s)", hname);
2366 printf(" Logged in anonymously\r\n");
2368 printf(" Logged in as %s\r\n", pw->pw_name);
2369 } else if (askpasswd)
2370 printf(" Waiting for password\r\n");
2372 printf(" Waiting for user name\r\n");
2373 printf(" TYPE: %s", typenames[type]);
2374 if (type == TYPE_A || type == TYPE_E)
2375 printf(", FORM: %s", formnames[form]);
2378 printf(" %d", CHAR_BIT);
2380 printf(" %d", bytesize); /* need definition! */
2382 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2383 strunames[stru], modenames[mode]);
2385 printf(" Data connection open\r\n");
2386 else if (pdata != -1) {
2390 } else if (usedefault == 0) {
2394 #define UC(b) (((int) b) & 0xff)
2396 printf(" EPSV only mode (EPSV ALL)\r\n");
2401 if (su->su_family == AF_INET) {
2402 a = (u_char *) &su->su_sin.sin_addr;
2403 p = (u_char *) &su->su_sin.sin_port;
2404 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2405 ispassive ? "PASV" : "PORT",
2406 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2407 UC(p[0]), UC(p[1]));
2414 switch (su->su_family) {
2416 a = (u_char *) &su->su_sin.sin_addr;
2417 p = (u_char *) &su->su_sin.sin_port;
2418 alen = sizeof(su->su_sin.sin_addr);
2422 a = (u_char *) &su->su_sin6.sin6_addr;
2423 p = (u_char *) &su->su_sin6.sin6_port;
2424 alen = sizeof(su->su_sin6.sin6_addr);
2432 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2434 for (i = 0; i < alen; i++)
2435 printf("%d,", UC(a[i]));
2436 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2445 switch (su->su_family) {
2457 union sockunion tmp;
2460 if (tmp.su_family == AF_INET6)
2461 tmp.su_sin6.sin6_scope_id = 0;
2462 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2463 hname, sizeof(hname) - 1, NULL, 0,
2465 hname[sizeof(hname) - 1] = 0;
2466 printf(" %s |%d|%s|%d|\r\n",
2467 ispassive ? "EPSV" : "EPRT",
2468 af, hname, htons(tmp.su_port));
2474 printf(" No data connection\r\n");
2475 reply(211, "End of status.");
2482 reply(451, "Error in server: %s", s);
2483 reply(221, "Closing connection due to server error.");
2489 reply(int n, const char *fmt, ...)
2500 syslog(LOG_DEBUG, "<--- %d ", n);
2502 vsyslog(LOG_DEBUG, fmt, ap);
2508 lreply(int n, const char *fmt, ...)
2519 syslog(LOG_DEBUG, "<--- %d- ", n);
2521 vsyslog(LOG_DEBUG, fmt, ap);
2530 reply(250, "%s command successful.", s);
2537 reply(502, "%s command not implemented.", s);
2546 if ((cp = strchr(cbuf,'\n')))
2548 reply(500, "%s: command not understood.", cbuf);
2556 LOGCMD("delete", name);
2557 if (lstat(name, &st) < 0) {
2558 perror_reply(550, name);
2561 if (S_ISDIR(st.st_mode)) {
2562 if (rmdir(name) < 0) {
2563 perror_reply(550, name);
2568 if (guest && noguestmod) {
2569 reply(550, "Operation not permitted.");
2572 if (unlink(name) < 0) {
2573 perror_reply(550, name);
2584 if (chdir(path) < 0)
2585 perror_reply(550, path);
2595 LOGCMD("mkdir", name);
2596 if (guest && noguestmkd)
2597 reply(550, "Operation not permitted.");
2598 else if (mkdir(name, 0777) < 0)
2599 perror_reply(550, name);
2601 if ((s = doublequote(name)) == NULL)
2602 fatalerror("Ran out of memory.");
2603 reply(257, "\"%s\" directory created.", s);
2609 removedir(char *name)
2612 LOGCMD("rmdir", name);
2613 if (rmdir(name) < 0)
2614 perror_reply(550, name);
2622 char *s, path[MAXPATHLEN + 1];
2624 if (getcwd(path, sizeof(path)) == NULL)
2625 perror_reply(550, "Get current directory");
2627 if ((s = doublequote(path)) == NULL)
2628 fatalerror("Ran out of memory.");
2629 reply(257, "\"%s\" is current directory.", s);
2635 renamefrom(char *name)
2639 if (guest && noguestmod) {
2640 reply(550, "Operation not permitted.");
2643 if (lstat(name, &st) < 0) {
2644 perror_reply(550, name);
2647 reply(350, "File exists, ready for destination name.");
2652 renamecmd(char *from, char *to)
2656 LOGCMD2("rename", from, to);
2658 if (guest && (stat(to, &st) == 0)) {
2659 reply(550, "%s: permission denied.", to);
2663 if (rename(from, to) < 0)
2664 perror_reply(550, "rename");
2670 dolog(struct sockaddr *who)
2672 char who_name[NI_MAXHOST];
2674 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2675 remotehost[sizeof(remotehost) - 1] = 0;
2676 if (getnameinfo(who, who->sa_len,
2677 who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
2679 who_name[sizeof(who_name) - 1] = 0;
2682 #ifdef VIRTUAL_HOSTING
2683 if (thishost != firsthost)
2684 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2685 remotehost, hostname);
2688 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2690 setproctitle("%s", proctitle);
2691 #endif /* SETPROCTITLE */
2694 #ifdef VIRTUAL_HOSTING
2695 if (thishost != firsthost)
2696 syslog(LOG_INFO, "connection from %s (%s) to %s",
2697 remotehost, who_name, hostname);
2700 syslog(LOG_INFO, "connection from %s (%s)",
2701 remotehost, who_name);
2706 * Record logout in wtmp file
2707 * and exit with supplied status.
2710 dologout(int status)
2713 if (logged_in && dowtmp) {
2715 ftpd_logwtmp(ttyline, "", NULL);
2717 /* beware of flushing buffers after a SIGPIPE */
2735 syslog(LOG_ERR, "Internal: maskurg() while no transfer");
2740 sigaddset(&sset, SIGURG);
2741 sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
2751 syslog(LOG_ERR, "Internal: flagxfer(1): "
2752 "transfer already under way");
2758 syslog(LOG_ERR, "Internal: flagxfer(0): "
2759 "no active transfer");
2766 * Returns 0 if OK to resume or -1 if abort requested.
2775 syslog(LOG_ERR, "Internal: myoob() while no transfer");
2779 ret = get_line(cp, 7, stdin);
2781 reply(221, "You could at least say goodbye.");
2783 } else if (ret == -2) {
2784 /* Ignore truncated command. */
2788 if (strcmp(cp, "ABOR\r\n") == 0) {
2790 reply(426, "Transfer aborted. Data connection closed.");
2791 reply(226, "Abort successful.");
2794 if (strcmp(cp, "STAT\r\n") == 0) {
2796 if (file_size != -1)
2797 reply(213, "Status: %jd of %jd bytes transferred.",
2798 (intmax_t)byte_count, (intmax_t)file_size);
2800 reply(213, "Status: %jd bytes transferred.",
2801 (intmax_t)byte_count);
2807 * Note: a response of 425 is not mentioned as a possible response to
2808 * the PASV command in RFC959. However, it has been blessed as
2809 * a legitimate response by Jon Postel in a telephone conversation
2810 * with Rick Adams on 25 Jan 89.
2819 if (pdata >= 0) /* close old port if one set */
2822 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2824 perror_reply(425, "Can't open passive connection");
2828 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2829 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2834 if (ctrl_addr.su_family == AF_INET) {
2835 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2836 : IP_PORTRANGE_DEFAULT;
2838 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2839 &on, sizeof(on)) < 0)
2843 #ifdef IPV6_PORTRANGE
2844 if (ctrl_addr.su_family == AF_INET6) {
2845 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2846 : IPV6_PORTRANGE_DEFAULT;
2848 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2849 &on, sizeof(on)) < 0)
2854 pasv_addr = ctrl_addr;
2855 pasv_addr.su_port = 0;
2856 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2859 seteuid(pw->pw_uid);
2861 len = sizeof(pasv_addr);
2862 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2864 if (listen(pdata, 1) < 0)
2866 if (pasv_addr.su_family == AF_INET)
2867 a = (char *) &pasv_addr.su_sin.sin_addr;
2868 else if (pasv_addr.su_family == AF_INET6 &&
2869 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2870 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2874 p = (char *) &pasv_addr.su_port;
2876 #define UC(b) (((int) b) & 0xff)
2878 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2879 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2883 seteuid(pw->pw_uid);
2886 perror_reply(425, "Can't open passive connection");
2891 * Long Passive defined in RFC 1639.
2892 * 228 Entering Long Passive Mode
2893 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2897 long_passive(char *cmd, int pf)
2903 if (pdata >= 0) /* close old port if one set */
2906 if (pf != PF_UNSPEC) {
2907 if (ctrl_addr.su_family != pf) {
2908 switch (ctrl_addr.su_family) {
2921 * only EPRT/EPSV ready clients will understand this
2923 if (strcmp(cmd, "EPSV") == 0 && pf) {
2924 reply(522, "Network protocol mismatch, "
2927 reply(501, "Network protocol mismatch."); /*XXX*/
2933 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2935 perror_reply(425, "Can't open passive connection");
2939 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2940 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2944 pasv_addr = ctrl_addr;
2945 pasv_addr.su_port = 0;
2946 len = pasv_addr.su_len;
2949 if (ctrl_addr.su_family == AF_INET) {
2950 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2951 : IP_PORTRANGE_DEFAULT;
2953 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2954 &on, sizeof(on)) < 0)
2958 #ifdef IPV6_PORTRANGE
2959 if (ctrl_addr.su_family == AF_INET6) {
2960 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2961 : IPV6_PORTRANGE_DEFAULT;
2963 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2964 &on, sizeof(on)) < 0)
2969 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2972 seteuid(pw->pw_uid);
2974 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2976 if (listen(pdata, 1) < 0)
2979 #define UC(b) (((int) b) & 0xff)
2981 if (strcmp(cmd, "LPSV") == 0) {
2982 p = (char *)&pasv_addr.su_port;
2983 switch (pasv_addr.su_family) {
2985 a = (char *) &pasv_addr.su_sin.sin_addr;
2988 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2989 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2990 2, UC(p[0]), UC(p[1]));
2993 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
2994 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2997 a = (char *) &pasv_addr.su_sin6.sin6_addr;
2999 "Entering Long Passive Mode "
3000 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3001 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3002 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3003 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3004 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3005 2, UC(p[0]), UC(p[1]));
3008 } else if (strcmp(cmd, "EPSV") == 0) {
3009 switch (pasv_addr.su_family) {
3012 reply(229, "Entering Extended Passive Mode (|||%d|)",
3013 ntohs(pasv_addr.su_port));
3017 /* more proper error code? */
3021 seteuid(pw->pw_uid);
3024 perror_reply(425, "Can't open passive connection");
3029 * Generate unique name for file with basename "local"
3030 * and open the file in order to avoid possible races.
3031 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3032 * Return descriptor to the file, set "name" to its name.
3034 * Generates failure reply on error.
3037 guniquefd(char *local, char **name)
3039 static char new[MAXPATHLEN];
3045 cp = strrchr(local, '/');
3048 if (stat(cp ? local : ".", &st) < 0) {
3049 perror_reply(553, cp ? local : ".");
3054 * Let not overwrite dirname with counter suffix.
3056 * In this extreme case dot won't be put in front of suffix.
3058 if (strlen(local) > sizeof(new) - 4) {
3059 reply(553, "Pathname too long.");
3064 /* -4 is for the .nn<null> we put on the end below */
3065 snprintf(new, sizeof(new) - 4, "%s", local);
3066 cp = new + strlen(new);
3068 * Don't generate dotfile unless requested explicitly.
3069 * This covers the case when basename gets truncated off
3072 if (cp > new && cp[-1] != '/')
3074 for (count = 0; count < 100; count++) {
3075 /* At count 0 try unmodified name */
3077 sprintf(cp, "%d", count);
3078 if ((fd = open(count ? new : local,
3079 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3080 *name = count ? new : local;
3083 if (errno != EEXIST) {
3084 perror_reply(553, count ? new : local);
3088 reply(452, "Unique file name cannot be created.");
3093 * Format and send reply containing system error number.
3096 perror_reply(int code, char *string)
3099 reply(code, "%s: %s.", string, strerror(errno));
3102 static char *onefile[] = {
3108 send_file_list(char *whichf)
3114 char **dirlist, *dirname;
3119 if (strpbrk(whichf, "~{[*?") != NULL) {
3120 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3122 memset(&gl, 0, sizeof(gl));
3123 gl.gl_matchc = MAXGLOBARGS;
3124 /*flags |= GLOB_LIMIT;*/
3126 if (glob(whichf, flags, 0, &gl)) {
3127 reply(550, "No matching files found.");
3129 } else if (gl.gl_pathc == 0) {
3131 perror_reply(550, whichf);
3134 dirlist = gl.gl_pathv;
3136 onefile[0] = whichf;
3141 while ((dirname = *dirlist++)) {
3142 if (stat(dirname, &st) < 0) {
3144 * If user typed "ls -l", etc, and the client
3145 * used NLST, do what the user meant.
3147 if (dirname[0] == '-' && *dirlist == NULL &&
3149 retrieve(_PATH_LS " %s", dirname);
3151 perror_reply(550, whichf);
3155 if (S_ISREG(st.st_mode)) {
3157 dout = dataconn("file list", -1, "w");
3163 fprintf(dout, "%s%s\n", dirname,
3164 type == TYPE_A ? "\r" : "");
3168 byte_count += strlen(dirname) +
3169 (type == TYPE_A ? 2 : 1);
3170 CHECKOOB(goto abrt);
3172 } else if (!S_ISDIR(st.st_mode))
3175 if ((dirp = opendir(dirname)) == NULL)
3178 while ((dir = readdir(dirp)) != NULL) {
3179 char nbuf[MAXPATHLEN];
3181 CHECKOOB(goto abrt);
3183 if (strcmp(dir->d_name, ".") == 0)
3185 if (strcmp(dir->d_name, "..") == 0)
3188 snprintf(nbuf, sizeof(nbuf),
3189 "%s/%s", dirname, dir->d_name);
3192 * We have to do a stat to insure it's
3193 * not a directory or special file.
3195 if (simple || (stat(nbuf, &st) == 0 &&
3196 S_ISREG(st.st_mode))) {
3198 dout = dataconn("file list", -1, "w");
3204 if (nbuf[0] == '.' && nbuf[1] == '/')
3205 fprintf(dout, "%s%s\n", &nbuf[2],
3206 type == TYPE_A ? "\r" : "");
3208 fprintf(dout, "%s%s\n", nbuf,
3209 type == TYPE_A ? "\r" : "");
3213 byte_count += strlen(nbuf) +
3214 (type == TYPE_A ? 2 : 1);
3215 CHECKOOB(goto abrt);
3223 reply(550, "No files found.");
3224 else if (ferror(dout))
3225 data_err: perror_reply(550, "Data connection");
3227 reply(226, "Transfer complete.");
3245 reapchild(int signo)
3247 while (waitpid(-1, NULL, WNOHANG) > 0);
3251 appendf(char **strp, char *fmt, ...)
3257 vasprintf(&p, fmt, ap);
3260 fatalerror("Ran out of memory.");
3265 asprintf(strp, "%s%s", ostr, p);
3267 fatalerror("Ran out of memory.");
3273 logcmd(char *cmd, char *file1, char *file2, off_t cnt)
3276 char wd[MAXPATHLEN + 1];
3281 if (getcwd(wd, sizeof(wd) - 1) == NULL)
3282 strcpy(wd, strerror(errno));
3284 appendf(&msg, "%s", cmd);
3286 appendf(&msg, " %s", file1);
3288 appendf(&msg, " %s", file2);
3290 appendf(&msg, " = %jd bytes", (intmax_t)cnt);
3291 appendf(&msg, " (wd: %s", wd);
3292 if (guest || dochroot)
3293 appendf(&msg, "; chrooted");
3295 syslog(LOG_INFO, "%s", msg);
3300 logxfer(char *name, off_t size, time_t start)
3302 char buf[MAXPATHLEN + 1024];
3303 char path[MAXPATHLEN + 1];
3308 if (realpath(name, path) == NULL) {
3309 syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
3312 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n",
3313 ctime(&now)+4, ident, remotehost,
3314 path, (intmax_t)size,
3315 (long)(now - start + (now == start)));
3316 write(statfd, buf, strlen(buf));
3321 doublequote(char *s)
3326 for (p = s, n = 0; *p; p++)
3330 if ((s2 = malloc(p - s + n + 1)) == NULL)
3333 for (p = s2; *s; s++, p++) {
3334 if ((*p = *s) == '"')
3342 /* setup server socket for specified address family */
3343 /* if af is PF_UNSPEC more than one socket may be returned */
3344 /* the returned list is dynamically allocated, so caller needs to free it */
3346 socksetup(int af, char *bindname, const char *bindport)
3348 struct addrinfo hints, *res, *r;
3349 int error, maxs, *s, *socks;
3352 memset(&hints, 0, sizeof(hints));
3353 hints.ai_flags = AI_PASSIVE;
3354 hints.ai_family = af;
3355 hints.ai_socktype = SOCK_STREAM;
3356 error = getaddrinfo(bindname, bindport, &hints, &res);
3358 syslog(LOG_ERR, "%s", gai_strerror(error));
3359 if (error == EAI_SYSTEM)
3360 syslog(LOG_ERR, "%s", strerror(errno));
3364 /* Count max number of sockets we may open */
3365 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3367 socks = malloc((maxs + 1) * sizeof(int));
3370 syslog(LOG_ERR, "couldn't allocate memory for sockets");
3374 *socks = 0; /* num of sockets counter at start of array */
3376 for (r = res; r; r = r->ai_next) {
3377 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3379 syslog(LOG_DEBUG, "control socket: %m");
3382 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3383 &on, sizeof(on)) < 0)
3385 "control setsockopt (SO_REUSEADDR): %m");
3386 if (r->ai_family == AF_INET6) {
3387 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3388 &on, sizeof(on)) < 0)
3390 "control setsockopt (IPV6_V6ONLY): %m");
3392 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3393 syslog(LOG_DEBUG, "control bind: %m");
3405 syslog(LOG_ERR, "control socket: Couldn't bind to any socket");