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>
77 #include <login_cap.h>
81 #include <security/pam_appl.h>
84 #include "pathnames.h"
89 static char version[] = "Version 6.00LS";
92 extern off_t restart_point;
95 union sockunion ctrl_addr;
96 union sockunion data_source;
97 union sockunion data_dest;
98 union sockunion his_addr;
99 union sockunion pasv_addr;
104 int hostinfo = 1; /* print host-specific info in messages */
109 int timeout = 900; /* timeout after 15 minutes of inactivity */
110 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
112 int restricted_data_ports = 1;
113 int paranoid = 1; /* be extra careful about security */
114 int anon_only = 0; /* Only anonymous ftp allowed */
115 int assumeutf8 = 0; /* Assume that server file names are in UTF-8 */
124 int stru; /* avoid C keyword */
126 int usedefault = 1; /* for data transfers */
127 int pdata = -1; /* for passive mode */
128 int readonly = 0; /* Server is in readonly mode. */
129 int noepsv = 0; /* EPSV command is disabled. */
130 int noretr = 0; /* RETR command is disabled. */
131 int noguestretr = 0; /* RETR command is disabled for anon users. */
132 int noguestmkd = 0; /* MKD command is disabled for anon users. */
133 int noguestmod = 1; /* anon users may not modify existing files. */
137 #if !defined(CMASK) || CMASK == 0
141 int defumask = CMASK; /* default umask value */
146 #ifdef VIRTUAL_HOSTING
149 static struct ftphost {
150 struct ftphost *next;
151 struct addrinfo *hostinfo;
157 } *thishost, *firsthost;
160 char remotehost[NI_MAXHOST];
163 static char ttyline[20];
164 char *tty = ttyline; /* for klogin */
167 static int auth_pam(struct passwd**, const char*);
168 pam_handle_t *pamh = NULL;
172 static struct opie opiedata;
173 static char opieprompt[OPIE_CHALLENGE_MAX+1];
177 char *pid_file = NULL; /* means default location to pidfile(3) */
180 * Limit number of pathnames that glob can return.
181 * A limit of 0 indicates the number of pathnames is unlimited.
183 #define MAXGLOBARGS 16384
186 * Timeout intervals for retrying connections
187 * to hosts that don't accept PORT cmds. This
188 * is a kludge, but given the problems with TCP...
190 #define SWAITMAX 90 /* wait at most 90 seconds */
191 #define SWAITINT 5 /* interval between retries */
193 int swaitmax = SWAITMAX;
194 int swaitint = SWAITINT;
197 char proctitle[LINE_MAX]; /* initial part of title */
198 #endif /* SETPROCTITLE */
200 #define LOGCMD(cmd, file) logcmd((cmd), (file), NULL, -1)
201 #define LOGCMD2(cmd, file1, file2) logcmd((cmd), (file1), (file2), -1)
202 #define LOGBYTES(cmd, file, cnt) logcmd((cmd), (file), NULL, (cnt))
204 static volatile sig_atomic_t recvurg;
205 static int transflag; /* NB: for debugging only */
207 #define STARTXFER flagxfer(1)
208 #define ENDXFER flagxfer(0)
210 #define START_UNSAFE maskurg(1)
211 #define END_UNSAFE maskurg(0)
213 /* It's OK to put an `else' clause after this macro. */
214 #define CHECKOOB(action) \
223 #ifdef VIRTUAL_HOSTING
224 static void inithosts(int);
225 static void selecthost(union sockunion *);
227 static void ack(char *);
228 static void sigurg(int);
229 static void maskurg(int);
230 static void flagxfer(int);
231 static int myoob(void);
232 static int checkuser(char *, char *, int, char **);
233 static FILE *dataconn(char *, off_t, char *);
234 static void dolog(struct sockaddr *);
235 static void end_login(void);
236 static FILE *getdatasock(char *);
237 static int guniquefd(char *, char **);
238 static void lostconn(int);
239 static void sigquit(int);
240 static int receive_data(FILE *, FILE *);
241 static int send_data(FILE *, FILE *, size_t, off_t, int);
242 static struct passwd *
244 static char *sgetsave(char *);
245 static void reapchild(int);
246 static void appendf(char **, char *, ...) __printflike(2, 3);
247 static void logcmd(char *, char *, char *, off_t);
248 static void logxfer(char *, off_t, time_t);
249 static char *doublequote(char *);
250 static int *socksetup(int, char *, const char *);
253 main(int argc, char *argv[])
257 char *cp, line[LINE_MAX];
259 char *bindname = NULL;
260 const char *bindport = "ftp";
261 int family = AF_UNSPEC;
264 tzset(); /* in case no timezone database in ~ftp */
265 sigemptyset(&sa.sa_mask);
266 sa.sa_flags = SA_RESTART;
269 * Prevent diagnostic messages from appearing on stderr.
270 * We run as a daemon or from inetd; in both cases, there's
271 * more reason in logging to syslog.
273 freopen(_PATH_DEVNULL, "w", stderr);
277 * LOG_NDELAY sets up the logging connection immediately,
278 * necessary for anonymous ftp's that chroot and can't do it later.
280 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
282 while ((ch = getopt(argc, argv,
283 "468a:AdDEH:hlmMoOp:P:rRSt:T:u:UvW")) != -1) {
286 family = (family == AF_INET6) ? AF_UNSPEC : AF_INET;
290 family = (family == AF_INET) ? AF_UNSPEC : AF_INET6;
326 logging++; /* > 1 == extra logging */
366 timeout = atoi(optarg);
367 if (maxtimeout < timeout)
368 maxtimeout = timeout;
372 maxtimeout = atoi(optarg);
373 if (timeout > maxtimeout)
374 timeout = maxtimeout;
381 val = strtol(optarg, &optarg, 8);
382 if (*optarg != '\0' || val < 0)
383 syslog(LOG_WARNING, "bad value for -u");
389 restricted_data_ports = 0;
401 syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
407 int *ctl_sock, fd, maxfd = -1, nfds, i;
408 fd_set defreadfds, readfds;
412 if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
413 if (errno == EEXIST) {
414 syslog(LOG_ERR, "%s already running, pid %d",
415 getprogname(), (int)pid);
418 syslog(LOG_WARNING, "pidfile_open: %m");
422 * Detach from parent.
424 if (daemon(1, 1) < 0) {
425 syslog(LOG_ERR, "failed to become a daemon");
429 if (pfh != NULL && pidfile_write(pfh) == -1)
430 syslog(LOG_WARNING, "pidfile_write: %m");
432 sa.sa_handler = reapchild;
433 sigaction(SIGCHLD, &sa, NULL);
435 #ifdef VIRTUAL_HOSTING
440 * Open a socket, bind it to the FTP port, and start
443 ctl_sock = socksetup(family, bindname, bindport);
444 if (ctl_sock == NULL)
447 FD_ZERO(&defreadfds);
448 for (i = 1; i <= *ctl_sock; i++) {
449 FD_SET(ctl_sock[i], &defreadfds);
450 if (listen(ctl_sock[i], 32) < 0) {
451 syslog(LOG_ERR, "control listen: %m");
454 if (maxfd < ctl_sock[i])
459 * Loop forever accepting connection requests and forking off
460 * children to handle them.
463 FD_COPY(&defreadfds, &readfds);
464 nfds = select(maxfd + 1, &readfds, NULL, NULL, 0);
466 if (nfds < 0 && errno != EINTR)
467 syslog(LOG_WARNING, "select: %m");
472 for (i = 1; i <= *ctl_sock; i++)
473 if (FD_ISSET(ctl_sock[i], &readfds)) {
474 addrlen = sizeof(his_addr);
475 fd = accept(ctl_sock[i],
476 (struct sockaddr *)&his_addr,
483 switch (pid = fork()) {
489 for (i = 1; i <= *ctl_sock; i++)
495 syslog(LOG_WARNING, "fork: %m");
503 addrlen = sizeof(his_addr);
504 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
505 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
509 #ifdef VIRTUAL_HOSTING
510 if (his_addr.su_family == AF_INET6 &&
511 IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))
514 family = his_addr.su_family;
520 sa.sa_handler = SIG_DFL;
521 sigaction(SIGCHLD, &sa, NULL);
523 sa.sa_handler = sigurg;
524 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
525 sigaction(SIGURG, &sa, NULL);
527 sigfillset(&sa.sa_mask); /* block all signals in handler */
528 sa.sa_flags = SA_RESTART;
529 sa.sa_handler = sigquit;
530 sigaction(SIGHUP, &sa, NULL);
531 sigaction(SIGINT, &sa, NULL);
532 sigaction(SIGQUIT, &sa, NULL);
533 sigaction(SIGTERM, &sa, NULL);
535 sa.sa_handler = lostconn;
536 sigaction(SIGPIPE, &sa, NULL);
538 addrlen = sizeof(ctrl_addr);
539 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
540 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
543 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
544 #ifdef VIRTUAL_HOSTING
545 /* select our identity from virtual host table */
546 selecthost(&ctrl_addr);
549 if (ctrl_addr.su_family == AF_INET)
551 tos = IPTOS_LOWDELAY;
552 if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
553 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
557 * Disable Nagle on the control channel so that we don't have to wait
558 * for peer's ACK before issuing our next reply.
560 if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
561 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
563 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
565 /* set this here so klogin can use it... */
566 snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
568 /* Try to handle urgent data inline */
570 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
571 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
575 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
576 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
578 dolog((struct sockaddr *)&his_addr);
580 * Set up default state
589 /* If logins are disabled, print out the message. */
590 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
591 while (fgets(line, sizeof(line), fd) != NULL) {
592 if ((cp = strchr(line, '\n')) != NULL)
594 lreply(530, "%s", line);
598 reply(530, "System not available.");
601 #ifdef VIRTUAL_HOSTING
602 fd = fopen(thishost->welcome, "r");
604 fd = fopen(_PATH_FTPWELCOME, "r");
607 while (fgets(line, sizeof(line), fd) != NULL) {
608 if ((cp = strchr(line, '\n')) != NULL)
610 lreply(220, "%s", line);
614 /* reply(220,) must follow */
616 #ifndef VIRTUAL_HOSTING
617 if (hostname == NULL) {
618 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
619 fatalerror("Ran out of memory.");
620 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
622 hostname[MAXHOSTNAMELEN - 1] = '\0';
626 reply(220, "%s FTP server (%s) ready.", hostname, version);
628 reply(220, "FTP server ready.");
639 syslog(LOG_DEBUG, "lost connection");
647 syslog(LOG_ERR, "got signal %d", signo);
651 #ifdef VIRTUAL_HOSTING
653 * read in virtual host tables (if they exist)
657 inithosts(int family)
662 char *cp, *mp, *line;
663 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
664 struct ftphost *hrp, *lhrp;
665 struct addrinfo hints, *res, *ai;
668 * Fill in the default host information
670 if (hostname == NULL) {
671 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
672 fatalerror("Ran out of memory.");
673 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
675 hostname[MAXHOSTNAMELEN - 1] = '\0';
677 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
678 fatalerror("Ran out of memory.");
679 hrp->hostname = hostname;
680 hrp->hostinfo = NULL;
682 memset(&hints, 0, sizeof(hints));
683 hints.ai_flags = AI_PASSIVE;
684 hints.ai_family = family;
685 hints.ai_socktype = SOCK_STREAM;
686 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
688 hrp->statfile = _PATH_FTPDSTATFILE;
689 hrp->welcome = _PATH_FTPWELCOME;
690 hrp->loginmsg = _PATH_FTPLOGINMESG;
691 hrp->anonuser = "ftp";
693 thishost = firsthost = lhrp = hrp;
694 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
695 int addrsize, gothost;
699 while ((line = fgetln(fp, &len)) != NULL) {
705 if (line[len - 1] == '\n') {
706 line[len - 1] = '\0';
709 if ((mp = malloc(len + 1)) == NULL)
710 fatalerror("Ran out of memory.");
711 memcpy(mp, line, len);
715 cp = strtok(line, " \t");
716 /* skip empty lines */
723 statfile = _PATH_FTPDSTATFILE;
724 welcome = _PATH_FTPWELCOME;
725 loginmsg = _PATH_FTPLOGINMESG;
728 * Preparse the line so we can use its info
729 * for all the addresses associated with
730 * the virtual host name.
731 * Field 0, the virtual host name, is special:
732 * it's already parsed off and will be strdup'ed
733 * later, after we know its canonical form.
735 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
736 if (*cp != '-' && (cp = strdup(cp)))
738 case 1: /* anon user permissions */
741 case 2: /* statistics file */
744 case 3: /* welcome message */
747 case 4: /* login message */
750 default: /* programming error */
755 hints.ai_flags = AI_PASSIVE;
756 hints.ai_family = family;
757 hints.ai_socktype = SOCK_STREAM;
758 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
760 for (ai = res; ai != NULL && ai->ai_addr != NULL;
764 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
767 for (hi = hrp->hostinfo; hi != NULL;
769 if (hi->ai_addrlen == ai->ai_addrlen &&
772 ai->ai_addr->sa_len) == 0) {
780 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
782 hrp->hostname = NULL;
785 if (hrp->hostinfo && hrp->hostinfo != res)
786 freeaddrinfo(hrp->hostinfo);
787 insert = 0; /* host already in the chain */
792 * determine hostname to use.
793 * force defined name if there is a valid alias
794 * otherwise fallback to primary hostname
796 /* XXX: getaddrinfo() can't do alias check */
797 switch(hrp->hostinfo->ai_family) {
799 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
800 addrsize = sizeof(struct in_addr);
803 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
804 addrsize = sizeof(struct in6_addr);
807 /* should not reach here */
808 freeaddrinfo(hrp->hostinfo);
810 free(hrp); /*not in chain, can free*/
812 hrp->hostinfo = NULL; /*mark as blank*/
816 if ((hp = getipnodebyaddr(addr, addrsize,
817 hrp->hostinfo->ai_family,
818 &hp_error)) != NULL) {
819 if (strcmp(vhost, hp->h_name) != 0) {
820 if (hp->h_aliases == NULL)
824 while (hp->h_aliases[i] &&
825 strcmp(vhost, hp->h_aliases[i]) != 0)
827 if (hp->h_aliases[i] == NULL)
833 strcmp(hrp->hostname, vhost) != 0) {
835 hrp->hostname = NULL;
837 if (hrp->hostname == NULL &&
838 (hrp->hostname = strdup(vhost)) == NULL) {
839 freeaddrinfo(hrp->hostinfo);
840 hrp->hostinfo = NULL; /* mark as blank */
845 hrp->anonuser = anonuser;
846 hrp->statfile = statfile;
847 hrp->welcome = welcome;
848 hrp->loginmsg = loginmsg;
866 selecthost(union sockunion *su)
871 struct in6_addr *mapped_in6 = NULL;
877 * XXX IPv4 mapped IPv6 addr consideraton,
878 * specified in rfc2373.
880 if (su->su_family == AF_INET6 &&
881 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
882 mapped_in6 = &su->su_sin6.sin6_addr;
885 hrp = thishost = firsthost; /* default */
888 while (hrp != NULL) {
889 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
890 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
895 /* XXX IPv4 mapped IPv6 addr consideraton */
896 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
897 (memcmp(&mapped_in6->s6_addr[12],
898 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
899 sizeof(struct in_addr)) == 0)) {
909 /* setup static variables as appropriate */
910 hostname = thishost->hostname;
911 ftpuser = thishost->anonuser;
916 * Helper function for sgetpwnam().
921 char *new = malloc(strlen(s) + 1);
924 reply(421, "Ran out of memory.");
933 * Save the result of a getpwnam. Used for USER command, since
934 * the data returned must not be clobbered by any other command
936 * NB: The data returned by sgetpwnam() will remain valid until
937 * the next call to this function. Its difference from getpwnam()
938 * is that sgetpwnam() is known to be called from ftpd code only.
940 static struct passwd *
941 sgetpwnam(char *name)
943 static struct passwd save;
946 if ((p = getpwnam(name)) == NULL)
950 free(save.pw_passwd);
956 save.pw_name = sgetsave(p->pw_name);
957 save.pw_passwd = sgetsave(p->pw_passwd);
958 save.pw_gecos = sgetsave(p->pw_gecos);
959 save.pw_dir = sgetsave(p->pw_dir);
960 save.pw_shell = sgetsave(p->pw_shell);
964 static int login_attempts; /* number of failed login attempts */
965 static int askpasswd; /* had user command, ask for passwd */
966 static char curname[MAXLOGNAME]; /* current USER name */
970 * Sets global passwd pointer pw if named account exists and is acceptable;
971 * sets askpasswd if a PASS command is expected. If logged in previously,
972 * need to reset state. If name is "ftp" or "anonymous", the name is not in
973 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
974 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
975 * requesting login privileges. Disallow anyone who does not have a standard
976 * shell as returned by getusershell(). Disallow anyone mentioned in the file
977 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
986 reply(530, "Can't change user from guest login.");
988 } else if (dochroot) {
989 reply(530, "Can't change user from chroot user.");
996 #ifdef VIRTUAL_HOSTING
997 pw = sgetpwnam(thishost->anonuser);
999 pw = sgetpwnam("ftp");
1001 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1002 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL) ||
1003 checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL))
1004 reply(530, "User %s access denied.", name);
1005 else if (pw != NULL) {
1009 "Guest login ok, send your email address as password.");
1011 reply(530, "User %s unknown.", name);
1012 if (!askpasswd && logging)
1014 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1017 if (anon_only != 0) {
1018 reply(530, "Sorry, only anonymous ftp allowed.");
1022 if ((pw = sgetpwnam(name))) {
1023 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1024 shell = _PATH_BSHELL;
1026 while ((cp = getusershell()) != NULL)
1027 if (strcmp(cp, shell) == 0)
1031 if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1, NULL)) {
1032 reply(530, "User %s access denied.", name);
1035 "FTP LOGIN REFUSED FROM %s, %s",
1042 strncpy(curname, name, sizeof(curname)-1);
1047 /* XXX Kluge! The conversation mechanism needs to be fixed. */
1049 if (opiechallenge(&opiedata, name, opieprompt) == 0) {
1050 pwok = (pw != NULL) &&
1051 opieaccessfile(remotehost) &&
1052 opiealways(pw->pw_dir);
1053 reply(331, "Response to %s %s for %s.",
1054 opieprompt, pwok ? "requested" : "required", name);
1057 reply(331, "Password required for %s.", name);
1061 reply(331, "Password required for %s.", name);
1065 * Delay before reading passwd after first failed
1066 * attempt to slow down passwd-guessing programs.
1069 sleep(login_attempts);
1073 * Check if a user is in the file "fname",
1074 * return a pointer to a malloc'd string with the rest
1075 * of the matching line in "residue" if not NULL.
1078 checkuser(char *fname, char *name, int pwset, char **residue)
1083 char *line, *mp, *p;
1085 if ((fd = fopen(fname, "r")) != NULL) {
1086 while (!found && (line = fgetln(fd, &len)) != NULL) {
1090 if (line[len - 1] == '\n') {
1091 line[len - 1] = '\0';
1094 if ((mp = malloc(len + 1)) == NULL)
1095 fatalerror("Ran out of memory.");
1096 memcpy(mp, line, len);
1100 /* avoid possible leading and trailing whitespace */
1101 p = strtok(line, " \t");
1102 /* skip empty lines */
1106 * if first chr is '@', check group membership
1112 if (p[1] == '\0') /* single @ matches anyone */
1115 if ((grp = getgrnam(p+1)) == NULL)
1118 * Check user's default group
1120 if (pwset && grp->gr_gid == pw->pw_gid)
1123 * Check supplementary groups
1125 while (!found && grp->gr_mem[i])
1126 found = strcmp(name,
1132 * Otherwise, just check for username match
1135 found = strcmp(p, name) == 0;
1137 * Save the rest of line to "residue" if matched
1139 if (found && residue) {
1140 if ((p = strtok(NULL, "")) != NULL)
1141 p += strspn(p, " \t");
1143 if ((*residue = strdup(p)) == NULL)
1144 fatalerror("Ran out of memory.");
1158 * Terminate login as previous user, if any, resetting state;
1159 * used when USER command is given or login fails.
1169 if (logged_in && dowtmp)
1170 ftpd_logwtmp(ttyline, "", NULL);
1173 /* XXX Missing LOGIN_SETMAC */
1174 setusercontext(NULL, getpwuid(0), 0,
1175 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1179 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1180 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1181 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1182 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1183 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1184 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1196 * the following code is stolen from imap-uw PAM authentication module and
1199 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1202 const char *uname; /* user name */
1203 const char *pass; /* password */
1205 typedef struct cred_t cred_t;
1208 auth_conv(int num_msg, const struct pam_message **msg,
1209 struct pam_response **resp, void *appdata)
1212 cred_t *cred = (cred_t *) appdata;
1213 struct pam_response *reply;
1215 reply = calloc(num_msg, sizeof *reply);
1219 for (i = 0; i < num_msg; i++) {
1220 switch (msg[i]->msg_style) {
1221 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1222 reply[i].resp_retcode = PAM_SUCCESS;
1223 reply[i].resp = COPY_STRING(cred->uname);
1224 /* PAM frees resp. */
1226 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1227 reply[i].resp_retcode = PAM_SUCCESS;
1228 reply[i].resp = COPY_STRING(cred->pass);
1229 /* PAM frees resp. */
1233 reply[i].resp_retcode = PAM_SUCCESS;
1234 reply[i].resp = NULL;
1236 default: /* unknown message style */
1238 return PAM_CONV_ERR;
1247 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1248 * authenticated, or 1 if not authenticated. If some sort of PAM system
1249 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1250 * function returns -1. This can be used as an indication that we should
1251 * fall back to a different authentication mechanism.
1254 auth_pam(struct passwd **ppw, const char *pass)
1256 const char *tmpl_user;
1260 cred_t auth_cred = { (*ppw)->pw_name, pass };
1261 struct pam_conv conv = { &auth_conv, &auth_cred };
1263 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1264 if (e != PAM_SUCCESS) {
1266 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1267 * if context creation has failed in the first place.
1269 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
1273 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1274 if (e != PAM_SUCCESS) {
1275 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1276 pam_strerror(pamh, e));
1277 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1278 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1284 e = pam_authenticate(pamh, 0);
1288 * With PAM we support the concept of a "template"
1289 * user. The user enters a login name which is
1290 * authenticated by PAM, usually via a remote service
1291 * such as RADIUS or TACACS+. If authentication
1292 * succeeds, a different but related "template" name
1293 * is used for setting the credentials, shell, and
1294 * home directory. The name the user enters need only
1295 * exist on the remote authentication server, but the
1296 * template name must be present in the local password
1299 * This is supported by two various mechanisms in the
1300 * individual modules. However, from the application's
1301 * point of view, the template user is always passed
1302 * back as a changed value of the PAM_USER item.
1304 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1306 tmpl_user = (const char *) item;
1307 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1308 *ppw = getpwnam(tmpl_user);
1310 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1311 pam_strerror(pamh, e));
1316 case PAM_USER_UNKNOWN:
1322 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1328 e = pam_acct_mgmt(pamh, 0);
1329 if (e != PAM_SUCCESS) {
1330 syslog(LOG_ERR, "pam_acct_mgmt: %s",
1331 pam_strerror(pamh, e));
1337 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1338 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1345 #endif /* USE_PAM */
1353 login_cap_t *lc = NULL;
1358 char *residue = NULL;
1361 if (logged_in || askpasswd == 0) {
1362 reply(503, "Login with USER first.");
1366 if (!guest) { /* "ftp" is only account allowed no password */
1368 rval = 1; /* failure below */
1372 rval = auth_pam(&pw, passwd);
1381 if (opieverify(&opiedata, passwd) == 0)
1382 xpasswd = pw->pw_passwd;
1386 xpasswd = crypt(passwd, pw->pw_passwd);
1387 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1393 rval = strcmp(pw->pw_passwd, xpasswd);
1394 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1395 rval = 1; /* failure */
1398 * If rval == 1, the user failed the authentication check
1399 * above. If rval == 0, either PAM or local authentication
1403 reply(530, "Login incorrect.");
1406 "FTP LOGIN FAILED FROM %s",
1408 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1409 "FTP LOGIN FAILED FROM %s, %s",
1410 remotehost, curname);
1413 if (login_attempts++ >= 5) {
1415 "repeated login failures from %s",
1422 login_attempts = 0; /* this time successful */
1423 if (setegid(pw->pw_gid) < 0) {
1424 reply(550, "Can't set gid.");
1427 /* May be overridden by login.conf */
1430 if ((lc = login_getpwclass(pw)) != NULL) {
1431 char remote_ip[NI_MAXHOST];
1433 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1434 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1437 remote_ip[sizeof(remote_ip) - 1] = 0;
1438 if (!auth_hostok(lc, remotehost, remote_ip)) {
1439 syslog(LOG_INFO|LOG_AUTH,
1440 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1442 reply(530, "Permission denied.");
1446 if (!auth_timeok(lc, time(NULL))) {
1447 reply(530, "Login not available right now.");
1452 /* XXX Missing LOGIN_SETMAC */
1453 setusercontext(lc, pw, 0,
1454 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1455 LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1457 setlogin(pw->pw_name);
1458 initgroups(pw->pw_name, pw->pw_gid);
1463 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1464 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1465 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1466 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1471 /* open wtmp before chroot */
1473 ftpd_logwtmp(ttyline, pw->pw_name,
1474 (struct sockaddr *)&his_addr);
1477 if (guest && stats && statfd < 0)
1478 #ifdef VIRTUAL_HOSTING
1479 statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1481 statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1487 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue)
1488 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1489 || login_getcapbool(lc, "ftp-chroot", 0)
1494 * For a chrooted local user,
1495 * a) see whether ftpchroot(5) specifies a chroot directory,
1496 * b) extract the directory pathname from the line,
1497 * c) expand it to the absolute pathname if necessary.
1499 if (dochroot && residue &&
1500 (chrootdir = strtok(residue, " \t")) != NULL) {
1501 if (chrootdir[0] != '/')
1502 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1504 chrootdir = strdup(chrootdir); /* make it permanent */
1505 if (chrootdir == NULL)
1506 fatalerror("Ran out of memory.");
1508 if (guest || dochroot) {
1510 * If no chroot directory set yet, use the login directory.
1511 * Copy it so it can be modified while pw->pw_dir stays intact.
1513 if (chrootdir == NULL &&
1514 (chrootdir = strdup(pw->pw_dir)) == NULL)
1515 fatalerror("Ran out of memory.");
1517 * Check for the "/chroot/./home" syntax,
1518 * separate the chroot and home directory pathnames.
1520 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1521 *(homedir++) = '\0'; /* wipe '/' */
1522 homedir++; /* skip '.' */
1525 * We MUST do a chdir() after the chroot. Otherwise
1526 * the old current directory will be accessible as "."
1527 * outside the new root!
1532 * Finally, do chroot()
1534 if (chroot(chrootdir) < 0) {
1535 reply(550, "Can't change root.");
1538 } else /* real user w/o chroot */
1539 homedir = pw->pw_dir;
1541 * Set euid *before* doing chdir() so
1542 * a) the user won't be carried to a directory that he couldn't reach
1543 * on his own due to no permission to upper path components,
1544 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1545 * (uid 0 has no root power over NFS if not mapped explicitly.)
1547 if (seteuid(pw->pw_uid) < 0) {
1548 reply(550, "Can't set uid.");
1551 if (chdir(homedir) < 0) {
1552 if (guest || dochroot) {
1553 reply(550, "Can't change to base directory.");
1556 if (chdir("/") < 0) {
1557 reply(550, "Root is inaccessible.");
1560 lreply(230, "No directory! Logging in with home=/.");
1565 * Display a login message, if it exists.
1566 * N.B. reply(230,) must follow the message.
1568 #ifdef VIRTUAL_HOSTING
1569 fd = fopen(thishost->loginmsg, "r");
1571 fd = fopen(_PATH_FTPLOGINMESG, "r");
1574 char *cp, line[LINE_MAX];
1576 while (fgets(line, sizeof(line), fd) != NULL) {
1577 if ((cp = strchr(line, '\n')) != NULL)
1579 lreply(230, "%s", line);
1587 ident = strdup(passwd);
1589 fatalerror("Ran out of memory.");
1591 reply(230, "Guest login ok, access restrictions apply.");
1593 #ifdef VIRTUAL_HOSTING
1594 if (thishost != firsthost)
1595 snprintf(proctitle, sizeof(proctitle),
1596 "%s: anonymous(%s)/%s", remotehost, hostname,
1600 snprintf(proctitle, sizeof(proctitle),
1601 "%s: anonymous/%s", remotehost, passwd);
1602 setproctitle("%s", proctitle);
1603 #endif /* SETPROCTITLE */
1605 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1606 remotehost, passwd);
1609 reply(230, "User %s logged in, "
1610 "access restrictions apply.", pw->pw_name);
1612 reply(230, "User %s logged in.", pw->pw_name);
1615 snprintf(proctitle, sizeof(proctitle),
1616 "%s: user/%s", remotehost, pw->pw_name);
1617 setproctitle("%s", proctitle);
1618 #endif /* SETPROCTITLE */
1620 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1621 remotehost, pw->pw_name);
1623 if (logging && (guest || dochroot))
1624 syslog(LOG_INFO, "session root changed to %s", chrootdir);
1632 /* Forget all about it... */
1642 retrieve(char *cmd, char *name)
1646 int (*closefunc)(FILE *);
1650 fin = fopen(name, "r"), closefunc = fclose;
1655 snprintf(line, sizeof(line), cmd, name), name = line;
1656 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1658 st.st_blksize = BUFSIZ;
1662 perror_reply(550, name);
1664 LOGCMD("get", name);
1671 if (fstat(fileno(fin), &st) < 0) {
1672 perror_reply(550, name);
1675 if (!S_ISREG(st.st_mode)) {
1677 * Never sending a raw directory is a workaround
1678 * for buggy clients that will attempt to RETR
1679 * a directory before listing it, e.g., Mozilla.
1680 * Preventing a guest from getting irregular files
1681 * is a simple security measure.
1683 if (S_ISDIR(st.st_mode) || guest) {
1684 reply(550, "%s: not a plain file.", name);
1688 /* st.st_blksize is set for all descriptor types */
1691 if (restart_point) {
1692 if (type == TYPE_A) {
1699 if ((c=getc(fin)) == EOF) {
1700 perror_reply(550, name);
1706 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1707 perror_reply(550, name);
1711 dout = dataconn(name, st.st_size, "w");
1715 send_data(fin, dout, st.st_blksize, st.st_size,
1716 restart_point == 0 && cmd == NULL && S_ISREG(st.st_mode));
1717 if (cmd == NULL && guest && stats && byte_count > 0)
1718 logxfer(name, byte_count, start);
1724 LOGBYTES("get", name, byte_count);
1729 store(char *name, char *mode, int unique)
1733 int (*closefunc)(FILE *);
1735 if (*mode == 'a') { /* APPE */
1737 /* Programming error */
1738 syslog(LOG_ERR, "Internal: unique flag to APPE");
1741 if (guest && noguestmod) {
1742 reply(550, "Appending to existing file denied.");
1745 restart_point = 0; /* not affected by preceding REST */
1747 if (unique) /* STOU overrides REST */
1749 if (guest && noguestmod) {
1750 if (restart_point) { /* guest STOR w/REST */
1751 reply(550, "Modifying existing file denied.");
1753 } else /* treat guest STOR as STOU */
1758 mode = "r+"; /* so ASCII manual seek can work */
1760 if ((fd = guniquefd(name, &name)) < 0)
1762 fout = fdopen(fd, mode);
1764 fout = fopen(name, mode);
1767 perror_reply(553, name);
1771 if (restart_point) {
1772 if (type == TYPE_A) {
1779 if ((c=getc(fout)) == EOF) {
1780 perror_reply(550, name);
1787 * We must do this seek to "current" position
1788 * because we are changing from reading to
1791 if (fseeko(fout, 0, SEEK_CUR) < 0) {
1792 perror_reply(550, name);
1795 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1796 perror_reply(550, name);
1800 din = dataconn(name, -1, "r");
1803 if (receive_data(din, fout) == 0) {
1805 reply(226, "Transfer complete (unique file name:%s).",
1808 reply(226, "Transfer complete.");
1814 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1818 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1823 getdatasock(char *mode)
1825 int on = 1, s, t, tries;
1828 return (fdopen(data, mode));
1830 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1833 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1834 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1835 /* anchor socket to avoid multi-homing problems */
1836 data_source = ctrl_addr;
1837 data_source.su_port = htons(dataport);
1839 for (tries = 1; ; tries++) {
1841 * We should loop here since it's possible that
1842 * another ftpd instance has passed this point and is
1843 * trying to open a data connection in active mode now.
1844 * Until the other connection is opened, we'll be getting
1845 * EADDRINUSE because no SOCK_STREAM sockets in the system
1846 * can share both local and remote addresses, localIP:20
1847 * and *:* in this case.
1849 if (bind(s, (struct sockaddr *)&data_source,
1850 data_source.su_len) >= 0)
1852 if (errno != EADDRINUSE || tries > 10)
1856 seteuid(pw->pw_uid);
1858 if (data_source.su_family == AF_INET)
1860 on = IPTOS_THROUGHPUT;
1861 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1862 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1867 * Turn off push flag to keep sender TCP from sending short packets
1868 * at the boundaries of each write().
1871 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1872 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1874 return (fdopen(s, mode));
1876 /* Return the real value of errno (close may change it) */
1878 seteuid(pw->pw_uid);
1885 dataconn(char *name, off_t size, char *mode)
1889 int retry = 0, tos, conerrno;
1894 snprintf(sizebuf, sizeof(sizebuf),
1895 " (%jd bytes)", (intmax_t)size);
1899 union sockunion from;
1900 socklen_t fromlen = ctrl_addr.su_len;
1902 struct timeval timeout;
1906 FD_SET(pdata, &set);
1908 timeout.tv_usec = 0;
1909 timeout.tv_sec = 120;
1912 * Granted a socket is in the blocking I/O mode,
1913 * accept() will block after a successful select()
1914 * if the selected connection dies in between.
1915 * Therefore set the non-blocking I/O flag here.
1917 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1918 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1920 if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
1921 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1926 * Unset the inherited non-blocking I/O flag
1927 * on the child socket so stdio can work on it.
1929 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1930 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1933 if (from.su_family == AF_INET)
1935 tos = IPTOS_THROUGHPUT;
1936 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1937 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1940 reply(150, "Opening %s mode data connection for '%s'%s.",
1941 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1942 return (fdopen(pdata, mode));
1944 reply(425, "Can't open data connection.");
1950 reply(125, "Using existing data connection for '%s'%s.",
1953 return (fdopen(data, mode));
1956 data_dest = his_addr;
1959 file = getdatasock(mode);
1961 char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
1963 if (getnameinfo((struct sockaddr *)&data_source,
1965 hostbuf, sizeof(hostbuf) - 1,
1966 portbuf, sizeof(portbuf) - 1,
1967 NI_NUMERICHOST|NI_NUMERICSERV))
1968 *hostbuf = *portbuf = 0;
1969 hostbuf[sizeof(hostbuf) - 1] = 0;
1970 portbuf[sizeof(portbuf) - 1] = 0;
1971 reply(425, "Can't create data socket (%s,%s): %s.",
1972 hostbuf, portbuf, strerror(errno));
1975 data = fileno(file);
1977 if (connect(data, (struct sockaddr *)&data_dest,
1978 data_dest.su_len) == 0)
1983 if (conerrno == EADDRINUSE) {
1989 } while (retry <= swaitmax);
1990 if (conerrno != 0) {
1991 reply(425, "Can't build data connection: %s.",
1992 strerror(conerrno));
1995 reply(150, "Opening %s mode data connection for '%s'%s.",
1996 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2001 * A helper macro to avoid code duplication
2002 * in send_data() and receive_data().
2004 * XXX We have to block SIGURG during putc() because BSD stdio
2005 * is unable to restart interrupted write operations and hence
2006 * the entire buffer contents will be lost as soon as a write()
2007 * call indicates EINTR to stdio.
2009 #define FTPD_PUTC(ch, file, label) \
2015 ret = putc((ch), (file)); \
2017 CHECKOOB(return (-1)) \
2018 else if (ferror(file)) \
2021 } while (ret == EOF); \
2025 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
2026 * encapsulation of the data subject to Mode, Structure, and Type.
2028 * NB: Form isn't handled.
2031 send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2033 int c, cp, filefd, netfd;
2044 CHECKOOB(return (-1))
2045 else if (c == EOF && ferror(instr))
2048 if (ferror(instr)) { /* resume after OOB */
2052 if (feof(instr)) /* EOF */
2054 syslog(LOG_ERR, "Internal: impossible condition"
2055 " on file after getc()");
2058 if (c == '\n' && cp != '\r') {
2059 FTPD_PUTC('\r', outstr, data_err);
2062 FTPD_PUTC(c, outstr, data_err);
2066 #ifdef notyet /* BSD stdio isn't ready for that */
2067 while (fflush(outstr) == EOF) {
2068 CHECKOOB(return (-1))
2076 if (fflush(outstr) == EOF)
2079 reply(226, "Transfer complete.");
2085 * isreg is only set if we are not doing restart and we
2086 * are sending a regular file
2088 netfd = fileno(outstr);
2089 filefd = fileno(instr);
2092 char *msg = "Transfer complete.";
2098 while (filesize > 0) {
2099 err = sendfile(filefd, netfd, offset, 0,
2102 * Calculate byte_count before OOB processing.
2103 * It can be used in myoob() later.
2108 CHECKOOB(return (-1))
2109 else if (err == -1) {
2110 if (errno != EINTR &&
2111 cnt == 0 && offset == 0)
2115 if (err == -1) /* resume after OOB */
2118 * We hit the EOF prematurely.
2119 * Perhaps the file was externally truncated.
2122 msg = "Transfer finished due to "
2123 "premature end of file.";
2128 reply(226, "%s", msg);
2133 if ((buf = malloc(blksize)) == NULL) {
2135 reply(451, "Ran out of memory.");
2143 cnt = read(filefd, buf, blksize);
2144 CHECKOOB(free(buf); return (-1))
2149 if (cnt < 0) /* resume after OOB */
2151 if (cnt == 0) /* EOF */
2153 for (len = cnt, bp = buf; len > 0;) {
2154 cnt = write(netfd, bp, len);
2155 CHECKOOB(free(buf); return (-1))
2169 reply(226, "Transfer complete.");
2173 reply(550, "Unimplemented TYPE %d in send_data.", type);
2179 perror_reply(426, "Data connection");
2184 perror_reply(551, "Error on input file");
2189 * Transfer data from peer to "outstr" using the appropriate encapulation of
2190 * the data subject to Mode, Structure, and Type.
2192 * N.B.: Form isn't handled.
2195 receive_data(FILE *instr, FILE *outstr)
2211 cnt = read(fileno(instr), buf, sizeof(buf));
2212 CHECKOOB(return (-1))
2215 if (cnt < 0) /* resume after OOB */
2217 if (cnt == 0) /* EOF */
2219 for (len = cnt, bp = buf; len > 0;) {
2220 cnt = write(fileno(outstr), bp, len);
2221 CHECKOOB(return (-1))
2236 reply(553, "TYPE E not implemented.");
2243 CHECKOOB(return (-1))
2244 else if (c == EOF && ferror(instr))
2246 if (c == EOF && ferror(instr)) { /* resume after OOB */
2253 FTPD_PUTC('\r', outstr, file_err);
2263 /* Check for EOF here in order not to lose last \r. */
2265 if (feof(instr)) /* EOF */
2267 syslog(LOG_ERR, "Internal: impossible condition"
2268 " on data stream after getc()");
2273 FTPD_PUTC(c, outstr, file_err);
2276 #ifdef notyet /* BSD stdio isn't ready for that */
2277 while (fflush(outstr) == EOF) {
2278 CHECKOOB(return (-1))
2286 if (fflush(outstr) == EOF)
2291 "WARNING! %d bare linefeeds received in ASCII mode.",
2293 printf(" File may not have transferred correctly.\r\n");
2298 reply(550, "Unimplemented TYPE %d in receive_data.", type);
2304 perror_reply(426, "Data connection");
2309 perror_reply(452, "Error writing to file");
2314 statfilecmd(char *filename)
2319 char line[LINE_MAX];
2322 code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2323 snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2324 fin = ftpd_popen(line, "r");
2325 lreply(code, "Status of %s:", filename);
2327 while ((c = getc(fin)) != EOF) {
2329 if (ferror(stdout)){
2330 perror_reply(421, "Control connection");
2336 perror_reply(551, filename);
2343 * RFC 959 says neutral text should be prepended before
2344 * a leading 3-digit number followed by whitespace, but
2345 * many ftp clients can be confused by any leading digits,
2346 * as a matter of fact.
2348 if (atstart && isdigit(c))
2351 atstart = (c == '\n');
2354 reply(code, "End of status.");
2360 union sockunion *su;
2362 char hname[NI_MAXHOST];
2366 lreply(211, "%s FTP server status:", hostname);
2367 printf(" %s\r\n", version);
2369 lreply(211, "FTP server status:");
2370 printf(" Connected to %s", remotehost);
2371 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2372 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2373 hname[sizeof(hname) - 1] = 0;
2374 if (strcmp(hname, remotehost) != 0)
2375 printf(" (%s)", hname);
2380 printf(" Logged in anonymously\r\n");
2382 printf(" Logged in as %s\r\n", pw->pw_name);
2383 } else if (askpasswd)
2384 printf(" Waiting for password\r\n");
2386 printf(" Waiting for user name\r\n");
2387 printf(" TYPE: %s", typenames[type]);
2388 if (type == TYPE_A || type == TYPE_E)
2389 printf(", FORM: %s", formnames[form]);
2392 printf(" %d", CHAR_BIT);
2394 printf(" %d", bytesize); /* need definition! */
2396 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2397 strunames[stru], modenames[mode]);
2399 printf(" Data connection open\r\n");
2400 else if (pdata != -1) {
2404 } else if (usedefault == 0) {
2408 #define UC(b) (((int) b) & 0xff)
2410 printf(" EPSV only mode (EPSV ALL)\r\n");
2415 if (su->su_family == AF_INET) {
2416 a = (u_char *) &su->su_sin.sin_addr;
2417 p = (u_char *) &su->su_sin.sin_port;
2418 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2419 ispassive ? "PASV" : "PORT",
2420 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2421 UC(p[0]), UC(p[1]));
2428 switch (su->su_family) {
2430 a = (u_char *) &su->su_sin.sin_addr;
2431 p = (u_char *) &su->su_sin.sin_port;
2432 alen = sizeof(su->su_sin.sin_addr);
2436 a = (u_char *) &su->su_sin6.sin6_addr;
2437 p = (u_char *) &su->su_sin6.sin6_port;
2438 alen = sizeof(su->su_sin6.sin6_addr);
2446 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2448 for (i = 0; i < alen; i++)
2449 printf("%d,", UC(a[i]));
2450 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2459 switch (su->su_family) {
2471 union sockunion tmp;
2474 if (tmp.su_family == AF_INET6)
2475 tmp.su_sin6.sin6_scope_id = 0;
2476 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2477 hname, sizeof(hname) - 1, NULL, 0,
2479 hname[sizeof(hname) - 1] = 0;
2480 printf(" %s |%d|%s|%d|\r\n",
2481 ispassive ? "EPSV" : "EPRT",
2482 af, hname, htons(tmp.su_port));
2488 printf(" No data connection\r\n");
2489 reply(211, "End of status.");
2496 reply(451, "Error in server: %s", s);
2497 reply(221, "Closing connection due to server error.");
2503 reply(int n, const char *fmt, ...)
2514 syslog(LOG_DEBUG, "<--- %d ", n);
2516 vsyslog(LOG_DEBUG, fmt, ap);
2522 lreply(int n, const char *fmt, ...)
2533 syslog(LOG_DEBUG, "<--- %d- ", n);
2535 vsyslog(LOG_DEBUG, fmt, ap);
2544 reply(250, "%s command successful.", s);
2551 reply(502, "%s command not implemented.", s);
2560 if ((cp = strchr(cbuf,'\n')))
2562 reply(500, "%s: command not understood.", cbuf);
2570 LOGCMD("delete", name);
2571 if (lstat(name, &st) < 0) {
2572 perror_reply(550, name);
2575 if (S_ISDIR(st.st_mode)) {
2576 if (rmdir(name) < 0) {
2577 perror_reply(550, name);
2582 if (guest && noguestmod) {
2583 reply(550, "Operation not permitted.");
2586 if (unlink(name) < 0) {
2587 perror_reply(550, name);
2598 if (chdir(path) < 0)
2599 perror_reply(550, path);
2609 LOGCMD("mkdir", name);
2610 if (guest && noguestmkd)
2611 reply(550, "Operation not permitted.");
2612 else if (mkdir(name, 0777) < 0)
2613 perror_reply(550, name);
2615 if ((s = doublequote(name)) == NULL)
2616 fatalerror("Ran out of memory.");
2617 reply(257, "\"%s\" directory created.", s);
2623 removedir(char *name)
2626 LOGCMD("rmdir", name);
2627 if (rmdir(name) < 0)
2628 perror_reply(550, name);
2636 char *s, path[MAXPATHLEN + 1];
2638 if (getcwd(path, sizeof(path)) == NULL)
2639 perror_reply(550, "Get current directory");
2641 if ((s = doublequote(path)) == NULL)
2642 fatalerror("Ran out of memory.");
2643 reply(257, "\"%s\" is current directory.", s);
2649 renamefrom(char *name)
2653 if (guest && noguestmod) {
2654 reply(550, "Operation not permitted.");
2657 if (lstat(name, &st) < 0) {
2658 perror_reply(550, name);
2661 reply(350, "File exists, ready for destination name.");
2666 renamecmd(char *from, char *to)
2670 LOGCMD2("rename", from, to);
2672 if (guest && (stat(to, &st) == 0)) {
2673 reply(550, "%s: permission denied.", to);
2677 if (rename(from, to) < 0)
2678 perror_reply(550, "rename");
2684 dolog(struct sockaddr *who)
2686 char who_name[NI_MAXHOST];
2688 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2689 remotehost[sizeof(remotehost) - 1] = 0;
2690 if (getnameinfo(who, who->sa_len,
2691 who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
2693 who_name[sizeof(who_name) - 1] = 0;
2696 #ifdef VIRTUAL_HOSTING
2697 if (thishost != firsthost)
2698 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2699 remotehost, hostname);
2702 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2704 setproctitle("%s", proctitle);
2705 #endif /* SETPROCTITLE */
2708 #ifdef VIRTUAL_HOSTING
2709 if (thishost != firsthost)
2710 syslog(LOG_INFO, "connection from %s (%s) to %s",
2711 remotehost, who_name, hostname);
2714 syslog(LOG_INFO, "connection from %s (%s)",
2715 remotehost, who_name);
2720 * Record logout in wtmp file
2721 * and exit with supplied status.
2724 dologout(int status)
2727 if (logged_in && dowtmp) {
2729 ftpd_logwtmp(ttyline, "", NULL);
2731 /* beware of flushing buffers after a SIGPIPE */
2749 syslog(LOG_ERR, "Internal: maskurg() while no transfer");
2754 sigaddset(&sset, SIGURG);
2755 sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
2765 syslog(LOG_ERR, "Internal: flagxfer(1): "
2766 "transfer already under way");
2772 syslog(LOG_ERR, "Internal: flagxfer(0): "
2773 "no active transfer");
2780 * Returns 0 if OK to resume or -1 if abort requested.
2789 syslog(LOG_ERR, "Internal: myoob() while no transfer");
2793 ret = get_line(cp, 7, stdin);
2795 reply(221, "You could at least say goodbye.");
2797 } else if (ret == -2) {
2798 /* Ignore truncated command. */
2802 if (strcmp(cp, "ABOR\r\n") == 0) {
2804 reply(426, "Transfer aborted. Data connection closed.");
2805 reply(226, "Abort successful.");
2808 if (strcmp(cp, "STAT\r\n") == 0) {
2810 if (file_size != -1)
2811 reply(213, "Status: %jd of %jd bytes transferred.",
2812 (intmax_t)byte_count, (intmax_t)file_size);
2814 reply(213, "Status: %jd bytes transferred.",
2815 (intmax_t)byte_count);
2821 * Note: a response of 425 is not mentioned as a possible response to
2822 * the PASV command in RFC959. However, it has been blessed as
2823 * a legitimate response by Jon Postel in a telephone conversation
2824 * with Rick Adams on 25 Jan 89.
2833 if (pdata >= 0) /* close old port if one set */
2836 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2838 perror_reply(425, "Can't open passive connection");
2842 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2843 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2848 if (ctrl_addr.su_family == AF_INET) {
2849 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2850 : IP_PORTRANGE_DEFAULT;
2852 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2853 &on, sizeof(on)) < 0)
2857 #ifdef IPV6_PORTRANGE
2858 if (ctrl_addr.su_family == AF_INET6) {
2859 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2860 : IPV6_PORTRANGE_DEFAULT;
2862 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2863 &on, sizeof(on)) < 0)
2868 pasv_addr = ctrl_addr;
2869 pasv_addr.su_port = 0;
2870 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2873 seteuid(pw->pw_uid);
2875 len = sizeof(pasv_addr);
2876 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2878 if (listen(pdata, 1) < 0)
2880 if (pasv_addr.su_family == AF_INET)
2881 a = (char *) &pasv_addr.su_sin.sin_addr;
2882 else if (pasv_addr.su_family == AF_INET6 &&
2883 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2884 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2888 p = (char *) &pasv_addr.su_port;
2890 #define UC(b) (((int) b) & 0xff)
2892 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2893 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2897 seteuid(pw->pw_uid);
2900 perror_reply(425, "Can't open passive connection");
2905 * Long Passive defined in RFC 1639.
2906 * 228 Entering Long Passive Mode
2907 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2911 long_passive(char *cmd, int pf)
2917 if (pdata >= 0) /* close old port if one set */
2920 if (pf != PF_UNSPEC) {
2921 if (ctrl_addr.su_family != pf) {
2922 switch (ctrl_addr.su_family) {
2935 * only EPRT/EPSV ready clients will understand this
2937 if (strcmp(cmd, "EPSV") == 0 && pf) {
2938 reply(522, "Network protocol mismatch, "
2941 reply(501, "Network protocol mismatch."); /*XXX*/
2947 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2949 perror_reply(425, "Can't open passive connection");
2953 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2954 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2958 pasv_addr = ctrl_addr;
2959 pasv_addr.su_port = 0;
2960 len = pasv_addr.su_len;
2963 if (ctrl_addr.su_family == AF_INET) {
2964 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2965 : IP_PORTRANGE_DEFAULT;
2967 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2968 &on, sizeof(on)) < 0)
2972 #ifdef IPV6_PORTRANGE
2973 if (ctrl_addr.su_family == AF_INET6) {
2974 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2975 : IPV6_PORTRANGE_DEFAULT;
2977 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2978 &on, sizeof(on)) < 0)
2983 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2986 seteuid(pw->pw_uid);
2988 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2990 if (listen(pdata, 1) < 0)
2993 #define UC(b) (((int) b) & 0xff)
2995 if (strcmp(cmd, "LPSV") == 0) {
2996 p = (char *)&pasv_addr.su_port;
2997 switch (pasv_addr.su_family) {
2999 a = (char *) &pasv_addr.su_sin.sin_addr;
3002 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3003 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3004 2, UC(p[0]), UC(p[1]));
3007 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
3008 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
3011 a = (char *) &pasv_addr.su_sin6.sin6_addr;
3013 "Entering Long Passive Mode "
3014 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3015 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3016 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3017 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3018 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3019 2, UC(p[0]), UC(p[1]));
3022 } else if (strcmp(cmd, "EPSV") == 0) {
3023 switch (pasv_addr.su_family) {
3026 reply(229, "Entering Extended Passive Mode (|||%d|)",
3027 ntohs(pasv_addr.su_port));
3031 /* more proper error code? */
3035 seteuid(pw->pw_uid);
3038 perror_reply(425, "Can't open passive connection");
3043 * Generate unique name for file with basename "local"
3044 * and open the file in order to avoid possible races.
3045 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3046 * Return descriptor to the file, set "name" to its name.
3048 * Generates failure reply on error.
3051 guniquefd(char *local, char **name)
3053 static char new[MAXPATHLEN];
3059 cp = strrchr(local, '/');
3062 if (stat(cp ? local : ".", &st) < 0) {
3063 perror_reply(553, cp ? local : ".");
3068 * Let not overwrite dirname with counter suffix.
3070 * In this extreme case dot won't be put in front of suffix.
3072 if (strlen(local) > sizeof(new) - 4) {
3073 reply(553, "Pathname too long.");
3078 /* -4 is for the .nn<null> we put on the end below */
3079 snprintf(new, sizeof(new) - 4, "%s", local);
3080 cp = new + strlen(new);
3082 * Don't generate dotfile unless requested explicitly.
3083 * This covers the case when basename gets truncated off
3086 if (cp > new && cp[-1] != '/')
3088 for (count = 0; count < 100; count++) {
3089 /* At count 0 try unmodified name */
3091 sprintf(cp, "%d", count);
3092 if ((fd = open(count ? new : local,
3093 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3094 *name = count ? new : local;
3097 if (errno != EEXIST) {
3098 perror_reply(553, count ? new : local);
3102 reply(452, "Unique file name cannot be created.");
3107 * Format and send reply containing system error number.
3110 perror_reply(int code, char *string)
3113 reply(code, "%s: %s.", string, strerror(errno));
3116 static char *onefile[] = {
3122 send_file_list(char *whichf)
3128 char **dirlist, *dirname;
3133 if (strpbrk(whichf, "~{[*?") != NULL) {
3134 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3136 memset(&gl, 0, sizeof(gl));
3137 gl.gl_matchc = MAXGLOBARGS;
3138 /*flags |= GLOB_LIMIT;*/
3140 if (glob(whichf, flags, 0, &gl)) {
3141 reply(550, "No matching files found.");
3143 } else if (gl.gl_pathc == 0) {
3145 perror_reply(550, whichf);
3148 dirlist = gl.gl_pathv;
3150 onefile[0] = whichf;
3155 while ((dirname = *dirlist++)) {
3156 if (stat(dirname, &st) < 0) {
3158 * If user typed "ls -l", etc, and the client
3159 * used NLST, do what the user meant.
3161 if (dirname[0] == '-' && *dirlist == NULL &&
3163 retrieve(_PATH_LS " %s", dirname);
3165 perror_reply(550, whichf);
3169 if (S_ISREG(st.st_mode)) {
3171 dout = dataconn("file list", -1, "w");
3177 fprintf(dout, "%s%s\n", dirname,
3178 type == TYPE_A ? "\r" : "");
3182 byte_count += strlen(dirname) +
3183 (type == TYPE_A ? 2 : 1);
3184 CHECKOOB(goto abrt);
3186 } else if (!S_ISDIR(st.st_mode))
3189 if ((dirp = opendir(dirname)) == NULL)
3192 while ((dir = readdir(dirp)) != NULL) {
3193 char nbuf[MAXPATHLEN];
3195 CHECKOOB(goto abrt);
3197 if (strcmp(dir->d_name, ".") == 0)
3199 if (strcmp(dir->d_name, "..") == 0)
3202 snprintf(nbuf, sizeof(nbuf),
3203 "%s/%s", dirname, dir->d_name);
3206 * We have to do a stat to insure it's
3207 * not a directory or special file.
3209 if (simple || (stat(nbuf, &st) == 0 &&
3210 S_ISREG(st.st_mode))) {
3212 dout = dataconn("file list", -1, "w");
3218 if (nbuf[0] == '.' && nbuf[1] == '/')
3219 fprintf(dout, "%s%s\n", &nbuf[2],
3220 type == TYPE_A ? "\r" : "");
3222 fprintf(dout, "%s%s\n", nbuf,
3223 type == TYPE_A ? "\r" : "");
3227 byte_count += strlen(nbuf) +
3228 (type == TYPE_A ? 2 : 1);
3229 CHECKOOB(goto abrt);
3237 reply(550, "No files found.");
3238 else if (ferror(dout))
3239 data_err: perror_reply(550, "Data connection");
3241 reply(226, "Transfer complete.");
3259 reapchild(int signo)
3261 while (waitpid(-1, NULL, WNOHANG) > 0);
3265 appendf(char **strp, char *fmt, ...)
3271 vasprintf(&p, fmt, ap);
3274 fatalerror("Ran out of memory.");
3279 asprintf(strp, "%s%s", ostr, p);
3281 fatalerror("Ran out of memory.");
3287 logcmd(char *cmd, char *file1, char *file2, off_t cnt)
3290 char wd[MAXPATHLEN + 1];
3295 if (getcwd(wd, sizeof(wd) - 1) == NULL)
3296 strcpy(wd, strerror(errno));
3298 appendf(&msg, "%s", cmd);
3300 appendf(&msg, " %s", file1);
3302 appendf(&msg, " %s", file2);
3304 appendf(&msg, " = %jd bytes", (intmax_t)cnt);
3305 appendf(&msg, " (wd: %s", wd);
3306 if (guest || dochroot)
3307 appendf(&msg, "; chrooted");
3309 syslog(LOG_INFO, "%s", msg);
3314 logxfer(char *name, off_t size, time_t start)
3316 char buf[MAXPATHLEN + 1024];
3317 char path[MAXPATHLEN + 1];
3322 if (realpath(name, path) == NULL) {
3323 syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
3326 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n",
3327 ctime(&now)+4, ident, remotehost,
3328 path, (intmax_t)size,
3329 (long)(now - start + (now == start)));
3330 write(statfd, buf, strlen(buf));
3335 doublequote(char *s)
3340 for (p = s, n = 0; *p; p++)
3344 if ((s2 = malloc(p - s + n + 1)) == NULL)
3347 for (p = s2; *s; s++, p++) {
3348 if ((*p = *s) == '"')
3356 /* setup server socket for specified address family */
3357 /* if af is PF_UNSPEC more than one socket may be returned */
3358 /* the returned list is dynamically allocated, so caller needs to free it */
3360 socksetup(int af, char *bindname, const char *bindport)
3362 struct addrinfo hints, *res, *r;
3363 int error, maxs, *s, *socks;
3366 memset(&hints, 0, sizeof(hints));
3367 hints.ai_flags = AI_PASSIVE;
3368 hints.ai_family = af;
3369 hints.ai_socktype = SOCK_STREAM;
3370 error = getaddrinfo(bindname, bindport, &hints, &res);
3372 syslog(LOG_ERR, "%s", gai_strerror(error));
3373 if (error == EAI_SYSTEM)
3374 syslog(LOG_ERR, "%s", strerror(errno));
3378 /* Count max number of sockets we may open */
3379 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3381 socks = malloc((maxs + 1) * sizeof(int));
3384 syslog(LOG_ERR, "couldn't allocate memory for sockets");
3388 *socks = 0; /* num of sockets counter at start of array */
3390 for (r = res; r; r = r->ai_next) {
3391 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3393 syslog(LOG_DEBUG, "control socket: %m");
3396 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3397 &on, sizeof(on)) < 0)
3399 "control setsockopt (SO_REUSEADDR): %m");
3400 if (r->ai_family == AF_INET6) {
3401 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3402 &on, sizeof(on)) < 0)
3404 "control setsockopt (IPV6_V6ONLY): %m");
3406 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3407 syslog(LOG_DEBUG, "control bind: %m");
3419 syslog(LOG_ERR, "control socket: Couldn't bind to any socket");