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>
74 #include <login_cap.h>
78 #include <security/pam_appl.h>
81 #include "pathnames.h"
86 static char version[] = "Version 6.00LS";
89 extern off_t restart_point;
92 union sockunion ctrl_addr;
93 union sockunion data_source;
94 union sockunion data_dest;
95 union sockunion his_addr;
96 union sockunion pasv_addr;
101 int hostinfo = 1; /* print host-specific info in messages */
106 int timeout = 900; /* timeout after 15 minutes of inactivity */
107 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
109 int restricted_data_ports = 1;
110 int paranoid = 1; /* be extra careful about security */
111 int anon_only = 0; /* Only anonymous ftp allowed */
112 int assumeutf8 = 0; /* Assume that server file names are in UTF-8 */
121 int stru; /* avoid C keyword */
123 int usedefault = 1; /* for data transfers */
124 int pdata = -1; /* for passive mode */
125 int readonly = 0; /* Server is in readonly mode. */
126 int noepsv = 0; /* EPSV command is disabled. */
127 int noretr = 0; /* RETR command is disabled. */
128 int noguestretr = 0; /* RETR command is disabled for anon users. */
129 int noguestmkd = 0; /* MKD command is disabled for anon users. */
130 int noguestmod = 1; /* anon users may not modify existing files. */
134 #if !defined(CMASK) || CMASK == 0
138 int defumask = CMASK; /* default umask value */
143 #ifdef VIRTUAL_HOSTING
146 static struct ftphost {
147 struct ftphost *next;
148 struct addrinfo *hostinfo;
154 } *thishost, *firsthost;
157 char remotehost[NI_MAXHOST];
160 static char ttyline[20];
161 char *tty = ttyline; /* for klogin */
164 static int auth_pam(struct passwd**, const char*);
165 pam_handle_t *pamh = NULL;
170 char *pid_file = NULL; /* means default location to pidfile(3) */
173 * Limit number of pathnames that glob can return.
174 * A limit of 0 indicates the number of pathnames is unlimited.
176 #define MAXGLOBARGS 16384
179 * Timeout intervals for retrying connections
180 * to hosts that don't accept PORT cmds. This
181 * is a kludge, but given the problems with TCP...
183 #define SWAITMAX 90 /* wait at most 90 seconds */
184 #define SWAITINT 5 /* interval between retries */
186 int swaitmax = SWAITMAX;
187 int swaitint = SWAITINT;
190 char proctitle[LINE_MAX]; /* initial part of title */
191 #endif /* SETPROCTITLE */
193 #define LOGCMD(cmd, file) logcmd((cmd), (file), NULL, -1)
194 #define LOGCMD2(cmd, file1, file2) logcmd((cmd), (file1), (file2), -1)
195 #define LOGBYTES(cmd, file, cnt) logcmd((cmd), (file), NULL, (cnt))
197 static volatile sig_atomic_t recvurg;
198 static int transflag; /* NB: for debugging only */
200 #define STARTXFER flagxfer(1)
201 #define ENDXFER flagxfer(0)
203 #define START_UNSAFE maskurg(1)
204 #define END_UNSAFE maskurg(0)
206 /* It's OK to put an `else' clause after this macro. */
207 #define CHECKOOB(action) \
216 #ifdef VIRTUAL_HOSTING
217 static void inithosts(int);
218 static void selecthost(union sockunion *);
220 static void ack(char *);
221 static void sigurg(int);
222 static void maskurg(int);
223 static void flagxfer(int);
224 static int myoob(void);
225 static int checkuser(char *, char *, int, char **);
226 static FILE *dataconn(char *, off_t, char *);
227 static void dolog(struct sockaddr *);
228 static void end_login(void);
229 static FILE *getdatasock(char *);
230 static int guniquefd(char *, char **);
231 static void lostconn(int);
232 static void sigquit(int);
233 static int receive_data(FILE *, FILE *);
234 static int send_data(FILE *, FILE *, size_t, off_t, int);
235 static struct passwd *
237 static char *sgetsave(char *);
238 static void reapchild(int);
239 static void appendf(char **, char *, ...) __printflike(2, 3);
240 static void logcmd(char *, char *, char *, off_t);
241 static void logxfer(char *, off_t, time_t);
242 static char *doublequote(char *);
243 static int *socksetup(int, char *, const char *);
246 main(int argc, char *argv[])
250 char *cp, line[LINE_MAX];
252 char *bindname = NULL;
253 const char *bindport = "ftp";
254 int family = AF_UNSPEC;
257 tzset(); /* in case no timezone database in ~ftp */
258 sigemptyset(&sa.sa_mask);
259 sa.sa_flags = SA_RESTART;
262 * Prevent diagnostic messages from appearing on stderr.
263 * We run as a daemon or from inetd; in both cases, there's
264 * more reason in logging to syslog.
266 freopen(_PATH_DEVNULL, "w", stderr);
270 * LOG_NDELAY sets up the logging connection immediately,
271 * necessary for anonymous ftp's that chroot and can't do it later.
273 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
275 while ((ch = getopt(argc, argv,
276 "468a:AdDEH:hlmMoOp:P:rRSt:T:u:UvW")) != -1) {
279 family = (family == AF_INET6) ? AF_UNSPEC : AF_INET;
283 family = (family == AF_INET) ? AF_UNSPEC : AF_INET6;
319 logging++; /* > 1 == extra logging */
359 timeout = atoi(optarg);
360 if (maxtimeout < timeout)
361 maxtimeout = timeout;
365 maxtimeout = atoi(optarg);
366 if (timeout > maxtimeout)
367 timeout = maxtimeout;
374 val = strtol(optarg, &optarg, 8);
375 if (*optarg != '\0' || val < 0)
376 syslog(LOG_WARNING, "bad value for -u");
382 restricted_data_ports = 0;
394 syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
400 int *ctl_sock, fd, maxfd = -1, nfds, i;
401 fd_set defreadfds, readfds;
405 if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
406 if (errno == EEXIST) {
407 syslog(LOG_ERR, "%s already running, pid %d",
408 getprogname(), (int)pid);
411 syslog(LOG_WARNING, "pidfile_open: %m");
415 * Detach from parent.
417 if (daemon(1, 1) < 0) {
418 syslog(LOG_ERR, "failed to become a daemon");
422 if (pfh != NULL && pidfile_write(pfh) == -1)
423 syslog(LOG_WARNING, "pidfile_write: %m");
425 sa.sa_handler = reapchild;
426 sigaction(SIGCHLD, &sa, NULL);
428 #ifdef VIRTUAL_HOSTING
433 * Open a socket, bind it to the FTP port, and start
436 ctl_sock = socksetup(family, bindname, bindport);
437 if (ctl_sock == NULL)
440 FD_ZERO(&defreadfds);
441 for (i = 1; i <= *ctl_sock; i++) {
442 FD_SET(ctl_sock[i], &defreadfds);
443 if (listen(ctl_sock[i], 32) < 0) {
444 syslog(LOG_ERR, "control listen: %m");
447 if (maxfd < ctl_sock[i])
452 * Loop forever accepting connection requests and forking off
453 * children to handle them.
456 FD_COPY(&defreadfds, &readfds);
457 nfds = select(maxfd + 1, &readfds, NULL, NULL, 0);
459 if (nfds < 0 && errno != EINTR)
460 syslog(LOG_WARNING, "select: %m");
465 for (i = 1; i <= *ctl_sock; i++)
466 if (FD_ISSET(ctl_sock[i], &readfds)) {
467 addrlen = sizeof(his_addr);
468 fd = accept(ctl_sock[i],
469 (struct sockaddr *)&his_addr,
476 switch (pid = fork()) {
482 for (i = 1; i <= *ctl_sock; i++)
488 syslog(LOG_WARNING, "fork: %m");
496 addrlen = sizeof(his_addr);
497 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
498 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
502 #ifdef VIRTUAL_HOSTING
503 if (his_addr.su_family == AF_INET6 &&
504 IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))
507 family = his_addr.su_family;
513 sa.sa_handler = SIG_DFL;
514 sigaction(SIGCHLD, &sa, NULL);
516 sa.sa_handler = sigurg;
517 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
518 sigaction(SIGURG, &sa, NULL);
520 sigfillset(&sa.sa_mask); /* block all signals in handler */
521 sa.sa_flags = SA_RESTART;
522 sa.sa_handler = sigquit;
523 sigaction(SIGHUP, &sa, NULL);
524 sigaction(SIGINT, &sa, NULL);
525 sigaction(SIGQUIT, &sa, NULL);
526 sigaction(SIGTERM, &sa, NULL);
528 sa.sa_handler = lostconn;
529 sigaction(SIGPIPE, &sa, NULL);
531 addrlen = sizeof(ctrl_addr);
532 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
533 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
536 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
537 #ifdef VIRTUAL_HOSTING
538 /* select our identity from virtual host table */
539 selecthost(&ctrl_addr);
542 if (ctrl_addr.su_family == AF_INET)
544 tos = IPTOS_LOWDELAY;
545 if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
546 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
550 * Disable Nagle on the control channel so that we don't have to wait
551 * for peer's ACK before issuing our next reply.
553 if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
554 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
556 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
558 /* set this here so klogin can use it... */
559 snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
561 /* Try to handle urgent data inline */
563 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
564 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
568 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
569 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
571 dolog((struct sockaddr *)&his_addr);
573 * Set up default state
582 /* If logins are disabled, print out the message. */
583 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
584 while (fgets(line, sizeof(line), fd) != NULL) {
585 if ((cp = strchr(line, '\n')) != NULL)
587 lreply(530, "%s", line);
591 reply(530, "System not available.");
594 #ifdef VIRTUAL_HOSTING
595 fd = fopen(thishost->welcome, "r");
597 fd = fopen(_PATH_FTPWELCOME, "r");
600 while (fgets(line, sizeof(line), fd) != NULL) {
601 if ((cp = strchr(line, '\n')) != NULL)
603 lreply(220, "%s", line);
607 /* reply(220,) must follow */
609 #ifndef VIRTUAL_HOSTING
610 if (hostname == NULL) {
611 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
612 fatalerror("Ran out of memory.");
613 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
615 hostname[MAXHOSTNAMELEN - 1] = '\0';
619 reply(220, "%s FTP server (%s) ready.", hostname, version);
621 reply(220, "FTP server ready.");
632 syslog(LOG_DEBUG, "lost connection");
640 syslog(LOG_ERR, "got signal %d", signo);
644 #ifdef VIRTUAL_HOSTING
646 * read in virtual host tables (if they exist)
650 inithosts(int family)
655 char *cp, *mp, *line;
656 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
657 struct ftphost *hrp, *lhrp;
658 struct addrinfo hints, *res, *ai;
661 * Fill in the default host information
663 if (hostname == NULL) {
664 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
665 fatalerror("Ran out of memory.");
666 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
668 hostname[MAXHOSTNAMELEN - 1] = '\0';
670 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
671 fatalerror("Ran out of memory.");
672 hrp->hostname = hostname;
673 hrp->hostinfo = NULL;
675 memset(&hints, 0, sizeof(hints));
676 hints.ai_flags = AI_PASSIVE;
677 hints.ai_family = family;
678 hints.ai_socktype = SOCK_STREAM;
679 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
681 hrp->statfile = _PATH_FTPDSTATFILE;
682 hrp->welcome = _PATH_FTPWELCOME;
683 hrp->loginmsg = _PATH_FTPLOGINMESG;
684 hrp->anonuser = "ftp";
686 thishost = firsthost = lhrp = hrp;
687 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
688 int addrsize, gothost;
692 while ((line = fgetln(fp, &len)) != NULL) {
698 if (line[len - 1] == '\n') {
699 line[len - 1] = '\0';
702 if ((mp = malloc(len + 1)) == NULL)
703 fatalerror("Ran out of memory.");
704 memcpy(mp, line, len);
708 cp = strtok(line, " \t");
709 /* skip empty lines */
716 statfile = _PATH_FTPDSTATFILE;
717 welcome = _PATH_FTPWELCOME;
718 loginmsg = _PATH_FTPLOGINMESG;
721 * Preparse the line so we can use its info
722 * for all the addresses associated with
723 * the virtual host name.
724 * Field 0, the virtual host name, is special:
725 * it's already parsed off and will be strdup'ed
726 * later, after we know its canonical form.
728 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
729 if (*cp != '-' && (cp = strdup(cp)))
731 case 1: /* anon user permissions */
734 case 2: /* statistics file */
737 case 3: /* welcome message */
740 case 4: /* login message */
743 default: /* programming error */
748 hints.ai_flags = AI_PASSIVE;
749 hints.ai_family = family;
750 hints.ai_socktype = SOCK_STREAM;
751 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
753 for (ai = res; ai != NULL && ai->ai_addr != NULL;
757 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
760 for (hi = hrp->hostinfo; hi != NULL;
762 if (hi->ai_addrlen == ai->ai_addrlen &&
765 ai->ai_addr->sa_len) == 0) {
773 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
775 hrp->hostname = NULL;
778 if (hrp->hostinfo && hrp->hostinfo != res)
779 freeaddrinfo(hrp->hostinfo);
780 insert = 0; /* host already in the chain */
785 * determine hostname to use.
786 * force defined name if there is a valid alias
787 * otherwise fallback to primary hostname
789 /* XXX: getaddrinfo() can't do alias check */
790 switch(hrp->hostinfo->ai_family) {
792 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
793 addrsize = sizeof(struct in_addr);
796 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
797 addrsize = sizeof(struct in6_addr);
800 /* should not reach here */
801 freeaddrinfo(hrp->hostinfo);
803 free(hrp); /*not in chain, can free*/
805 hrp->hostinfo = NULL; /*mark as blank*/
809 if ((hp = getipnodebyaddr(addr, addrsize,
810 hrp->hostinfo->ai_family,
811 &hp_error)) != NULL) {
812 if (strcmp(vhost, hp->h_name) != 0) {
813 if (hp->h_aliases == NULL)
817 while (hp->h_aliases[i] &&
818 strcmp(vhost, hp->h_aliases[i]) != 0)
820 if (hp->h_aliases[i] == NULL)
826 strcmp(hrp->hostname, vhost) != 0) {
828 hrp->hostname = NULL;
830 if (hrp->hostname == NULL &&
831 (hrp->hostname = strdup(vhost)) == NULL) {
832 freeaddrinfo(hrp->hostinfo);
833 hrp->hostinfo = NULL; /* mark as blank */
838 hrp->anonuser = anonuser;
839 hrp->statfile = statfile;
840 hrp->welcome = welcome;
841 hrp->loginmsg = loginmsg;
859 selecthost(union sockunion *su)
864 struct in6_addr *mapped_in6 = NULL;
870 * XXX IPv4 mapped IPv6 addr consideraton,
871 * specified in rfc2373.
873 if (su->su_family == AF_INET6 &&
874 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
875 mapped_in6 = &su->su_sin6.sin6_addr;
878 hrp = thishost = firsthost; /* default */
881 while (hrp != NULL) {
882 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
883 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
888 /* XXX IPv4 mapped IPv6 addr consideraton */
889 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
890 (memcmp(&mapped_in6->s6_addr[12],
891 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
892 sizeof(struct in_addr)) == 0)) {
902 /* setup static variables as appropriate */
903 hostname = thishost->hostname;
904 ftpuser = thishost->anonuser;
909 * Helper function for sgetpwnam().
914 char *new = malloc(strlen(s) + 1);
917 reply(421, "Ran out of memory.");
926 * Save the result of a getpwnam. Used for USER command, since
927 * the data returned must not be clobbered by any other command
929 * NB: The data returned by sgetpwnam() will remain valid until
930 * the next call to this function. Its difference from getpwnam()
931 * is that sgetpwnam() is known to be called from ftpd code only.
933 static struct passwd *
934 sgetpwnam(char *name)
936 static struct passwd save;
939 if ((p = getpwnam(name)) == NULL)
943 free(save.pw_passwd);
949 save.pw_name = sgetsave(p->pw_name);
950 save.pw_passwd = sgetsave(p->pw_passwd);
951 save.pw_gecos = sgetsave(p->pw_gecos);
952 save.pw_dir = sgetsave(p->pw_dir);
953 save.pw_shell = sgetsave(p->pw_shell);
957 static int login_attempts; /* number of failed login attempts */
958 static int askpasswd; /* had user command, ask for passwd */
959 static char curname[MAXLOGNAME]; /* current USER name */
963 * Sets global passwd pointer pw if named account exists and is acceptable;
964 * sets askpasswd if a PASS command is expected. If logged in previously,
965 * need to reset state. If name is "ftp" or "anonymous", the name is not in
966 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
967 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
968 * requesting login privileges. Disallow anyone who does not have a standard
969 * shell as returned by getusershell(). Disallow anyone mentioned in the file
970 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
979 reply(530, "Can't change user from guest login.");
981 } else if (dochroot) {
982 reply(530, "Can't change user from chroot user.");
989 #ifdef VIRTUAL_HOSTING
990 pw = sgetpwnam(thishost->anonuser);
992 pw = sgetpwnam("ftp");
994 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
995 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL) ||
996 checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL))
997 reply(530, "User %s access denied.", name);
998 else if (pw != NULL) {
1002 "Guest login ok, send your email address as password.");
1004 reply(530, "User %s unknown.", name);
1005 if (!askpasswd && logging)
1007 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1010 if (anon_only != 0) {
1011 reply(530, "Sorry, only anonymous ftp allowed.");
1015 if ((pw = sgetpwnam(name))) {
1016 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1017 shell = _PATH_BSHELL;
1019 while ((cp = getusershell()) != NULL)
1020 if (strcmp(cp, shell) == 0)
1024 if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1, NULL)) {
1025 reply(530, "User %s access denied.", name);
1028 "FTP LOGIN REFUSED FROM %s, %s",
1035 strncpy(curname, name, sizeof(curname)-1);
1038 reply(331, "Password required for %s.", name);
1041 * Delay before reading passwd after first failed
1042 * attempt to slow down passwd-guessing programs.
1045 sleep(login_attempts);
1049 * Check if a user is in the file "fname",
1050 * return a pointer to a malloc'd string with the rest
1051 * of the matching line in "residue" if not NULL.
1054 checkuser(char *fname, char *name, int pwset, char **residue)
1059 char *line, *mp, *p;
1061 if ((fd = fopen(fname, "r")) != NULL) {
1062 while (!found && (line = fgetln(fd, &len)) != NULL) {
1066 if (line[len - 1] == '\n') {
1067 line[len - 1] = '\0';
1070 if ((mp = malloc(len + 1)) == NULL)
1071 fatalerror("Ran out of memory.");
1072 memcpy(mp, line, len);
1076 /* avoid possible leading and trailing whitespace */
1077 p = strtok(line, " \t");
1078 /* skip empty lines */
1082 * if first chr is '@', check group membership
1088 if (p[1] == '\0') /* single @ matches anyone */
1091 if ((grp = getgrnam(p+1)) == NULL)
1094 * Check user's default group
1096 if (pwset && grp->gr_gid == pw->pw_gid)
1099 * Check supplementary groups
1101 while (!found && grp->gr_mem[i])
1102 found = strcmp(name,
1108 * Otherwise, just check for username match
1111 found = strcmp(p, name) == 0;
1113 * Save the rest of line to "residue" if matched
1115 if (found && residue) {
1116 if ((p = strtok(NULL, "")) != NULL)
1117 p += strspn(p, " \t");
1119 if ((*residue = strdup(p)) == NULL)
1120 fatalerror("Ran out of memory.");
1134 * Terminate login as previous user, if any, resetting state;
1135 * used when USER command is given or login fails.
1145 if (logged_in && dowtmpx)
1146 ftpd_logwtmpx(ttyline, "", NULL);
1149 /* XXX Missing LOGIN_SETMAC */
1150 setusercontext(NULL, getpwuid(0), 0,
1151 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1155 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1156 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1157 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1158 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1159 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1160 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1172 * the following code is stolen from imap-uw PAM authentication module and
1175 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1178 const char *uname; /* user name */
1179 const char *pass; /* password */
1181 typedef struct cred_t cred_t;
1184 auth_conv(int num_msg, const struct pam_message **msg,
1185 struct pam_response **resp, void *appdata)
1188 cred_t *cred = (cred_t *) appdata;
1189 struct pam_response *reply;
1191 reply = calloc(num_msg, sizeof *reply);
1195 for (i = 0; i < num_msg; i++) {
1196 switch (msg[i]->msg_style) {
1197 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1198 reply[i].resp_retcode = PAM_SUCCESS;
1199 reply[i].resp = COPY_STRING(cred->uname);
1200 /* PAM frees resp. */
1202 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1203 reply[i].resp_retcode = PAM_SUCCESS;
1204 reply[i].resp = COPY_STRING(cred->pass);
1205 /* PAM frees resp. */
1209 reply[i].resp_retcode = PAM_SUCCESS;
1210 reply[i].resp = NULL;
1212 default: /* unknown message style */
1214 return PAM_CONV_ERR;
1223 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1224 * authenticated, or 1 if not authenticated. If some sort of PAM system
1225 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1226 * function returns -1. This can be used as an indication that we should
1227 * fall back to a different authentication mechanism.
1230 auth_pam(struct passwd **ppw, const char *pass)
1232 const char *tmpl_user;
1236 cred_t auth_cred = { (*ppw)->pw_name, pass };
1237 struct pam_conv conv = { &auth_conv, &auth_cred };
1239 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1240 if (e != PAM_SUCCESS) {
1242 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1243 * if context creation has failed in the first place.
1245 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
1249 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1250 if (e != PAM_SUCCESS) {
1251 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1252 pam_strerror(pamh, e));
1253 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1254 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1260 e = pam_authenticate(pamh, 0);
1264 * With PAM we support the concept of a "template"
1265 * user. The user enters a login name which is
1266 * authenticated by PAM, usually via a remote service
1267 * such as RADIUS or TACACS+. If authentication
1268 * succeeds, a different but related "template" name
1269 * is used for setting the credentials, shell, and
1270 * home directory. The name the user enters need only
1271 * exist on the remote authentication server, but the
1272 * template name must be present in the local password
1275 * This is supported by two various mechanisms in the
1276 * individual modules. However, from the application's
1277 * point of view, the template user is always passed
1278 * back as a changed value of the PAM_USER item.
1280 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1282 tmpl_user = (const char *) item;
1283 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1284 *ppw = getpwnam(tmpl_user);
1286 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1287 pam_strerror(pamh, e));
1292 case PAM_USER_UNKNOWN:
1298 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1304 e = pam_acct_mgmt(pamh, 0);
1305 if (e != PAM_SUCCESS) {
1306 syslog(LOG_ERR, "pam_acct_mgmt: %s",
1307 pam_strerror(pamh, e));
1313 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1314 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1321 #endif /* USE_PAM */
1329 login_cap_t *lc = NULL;
1334 char *residue = NULL;
1337 if (logged_in || askpasswd == 0) {
1338 reply(503, "Login with USER first.");
1342 if (!guest) { /* "ftp" is only account allowed no password */
1344 rval = 1; /* failure below */
1348 rval = auth_pam(&pw, passwd);
1353 xpasswd = crypt(passwd, pw->pw_passwd);
1354 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1360 rval = strcmp(pw->pw_passwd, xpasswd);
1361 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1362 rval = 1; /* failure */
1365 * If rval == 1, the user failed the authentication check
1366 * above. If rval == 0, either PAM or local authentication
1370 reply(530, "Login incorrect.");
1373 "FTP LOGIN FAILED FROM %s",
1375 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1376 "FTP LOGIN FAILED FROM %s, %s",
1377 remotehost, curname);
1380 if (login_attempts++ >= 5) {
1382 "repeated login failures from %s",
1389 login_attempts = 0; /* this time successful */
1390 if (setegid(pw->pw_gid) < 0) {
1391 reply(550, "Can't set gid.");
1394 /* May be overridden by login.conf */
1397 if ((lc = login_getpwclass(pw)) != NULL) {
1398 char remote_ip[NI_MAXHOST];
1400 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1401 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1404 remote_ip[sizeof(remote_ip) - 1] = 0;
1405 if (!auth_hostok(lc, remotehost, remote_ip)) {
1406 syslog(LOG_INFO|LOG_AUTH,
1407 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1409 reply(530, "Permission denied.");
1413 if (!auth_timeok(lc, time(NULL))) {
1414 reply(530, "Login not available right now.");
1419 /* XXX Missing LOGIN_SETMAC */
1420 setusercontext(lc, pw, 0,
1421 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1422 LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1424 setlogin(pw->pw_name);
1425 initgroups(pw->pw_name, pw->pw_gid);
1430 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1431 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1432 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1433 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1438 /* open wtmpx before chroot */
1440 ftpd_logwtmpx(ttyline, pw->pw_name,
1441 (struct sockaddr *)&his_addr);
1444 if (guest && stats && statfd < 0)
1445 #ifdef VIRTUAL_HOSTING
1446 statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1448 statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1454 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue)
1455 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1456 || login_getcapbool(lc, "ftp-chroot", 0)
1461 * For a chrooted local user,
1462 * a) see whether ftpchroot(5) specifies a chroot directory,
1463 * b) extract the directory pathname from the line,
1464 * c) expand it to the absolute pathname if necessary.
1466 if (dochroot && residue &&
1467 (chrootdir = strtok(residue, " \t")) != NULL) {
1468 if (chrootdir[0] != '/')
1469 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1471 chrootdir = strdup(chrootdir); /* make it permanent */
1472 if (chrootdir == NULL)
1473 fatalerror("Ran out of memory.");
1475 if (guest || dochroot) {
1477 * If no chroot directory set yet, use the login directory.
1478 * Copy it so it can be modified while pw->pw_dir stays intact.
1480 if (chrootdir == NULL &&
1481 (chrootdir = strdup(pw->pw_dir)) == NULL)
1482 fatalerror("Ran out of memory.");
1484 * Check for the "/chroot/./home" syntax,
1485 * separate the chroot and home directory pathnames.
1487 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1488 *(homedir++) = '\0'; /* wipe '/' */
1489 homedir++; /* skip '.' */
1492 * We MUST do a chdir() after the chroot. Otherwise
1493 * the old current directory will be accessible as "."
1494 * outside the new root!
1499 * Finally, do chroot()
1501 if (chroot(chrootdir) < 0) {
1502 reply(550, "Can't change root.");
1505 } else /* real user w/o chroot */
1506 homedir = pw->pw_dir;
1508 * Set euid *before* doing chdir() so
1509 * a) the user won't be carried to a directory that he couldn't reach
1510 * on his own due to no permission to upper path components,
1511 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1512 * (uid 0 has no root power over NFS if not mapped explicitly.)
1514 if (seteuid(pw->pw_uid) < 0) {
1515 reply(550, "Can't set uid.");
1518 if (chdir(homedir) < 0) {
1519 if (guest || dochroot) {
1520 reply(550, "Can't change to base directory.");
1523 if (chdir("/") < 0) {
1524 reply(550, "Root is inaccessible.");
1527 lreply(230, "No directory! Logging in with home=/.");
1532 * Display a login message, if it exists.
1533 * N.B. reply(230,) must follow the message.
1535 #ifdef VIRTUAL_HOSTING
1536 fd = fopen(thishost->loginmsg, "r");
1538 fd = fopen(_PATH_FTPLOGINMESG, "r");
1541 char *cp, line[LINE_MAX];
1543 while (fgets(line, sizeof(line), fd) != NULL) {
1544 if ((cp = strchr(line, '\n')) != NULL)
1546 lreply(230, "%s", line);
1554 ident = strdup(passwd);
1556 fatalerror("Ran out of memory.");
1558 reply(230, "Guest login ok, access restrictions apply.");
1560 #ifdef VIRTUAL_HOSTING
1561 if (thishost != firsthost)
1562 snprintf(proctitle, sizeof(proctitle),
1563 "%s: anonymous(%s)/%s", remotehost, hostname,
1567 snprintf(proctitle, sizeof(proctitle),
1568 "%s: anonymous/%s", remotehost, passwd);
1569 setproctitle("%s", proctitle);
1570 #endif /* SETPROCTITLE */
1572 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1573 remotehost, passwd);
1576 reply(230, "User %s logged in, "
1577 "access restrictions apply.", pw->pw_name);
1579 reply(230, "User %s logged in.", pw->pw_name);
1582 snprintf(proctitle, sizeof(proctitle),
1583 "%s: user/%s", remotehost, pw->pw_name);
1584 setproctitle("%s", proctitle);
1585 #endif /* SETPROCTITLE */
1587 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1588 remotehost, pw->pw_name);
1590 if (logging && (guest || dochroot))
1591 syslog(LOG_INFO, "session root changed to %s", chrootdir);
1599 /* Forget all about it... */
1609 retrieve(char *cmd, char *name)
1613 int (*closefunc)(FILE *);
1617 fin = fopen(name, "r"), closefunc = fclose;
1622 snprintf(line, sizeof(line), cmd, name), name = line;
1623 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1625 st.st_blksize = BUFSIZ;
1629 perror_reply(550, name);
1631 LOGCMD("get", name);
1638 if (fstat(fileno(fin), &st) < 0) {
1639 perror_reply(550, name);
1642 if (!S_ISREG(st.st_mode)) {
1644 * Never sending a raw directory is a workaround
1645 * for buggy clients that will attempt to RETR
1646 * a directory before listing it, e.g., Mozilla.
1647 * Preventing a guest from getting irregular files
1648 * is a simple security measure.
1650 if (S_ISDIR(st.st_mode) || guest) {
1651 reply(550, "%s: not a plain file.", name);
1655 /* st.st_blksize is set for all descriptor types */
1658 if (restart_point) {
1659 if (type == TYPE_A) {
1666 if ((c=getc(fin)) == EOF) {
1667 perror_reply(550, name);
1673 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1674 perror_reply(550, name);
1678 dout = dataconn(name, st.st_size, "w");
1682 send_data(fin, dout, st.st_blksize, st.st_size,
1683 restart_point == 0 && cmd == NULL && S_ISREG(st.st_mode));
1684 if (cmd == NULL && guest && stats && byte_count > 0)
1685 logxfer(name, byte_count, start);
1691 LOGBYTES("get", name, byte_count);
1696 store(char *name, char *mode, int unique)
1700 int (*closefunc)(FILE *);
1702 if (*mode == 'a') { /* APPE */
1704 /* Programming error */
1705 syslog(LOG_ERR, "Internal: unique flag to APPE");
1708 if (guest && noguestmod) {
1709 reply(550, "Appending to existing file denied.");
1712 restart_point = 0; /* not affected by preceding REST */
1714 if (unique) /* STOU overrides REST */
1716 if (guest && noguestmod) {
1717 if (restart_point) { /* guest STOR w/REST */
1718 reply(550, "Modifying existing file denied.");
1720 } else /* treat guest STOR as STOU */
1725 mode = "r+"; /* so ASCII manual seek can work */
1727 if ((fd = guniquefd(name, &name)) < 0)
1729 fout = fdopen(fd, mode);
1731 fout = fopen(name, mode);
1734 perror_reply(553, name);
1738 if (restart_point) {
1739 if (type == TYPE_A) {
1746 if ((c=getc(fout)) == EOF) {
1747 perror_reply(550, name);
1754 * We must do this seek to "current" position
1755 * because we are changing from reading to
1758 if (fseeko(fout, 0, SEEK_CUR) < 0) {
1759 perror_reply(550, name);
1762 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1763 perror_reply(550, name);
1767 din = dataconn(name, -1, "r");
1770 if (receive_data(din, fout) == 0) {
1772 reply(226, "Transfer complete (unique file name:%s).",
1775 reply(226, "Transfer complete.");
1781 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1785 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1790 getdatasock(char *mode)
1792 int on = 1, s, t, tries;
1795 return (fdopen(data, mode));
1797 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1800 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1801 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1802 /* anchor socket to avoid multi-homing problems */
1803 data_source = ctrl_addr;
1804 data_source.su_port = htons(dataport);
1806 for (tries = 1; ; tries++) {
1808 * We should loop here since it's possible that
1809 * another ftpd instance has passed this point and is
1810 * trying to open a data connection in active mode now.
1811 * Until the other connection is opened, we'll be getting
1812 * EADDRINUSE because no SOCK_STREAM sockets in the system
1813 * can share both local and remote addresses, localIP:20
1814 * and *:* in this case.
1816 if (bind(s, (struct sockaddr *)&data_source,
1817 data_source.su_len) >= 0)
1819 if (errno != EADDRINUSE || tries > 10)
1823 seteuid(pw->pw_uid);
1825 if (data_source.su_family == AF_INET)
1827 on = IPTOS_THROUGHPUT;
1828 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1829 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1834 * Turn off push flag to keep sender TCP from sending short packets
1835 * at the boundaries of each write().
1838 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1839 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1841 return (fdopen(s, mode));
1843 /* Return the real value of errno (close may change it) */
1845 seteuid(pw->pw_uid);
1852 dataconn(char *name, off_t size, char *mode)
1856 int retry = 0, tos, conerrno;
1861 snprintf(sizebuf, sizeof(sizebuf),
1862 " (%jd bytes)", (intmax_t)size);
1866 union sockunion from;
1867 socklen_t fromlen = ctrl_addr.su_len;
1869 struct timeval timeout;
1873 FD_SET(pdata, &set);
1875 timeout.tv_usec = 0;
1876 timeout.tv_sec = 120;
1879 * Granted a socket is in the blocking I/O mode,
1880 * accept() will block after a successful select()
1881 * if the selected connection dies in between.
1882 * Therefore set the non-blocking I/O flag here.
1884 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1885 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1887 if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
1888 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1893 * Unset the inherited non-blocking I/O flag
1894 * on the child socket so stdio can work on it.
1896 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1897 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1900 if (from.su_family == AF_INET)
1902 tos = IPTOS_THROUGHPUT;
1903 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1904 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1907 reply(150, "Opening %s mode data connection for '%s'%s.",
1908 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1909 return (fdopen(pdata, mode));
1911 reply(425, "Can't open data connection.");
1917 reply(125, "Using existing data connection for '%s'%s.",
1920 return (fdopen(data, mode));
1923 data_dest = his_addr;
1926 file = getdatasock(mode);
1928 char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
1930 if (getnameinfo((struct sockaddr *)&data_source,
1932 hostbuf, sizeof(hostbuf) - 1,
1933 portbuf, sizeof(portbuf) - 1,
1934 NI_NUMERICHOST|NI_NUMERICSERV))
1935 *hostbuf = *portbuf = 0;
1936 hostbuf[sizeof(hostbuf) - 1] = 0;
1937 portbuf[sizeof(portbuf) - 1] = 0;
1938 reply(425, "Can't create data socket (%s,%s): %s.",
1939 hostbuf, portbuf, strerror(errno));
1942 data = fileno(file);
1944 if (connect(data, (struct sockaddr *)&data_dest,
1945 data_dest.su_len) == 0)
1950 if (conerrno == EADDRINUSE) {
1956 } while (retry <= swaitmax);
1957 if (conerrno != 0) {
1958 reply(425, "Can't build data connection: %s.",
1959 strerror(conerrno));
1962 reply(150, "Opening %s mode data connection for '%s'%s.",
1963 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1968 * A helper macro to avoid code duplication
1969 * in send_data() and receive_data().
1971 * XXX We have to block SIGURG during putc() because BSD stdio
1972 * is unable to restart interrupted write operations and hence
1973 * the entire buffer contents will be lost as soon as a write()
1974 * call indicates EINTR to stdio.
1976 #define FTPD_PUTC(ch, file, label) \
1982 ret = putc((ch), (file)); \
1984 CHECKOOB(return (-1)) \
1985 else if (ferror(file)) \
1988 } while (ret == EOF); \
1992 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1993 * encapsulation of the data subject to Mode, Structure, and Type.
1995 * NB: Form isn't handled.
1998 send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2000 int c, cp, filefd, netfd;
2011 CHECKOOB(return (-1))
2012 else if (c == EOF && ferror(instr))
2015 if (ferror(instr)) { /* resume after OOB */
2019 if (feof(instr)) /* EOF */
2021 syslog(LOG_ERR, "Internal: impossible condition"
2022 " on file after getc()");
2025 if (c == '\n' && cp != '\r') {
2026 FTPD_PUTC('\r', outstr, data_err);
2029 FTPD_PUTC(c, outstr, data_err);
2033 #ifdef notyet /* BSD stdio isn't ready for that */
2034 while (fflush(outstr) == EOF) {
2035 CHECKOOB(return (-1))
2043 if (fflush(outstr) == EOF)
2046 reply(226, "Transfer complete.");
2052 * isreg is only set if we are not doing restart and we
2053 * are sending a regular file
2055 netfd = fileno(outstr);
2056 filefd = fileno(instr);
2059 char *msg = "Transfer complete.";
2065 while (filesize > 0) {
2066 err = sendfile(filefd, netfd, offset, 0,
2069 * Calculate byte_count before OOB processing.
2070 * It can be used in myoob() later.
2075 CHECKOOB(return (-1))
2076 else if (err == -1) {
2077 if (errno != EINTR &&
2078 cnt == 0 && offset == 0)
2082 if (err == -1) /* resume after OOB */
2085 * We hit the EOF prematurely.
2086 * Perhaps the file was externally truncated.
2089 msg = "Transfer finished due to "
2090 "premature end of file.";
2095 reply(226, "%s", msg);
2100 if ((buf = malloc(blksize)) == NULL) {
2102 reply(451, "Ran out of memory.");
2110 cnt = read(filefd, buf, blksize);
2111 CHECKOOB(free(buf); return (-1))
2116 if (cnt < 0) /* resume after OOB */
2118 if (cnt == 0) /* EOF */
2120 for (len = cnt, bp = buf; len > 0;) {
2121 cnt = write(netfd, bp, len);
2122 CHECKOOB(free(buf); return (-1))
2136 reply(226, "Transfer complete.");
2140 reply(550, "Unimplemented TYPE %d in send_data.", type);
2146 perror_reply(426, "Data connection");
2151 perror_reply(551, "Error on input file");
2156 * Transfer data from peer to "outstr" using the appropriate encapulation of
2157 * the data subject to Mode, Structure, and Type.
2159 * N.B.: Form isn't handled.
2162 receive_data(FILE *instr, FILE *outstr)
2178 cnt = read(fileno(instr), buf, sizeof(buf));
2179 CHECKOOB(return (-1))
2182 if (cnt < 0) /* resume after OOB */
2184 if (cnt == 0) /* EOF */
2186 for (len = cnt, bp = buf; len > 0;) {
2187 cnt = write(fileno(outstr), bp, len);
2188 CHECKOOB(return (-1))
2203 reply(553, "TYPE E not implemented.");
2210 CHECKOOB(return (-1))
2211 else if (c == EOF && ferror(instr))
2213 if (c == EOF && ferror(instr)) { /* resume after OOB */
2220 FTPD_PUTC('\r', outstr, file_err);
2230 /* Check for EOF here in order not to lose last \r. */
2232 if (feof(instr)) /* EOF */
2234 syslog(LOG_ERR, "Internal: impossible condition"
2235 " on data stream after getc()");
2240 FTPD_PUTC(c, outstr, file_err);
2243 #ifdef notyet /* BSD stdio isn't ready for that */
2244 while (fflush(outstr) == EOF) {
2245 CHECKOOB(return (-1))
2253 if (fflush(outstr) == EOF)
2258 "WARNING! %d bare linefeeds received in ASCII mode.",
2260 printf(" File may not have transferred correctly.\r\n");
2265 reply(550, "Unimplemented TYPE %d in receive_data.", type);
2271 perror_reply(426, "Data connection");
2276 perror_reply(452, "Error writing to file");
2281 statfilecmd(char *filename)
2286 char line[LINE_MAX];
2289 code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2290 snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2291 fin = ftpd_popen(line, "r");
2292 lreply(code, "Status of %s:", filename);
2294 while ((c = getc(fin)) != EOF) {
2296 if (ferror(stdout)){
2297 perror_reply(421, "Control connection");
2303 perror_reply(551, filename);
2310 * RFC 959 says neutral text should be prepended before
2311 * a leading 3-digit number followed by whitespace, but
2312 * many ftp clients can be confused by any leading digits,
2313 * as a matter of fact.
2315 if (atstart && isdigit(c))
2318 atstart = (c == '\n');
2321 reply(code, "End of status.");
2327 union sockunion *su;
2329 char hname[NI_MAXHOST];
2333 lreply(211, "%s FTP server status:", hostname);
2334 printf(" %s\r\n", version);
2336 lreply(211, "FTP server status:");
2337 printf(" Connected to %s", remotehost);
2338 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2339 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2340 hname[sizeof(hname) - 1] = 0;
2341 if (strcmp(hname, remotehost) != 0)
2342 printf(" (%s)", hname);
2347 printf(" Logged in anonymously\r\n");
2349 printf(" Logged in as %s\r\n", pw->pw_name);
2350 } else if (askpasswd)
2351 printf(" Waiting for password\r\n");
2353 printf(" Waiting for user name\r\n");
2354 printf(" TYPE: %s", typenames[type]);
2355 if (type == TYPE_A || type == TYPE_E)
2356 printf(", FORM: %s", formnames[form]);
2359 printf(" %d", CHAR_BIT);
2361 printf(" %d", bytesize); /* need definition! */
2363 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2364 strunames[stru], modenames[mode]);
2366 printf(" Data connection open\r\n");
2367 else if (pdata != -1) {
2371 } else if (usedefault == 0) {
2375 #define UC(b) (((int) b) & 0xff)
2377 printf(" EPSV only mode (EPSV ALL)\r\n");
2382 if (su->su_family == AF_INET) {
2383 a = (u_char *) &su->su_sin.sin_addr;
2384 p = (u_char *) &su->su_sin.sin_port;
2385 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2386 ispassive ? "PASV" : "PORT",
2387 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2388 UC(p[0]), UC(p[1]));
2395 switch (su->su_family) {
2397 a = (u_char *) &su->su_sin.sin_addr;
2398 p = (u_char *) &su->su_sin.sin_port;
2399 alen = sizeof(su->su_sin.sin_addr);
2403 a = (u_char *) &su->su_sin6.sin6_addr;
2404 p = (u_char *) &su->su_sin6.sin6_port;
2405 alen = sizeof(su->su_sin6.sin6_addr);
2413 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2415 for (i = 0; i < alen; i++)
2416 printf("%d,", UC(a[i]));
2417 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2426 switch (su->su_family) {
2438 union sockunion tmp;
2441 if (tmp.su_family == AF_INET6)
2442 tmp.su_sin6.sin6_scope_id = 0;
2443 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2444 hname, sizeof(hname) - 1, NULL, 0,
2446 hname[sizeof(hname) - 1] = 0;
2447 printf(" %s |%d|%s|%d|\r\n",
2448 ispassive ? "EPSV" : "EPRT",
2449 af, hname, htons(tmp.su_port));
2455 printf(" No data connection\r\n");
2456 reply(211, "End of status.");
2463 reply(451, "Error in server: %s", s);
2464 reply(221, "Closing connection due to server error.");
2470 reply(int n, const char *fmt, ...)
2481 syslog(LOG_DEBUG, "<--- %d ", n);
2483 vsyslog(LOG_DEBUG, fmt, ap);
2489 lreply(int n, const char *fmt, ...)
2500 syslog(LOG_DEBUG, "<--- %d- ", n);
2502 vsyslog(LOG_DEBUG, fmt, ap);
2511 reply(250, "%s command successful.", s);
2518 reply(502, "%s command not implemented.", s);
2527 if ((cp = strchr(cbuf,'\n')))
2529 reply(500, "%s: command not understood.", cbuf);
2537 LOGCMD("delete", name);
2538 if (lstat(name, &st) < 0) {
2539 perror_reply(550, name);
2542 if (S_ISDIR(st.st_mode)) {
2543 if (rmdir(name) < 0) {
2544 perror_reply(550, name);
2549 if (guest && noguestmod) {
2550 reply(550, "Operation not permitted.");
2553 if (unlink(name) < 0) {
2554 perror_reply(550, name);
2565 if (chdir(path) < 0)
2566 perror_reply(550, path);
2576 LOGCMD("mkdir", name);
2577 if (guest && noguestmkd)
2578 reply(550, "Operation not permitted.");
2579 else if (mkdir(name, 0777) < 0)
2580 perror_reply(550, name);
2582 if ((s = doublequote(name)) == NULL)
2583 fatalerror("Ran out of memory.");
2584 reply(257, "\"%s\" directory created.", s);
2590 removedir(char *name)
2593 LOGCMD("rmdir", name);
2594 if (rmdir(name) < 0)
2595 perror_reply(550, name);
2603 char *s, path[MAXPATHLEN + 1];
2605 if (getcwd(path, sizeof(path)) == NULL)
2606 perror_reply(550, "Get current directory");
2608 if ((s = doublequote(path)) == NULL)
2609 fatalerror("Ran out of memory.");
2610 reply(257, "\"%s\" is current directory.", s);
2616 renamefrom(char *name)
2620 if (guest && noguestmod) {
2621 reply(550, "Operation not permitted.");
2624 if (lstat(name, &st) < 0) {
2625 perror_reply(550, name);
2628 reply(350, "File exists, ready for destination name.");
2633 renamecmd(char *from, char *to)
2637 LOGCMD2("rename", from, to);
2639 if (guest && (stat(to, &st) == 0)) {
2640 reply(550, "%s: permission denied.", to);
2644 if (rename(from, to) < 0)
2645 perror_reply(550, "rename");
2651 dolog(struct sockaddr *who)
2653 char who_name[NI_MAXHOST];
2655 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2656 remotehost[sizeof(remotehost) - 1] = 0;
2657 if (getnameinfo(who, who->sa_len,
2658 who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
2660 who_name[sizeof(who_name) - 1] = 0;
2663 #ifdef VIRTUAL_HOSTING
2664 if (thishost != firsthost)
2665 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2666 remotehost, hostname);
2669 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2671 setproctitle("%s", proctitle);
2672 #endif /* SETPROCTITLE */
2675 #ifdef VIRTUAL_HOSTING
2676 if (thishost != firsthost)
2677 syslog(LOG_INFO, "connection from %s (%s) to %s",
2678 remotehost, who_name, hostname);
2681 syslog(LOG_INFO, "connection from %s (%s)",
2682 remotehost, who_name);
2687 * Record logout in wtmpx file
2688 * and exit with supplied status.
2691 dologout(int status)
2694 if (logged_in && dowtmpx) {
2696 ftpd_logwtmpx(ttyline, "", NULL);
2698 /* beware of flushing buffers after a SIGPIPE */
2716 syslog(LOG_ERR, "Internal: maskurg() while no transfer");
2721 sigaddset(&sset, SIGURG);
2722 sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
2732 syslog(LOG_ERR, "Internal: flagxfer(1): "
2733 "transfer already under way");
2739 syslog(LOG_ERR, "Internal: flagxfer(0): "
2740 "no active transfer");
2747 * Returns 0 if OK to resume or -1 if abort requested.
2756 syslog(LOG_ERR, "Internal: myoob() while no transfer");
2760 ret = get_line(cp, 7, stdin);
2762 reply(221, "You could at least say goodbye.");
2764 } else if (ret == -2) {
2765 /* Ignore truncated command. */
2769 if (strcmp(cp, "ABOR\r\n") == 0) {
2771 reply(426, "Transfer aborted. Data connection closed.");
2772 reply(226, "Abort successful.");
2775 if (strcmp(cp, "STAT\r\n") == 0) {
2777 if (file_size != -1)
2778 reply(213, "Status: %jd of %jd bytes transferred.",
2779 (intmax_t)byte_count, (intmax_t)file_size);
2781 reply(213, "Status: %jd bytes transferred.",
2782 (intmax_t)byte_count);
2788 * Note: a response of 425 is not mentioned as a possible response to
2789 * the PASV command in RFC959. However, it has been blessed as
2790 * a legitimate response by Jon Postel in a telephone conversation
2791 * with Rick Adams on 25 Jan 89.
2800 if (pdata >= 0) /* close old port if one set */
2803 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2805 perror_reply(425, "Can't open passive connection");
2809 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2810 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2815 if (ctrl_addr.su_family == AF_INET) {
2816 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2817 : IP_PORTRANGE_DEFAULT;
2819 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2820 &on, sizeof(on)) < 0)
2824 #ifdef IPV6_PORTRANGE
2825 if (ctrl_addr.su_family == AF_INET6) {
2826 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2827 : IPV6_PORTRANGE_DEFAULT;
2829 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2830 &on, sizeof(on)) < 0)
2835 pasv_addr = ctrl_addr;
2836 pasv_addr.su_port = 0;
2837 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2840 seteuid(pw->pw_uid);
2842 len = sizeof(pasv_addr);
2843 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2845 if (listen(pdata, 1) < 0)
2847 if (pasv_addr.su_family == AF_INET)
2848 a = (char *) &pasv_addr.su_sin.sin_addr;
2849 else if (pasv_addr.su_family == AF_INET6 &&
2850 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2851 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2855 p = (char *) &pasv_addr.su_port;
2857 #define UC(b) (((int) b) & 0xff)
2859 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2860 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2864 seteuid(pw->pw_uid);
2867 perror_reply(425, "Can't open passive connection");
2872 * Long Passive defined in RFC 1639.
2873 * 228 Entering Long Passive Mode
2874 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2878 long_passive(char *cmd, int pf)
2884 if (pdata >= 0) /* close old port if one set */
2887 if (pf != PF_UNSPEC) {
2888 if (ctrl_addr.su_family != pf) {
2889 switch (ctrl_addr.su_family) {
2902 * only EPRT/EPSV ready clients will understand this
2904 if (strcmp(cmd, "EPSV") == 0 && pf) {
2905 reply(522, "Network protocol mismatch, "
2908 reply(501, "Network protocol mismatch."); /*XXX*/
2914 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2916 perror_reply(425, "Can't open passive connection");
2920 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2921 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2925 pasv_addr = ctrl_addr;
2926 pasv_addr.su_port = 0;
2927 len = pasv_addr.su_len;
2930 if (ctrl_addr.su_family == AF_INET) {
2931 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2932 : IP_PORTRANGE_DEFAULT;
2934 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2935 &on, sizeof(on)) < 0)
2939 #ifdef IPV6_PORTRANGE
2940 if (ctrl_addr.su_family == AF_INET6) {
2941 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2942 : IPV6_PORTRANGE_DEFAULT;
2944 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2945 &on, sizeof(on)) < 0)
2950 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2953 seteuid(pw->pw_uid);
2955 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2957 if (listen(pdata, 1) < 0)
2960 #define UC(b) (((int) b) & 0xff)
2962 if (strcmp(cmd, "LPSV") == 0) {
2963 p = (char *)&pasv_addr.su_port;
2964 switch (pasv_addr.su_family) {
2966 a = (char *) &pasv_addr.su_sin.sin_addr;
2969 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2970 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2971 2, UC(p[0]), UC(p[1]));
2974 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
2975 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2978 a = (char *) &pasv_addr.su_sin6.sin6_addr;
2980 "Entering Long Passive Mode "
2981 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2982 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2983 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2984 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2985 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2986 2, UC(p[0]), UC(p[1]));
2989 } else if (strcmp(cmd, "EPSV") == 0) {
2990 switch (pasv_addr.su_family) {
2993 reply(229, "Entering Extended Passive Mode (|||%d|)",
2994 ntohs(pasv_addr.su_port));
2998 /* more proper error code? */
3002 seteuid(pw->pw_uid);
3005 perror_reply(425, "Can't open passive connection");
3010 * Generate unique name for file with basename "local"
3011 * and open the file in order to avoid possible races.
3012 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3013 * Return descriptor to the file, set "name" to its name.
3015 * Generates failure reply on error.
3018 guniquefd(char *local, char **name)
3020 static char new[MAXPATHLEN];
3026 cp = strrchr(local, '/');
3029 if (stat(cp ? local : ".", &st) < 0) {
3030 perror_reply(553, cp ? local : ".");
3035 * Let not overwrite dirname with counter suffix.
3037 * In this extreme case dot won't be put in front of suffix.
3039 if (strlen(local) > sizeof(new) - 4) {
3040 reply(553, "Pathname too long.");
3045 /* -4 is for the .nn<null> we put on the end below */
3046 snprintf(new, sizeof(new) - 4, "%s", local);
3047 cp = new + strlen(new);
3049 * Don't generate dotfile unless requested explicitly.
3050 * This covers the case when basename gets truncated off
3053 if (cp > new && cp[-1] != '/')
3055 for (count = 0; count < 100; count++) {
3056 /* At count 0 try unmodified name */
3058 sprintf(cp, "%d", count);
3059 if ((fd = open(count ? new : local,
3060 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3061 *name = count ? new : local;
3064 if (errno != EEXIST) {
3065 perror_reply(553, count ? new : local);
3069 reply(452, "Unique file name cannot be created.");
3074 * Format and send reply containing system error number.
3077 perror_reply(int code, char *string)
3080 reply(code, "%s: %s.", string, strerror(errno));
3083 static char *onefile[] = {
3089 send_file_list(char *whichf)
3095 char **dirlist, *dirname;
3100 if (strpbrk(whichf, "~{[*?") != NULL) {
3101 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3103 memset(&gl, 0, sizeof(gl));
3104 gl.gl_matchc = MAXGLOBARGS;
3105 /*flags |= GLOB_LIMIT;*/
3107 if (glob(whichf, flags, 0, &gl)) {
3108 reply(550, "No matching files found.");
3110 } else if (gl.gl_pathc == 0) {
3112 perror_reply(550, whichf);
3115 dirlist = gl.gl_pathv;
3117 onefile[0] = whichf;
3122 while ((dirname = *dirlist++)) {
3123 if (stat(dirname, &st) < 0) {
3125 * If user typed "ls -l", etc, and the client
3126 * used NLST, do what the user meant.
3128 if (dirname[0] == '-' && *dirlist == NULL &&
3130 retrieve(_PATH_LS " %s", dirname);
3132 perror_reply(550, whichf);
3136 if (S_ISREG(st.st_mode)) {
3138 dout = dataconn("file list", -1, "w");
3144 fprintf(dout, "%s%s\n", dirname,
3145 type == TYPE_A ? "\r" : "");
3149 byte_count += strlen(dirname) +
3150 (type == TYPE_A ? 2 : 1);
3151 CHECKOOB(goto abrt);
3153 } else if (!S_ISDIR(st.st_mode))
3156 if ((dirp = opendir(dirname)) == NULL)
3159 while ((dir = readdir(dirp)) != NULL) {
3160 char nbuf[MAXPATHLEN];
3162 CHECKOOB(goto abrt);
3164 if (strcmp(dir->d_name, ".") == 0)
3166 if (strcmp(dir->d_name, "..") == 0)
3169 snprintf(nbuf, sizeof(nbuf),
3170 "%s/%s", dirname, dir->d_name);
3173 * We have to do a stat to insure it's
3174 * not a directory or special file.
3176 if (simple || (stat(nbuf, &st) == 0 &&
3177 S_ISREG(st.st_mode))) {
3179 dout = dataconn("file list", -1, "w");
3185 if (nbuf[0] == '.' && nbuf[1] == '/')
3186 fprintf(dout, "%s%s\n", &nbuf[2],
3187 type == TYPE_A ? "\r" : "");
3189 fprintf(dout, "%s%s\n", nbuf,
3190 type == TYPE_A ? "\r" : "");
3194 byte_count += strlen(nbuf) +
3195 (type == TYPE_A ? 2 : 1);
3196 CHECKOOB(goto abrt);
3204 reply(550, "No files found.");
3205 else if (ferror(dout))
3206 data_err: perror_reply(550, "Data connection");
3208 reply(226, "Transfer complete.");
3226 reapchild(int signo)
3228 while (waitpid(-1, NULL, WNOHANG) > 0);
3232 appendf(char **strp, char *fmt, ...)
3238 vasprintf(&p, fmt, ap);
3241 fatalerror("Ran out of memory.");
3246 asprintf(strp, "%s%s", ostr, p);
3248 fatalerror("Ran out of memory.");
3254 logcmd(char *cmd, char *file1, char *file2, off_t cnt)
3257 char wd[MAXPATHLEN + 1];
3262 if (getcwd(wd, sizeof(wd) - 1) == NULL)
3263 strcpy(wd, strerror(errno));
3265 appendf(&msg, "%s", cmd);
3267 appendf(&msg, " %s", file1);
3269 appendf(&msg, " %s", file2);
3271 appendf(&msg, " = %jd bytes", (intmax_t)cnt);
3272 appendf(&msg, " (wd: %s", wd);
3273 if (guest || dochroot)
3274 appendf(&msg, "; chrooted");
3276 syslog(LOG_INFO, "%s", msg);
3281 logxfer(char *name, off_t size, time_t start)
3283 char buf[MAXPATHLEN + 1024];
3284 char path[MAXPATHLEN + 1];
3289 if (realpath(name, path) == NULL) {
3290 syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
3293 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n",
3294 ctime(&now)+4, ident, remotehost,
3295 path, (intmax_t)size,
3296 (long)(now - start + (now == start)));
3297 write(statfd, buf, strlen(buf));
3302 doublequote(char *s)
3307 for (p = s, n = 0; *p; p++)
3311 if ((s2 = malloc(p - s + n + 1)) == NULL)
3314 for (p = s2; *s; s++, p++) {
3315 if ((*p = *s) == '"')
3323 /* setup server socket for specified address family */
3324 /* if af is PF_UNSPEC more than one socket may be returned */
3325 /* the returned list is dynamically allocated, so caller needs to free it */
3327 socksetup(int af, char *bindname, const char *bindport)
3329 struct addrinfo hints, *res, *r;
3330 int error, maxs, *s, *socks;
3333 memset(&hints, 0, sizeof(hints));
3334 hints.ai_flags = AI_PASSIVE;
3335 hints.ai_family = af;
3336 hints.ai_socktype = SOCK_STREAM;
3337 error = getaddrinfo(bindname, bindport, &hints, &res);
3339 syslog(LOG_ERR, "%s", gai_strerror(error));
3340 if (error == EAI_SYSTEM)
3341 syslog(LOG_ERR, "%s", strerror(errno));
3345 /* Count max number of sockets we may open */
3346 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3348 socks = malloc((maxs + 1) * sizeof(int));
3351 syslog(LOG_ERR, "couldn't allocate memory for sockets");
3355 *socks = 0; /* num of sockets counter at start of array */
3357 for (r = res; r; r = r->ai_next) {
3358 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3360 syslog(LOG_DEBUG, "control socket: %m");
3363 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3364 &on, sizeof(on)) < 0)
3366 "control setsockopt (SO_REUSEADDR): %m");
3367 if (r->ai_family == AF_INET6) {
3368 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3369 &on, sizeof(on)) < 0)
3371 "control setsockopt (IPV6_V6ONLY): %m");
3373 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3374 syslog(LOG_DEBUG, "control bind: %m");
3386 syslog(LOG_ERR, "control socket: Couldn't bind to any socket");