2 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * @(#)ftpd.c 8.4 (Berkeley) 4/16/94
34 * $FreeBSD: src/libexec/ftpd/ftpd.c,v 1.213 2008/12/23 01:23:09 cperciva Exp $
40 #include <sys/param.h>
41 #include <sys/ioctl.h>
43 #include <sys/socket.h>
48 #include <netinet/in.h>
49 #include <netinet/in_systm.h>
50 #include <netinet/ip.h>
51 #include <netinet/tcp.h>
55 #include <arpa/inet.h>
56 #include <arpa/telnet.h>
79 #include <login_cap.h>
83 #include <security/pam_appl.h>
86 #include "pathnames.h"
92 static char version[] = "Version 6.00LS";
95 extern off_t restart_point;
98 union sockunion ctrl_addr;
99 union sockunion data_source;
100 union sockunion data_dest;
101 union sockunion his_addr;
102 union sockunion pasv_addr;
107 int hostinfo = 1; /* print host-specific info in messages */
112 int timeout = 900; /* timeout after 15 minutes of inactivity */
113 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
115 int restricted_data_ports = 1;
116 int paranoid = 1; /* be extra careful about security */
117 int anon_only = 0; /* Only anonymous ftp allowed */
118 int assumeutf8 = 0; /* Assume that server file names are in UTF-8 */
127 int stru; /* avoid C keyword */
129 int usedefault = 1; /* for data transfers */
130 int pdata = -1; /* for passive mode */
131 int readonly = 0; /* Server is in readonly mode. */
132 int noepsv = 0; /* EPSV command is disabled. */
133 int noretr = 0; /* RETR command is disabled. */
134 int noguestretr = 0; /* RETR command is disabled for anon users. */
135 int noguestmkd = 0; /* MKD command is disabled for anon users. */
136 int noguestmod = 1; /* anon users may not modify existing files. */
140 #if !defined(CMASK) || CMASK == 0
144 int defumask = CMASK; /* default umask value */
149 #ifdef VIRTUAL_HOSTING
152 static struct ftphost {
153 struct ftphost *next;
154 struct addrinfo *hostinfo;
160 } *thishost, *firsthost;
163 char remotehost[NI_MAXHOST];
166 static char ttyline[20];
167 char *tty = ttyline; /* for klogin */
170 static int auth_pam(struct passwd**, const char*);
171 pam_handle_t *pamh = NULL;
174 static struct opie opiedata;
175 static char opieprompt[OPIE_CHALLENGE_MAX+1];
178 char *pid_file = NULL; /* means default location to pidfile(3) */
181 * Limit number of pathnames that glob can return.
182 * A limit of 0 indicates the number of pathnames is unlimited.
184 #define MAXGLOBARGS 16384
188 * Timeout intervals for retrying connections
189 * to hosts that don't accept PORT cmds. This
190 * is a kludge, but given the problems with TCP...
192 #define SWAITMAX 90 /* wait at most 90 seconds */
193 #define SWAITINT 5 /* interval between retries */
195 int swaitmax = SWAITMAX;
196 int swaitint = SWAITINT;
199 char proctitle[LINE_MAX]; /* initial part of title */
200 #endif /* SETPROCTITLE */
202 #define LOGCMD(cmd, file) logcmd((cmd), (file), NULL, -1)
203 #define LOGCMD2(cmd, file1, file2) logcmd((cmd), (file1), (file2), -1)
204 #define LOGBYTES(cmd, file, cnt) logcmd((cmd), (file), NULL, (cnt))
206 static volatile sig_atomic_t recvurg;
207 static int transflag; /* NB: for debugging only */
209 #define STARTXFER flagxfer(1)
210 #define ENDXFER flagxfer(0)
212 #define START_UNSAFE maskurg(1)
213 #define END_UNSAFE maskurg(0)
215 /* It's OK to put an `else' clause after this macro. */
216 #define CHECKOOB(action) \
225 #ifdef VIRTUAL_HOSTING
226 static void inithosts(int);
227 static void selecthost(union sockunion *);
229 static void ack(char *);
230 static void sigurg(int);
231 static void maskurg(int);
232 static void flagxfer(int);
233 static int myoob(void);
234 static int checkuser(char *, char *, int, char **);
235 static FILE *dataconn(char *, off_t, char *);
236 static void dolog(struct sockaddr *);
237 static void end_login(void);
238 static FILE *getdatasock(char *);
239 static int guniquefd(char *, char **);
240 static void lostconn(int);
241 static void sigquit(int);
242 static int receive_data(FILE *, FILE *);
243 static int send_data(FILE *, FILE *, size_t, off_t, int);
244 static struct passwd *
246 static char *sgetsave(char *);
247 static void reapchild(int);
248 static void appendf(char **, char *, ...) __printflike(2, 3);
249 static void logcmd(char *, char *, char *, off_t);
250 static void logxfer(char *, off_t, time_t);
251 static char *doublequote(char *);
252 static int *socksetup(int, char *, const char *);
255 main(int argc, char *argv[])
259 char *cp, line[LINE_MAX];
261 char *bindname = NULL;
262 const char *bindport = "ftp";
263 int family = AF_UNSPEC;
266 tzset(); /* in case no timezone database in ~ftp */
267 sigemptyset(&sa.sa_mask);
268 sa.sa_flags = SA_RESTART;
271 * Prevent diagnostic messages from appearing on stderr.
272 * We run as a daemon or from inetd; in both cases, there's
273 * more reason in logging to syslog.
275 freopen(_PATH_DEVNULL, "w", stderr);
279 * LOG_NDELAY sets up the logging connection immediately,
280 * necessary for anonymous ftp's that chroot and can't do it later.
282 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
284 while ((ch = getopt(argc, argv,
285 "468a:AdDEH:hlmMoOp:P:rRSt:T:u:UvW")) != -1) {
288 family = (family == AF_INET6) ? AF_UNSPEC : AF_INET;
292 family = (family == AF_INET) ? AF_UNSPEC : AF_INET6;
328 logging++; /* > 1 == extra logging */
368 timeout = atoi(optarg);
369 if (maxtimeout < timeout)
370 maxtimeout = timeout;
374 maxtimeout = atoi(optarg);
375 if (timeout > maxtimeout)
376 timeout = maxtimeout;
383 val = strtol(optarg, &optarg, 8);
384 if (*optarg != '\0' || val < 0)
385 syslog(LOG_WARNING, "bad value for -u");
391 restricted_data_ports = 0;
403 syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
409 int *ctl_sock, fd, maxfd = -1, nfds, i;
410 fd_set defreadfds, readfds;
414 if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
415 if (errno == EEXIST) {
416 syslog(LOG_ERR, "%s already running, pid %d",
417 getprogname(), (int)pid);
420 syslog(LOG_WARNING, "pidfile_open: %m");
424 * Detach from parent.
426 if (daemon(1, 1) < 0) {
427 syslog(LOG_ERR, "failed to become a daemon");
431 if (pfh != NULL && pidfile_write(pfh) == -1)
432 syslog(LOG_WARNING, "pidfile_write: %m");
434 sa.sa_handler = reapchild;
435 sigaction(SIGCHLD, &sa, NULL);
437 #ifdef VIRTUAL_HOSTING
442 * Open a socket, bind it to the FTP port, and start
445 ctl_sock = socksetup(family, bindname, bindport);
446 if (ctl_sock == NULL)
449 FD_ZERO(&defreadfds);
450 for (i = 1; i <= *ctl_sock; i++) {
451 FD_SET(ctl_sock[i], &defreadfds);
452 if (listen(ctl_sock[i], 32) < 0) {
453 syslog(LOG_ERR, "control listen: %m");
456 if (maxfd < ctl_sock[i])
461 * Loop forever accepting connection requests and forking off
462 * children to handle them.
465 FD_COPY(&defreadfds, &readfds);
466 nfds = select(maxfd + 1, &readfds, NULL, NULL, 0);
468 if (nfds < 0 && errno != EINTR)
469 syslog(LOG_WARNING, "select: %m");
474 for (i = 1; i <= *ctl_sock; i++)
475 if (FD_ISSET(ctl_sock[i], &readfds)) {
476 addrlen = sizeof(his_addr);
477 fd = accept(ctl_sock[i],
478 (struct sockaddr *)&his_addr,
485 switch (pid = fork()) {
491 for (i = 1; i <= *ctl_sock; i++)
497 syslog(LOG_WARNING, "fork: %m");
505 addrlen = sizeof(his_addr);
506 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
507 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
511 #ifdef VIRTUAL_HOSTING
512 if (his_addr.su_family == AF_INET6 &&
513 IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))
516 family = his_addr.su_family;
522 sa.sa_handler = SIG_DFL;
523 sigaction(SIGCHLD, &sa, NULL);
525 sa.sa_handler = sigurg;
526 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
527 sigaction(SIGURG, &sa, NULL);
529 sigfillset(&sa.sa_mask); /* block all signals in handler */
530 sa.sa_flags = SA_RESTART;
531 sa.sa_handler = sigquit;
532 sigaction(SIGHUP, &sa, NULL);
533 sigaction(SIGINT, &sa, NULL);
534 sigaction(SIGQUIT, &sa, NULL);
535 sigaction(SIGTERM, &sa, NULL);
537 sa.sa_handler = lostconn;
538 sigaction(SIGPIPE, &sa, NULL);
540 addrlen = sizeof(ctrl_addr);
541 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
542 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
545 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
546 #ifdef VIRTUAL_HOSTING
547 /* select our identity from virtual host table */
548 selecthost(&ctrl_addr);
551 if (ctrl_addr.su_family == AF_INET)
553 tos = IPTOS_LOWDELAY;
554 if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
555 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
559 * Disable Nagle on the control channel so that we don't have to wait
560 * for peer's ACK before issuing our next reply.
562 if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
563 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
565 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
567 /* set this here so klogin can use it... */
568 snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
570 /* Try to handle urgent data inline */
572 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
573 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
577 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
578 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
580 dolog((struct sockaddr *)&his_addr);
582 * Set up default state
591 /* If logins are disabled, print out the message. */
592 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
593 while (fgets(line, sizeof(line), fd) != NULL) {
594 if ((cp = strchr(line, '\n')) != NULL)
596 lreply(530, "%s", line);
600 reply(530, "System not available.");
603 #ifdef VIRTUAL_HOSTING
604 fd = fopen(thishost->welcome, "r");
606 fd = fopen(_PATH_FTPWELCOME, "r");
609 while (fgets(line, sizeof(line), fd) != NULL) {
610 if ((cp = strchr(line, '\n')) != NULL)
612 lreply(220, "%s", line);
616 /* reply(220,) must follow */
618 #ifndef VIRTUAL_HOSTING
619 if (hostname == NULL) {
620 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
621 fatalerror("Ran out of memory.");
622 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
624 hostname[MAXHOSTNAMELEN - 1] = '\0';
628 reply(220, "%s FTP server (%s) ready.", hostname, version);
630 reply(220, "FTP server ready.");
641 syslog(LOG_DEBUG, "lost connection");
649 syslog(LOG_ERR, "got signal %d", signo);
653 #ifdef VIRTUAL_HOSTING
655 * read in virtual host tables (if they exist)
659 inithosts(int family)
664 char *cp, *mp, *line;
665 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
666 struct ftphost *hrp, *lhrp;
667 struct addrinfo hints, *res, *ai;
670 * Fill in the default host information
672 if (hostname == NULL) {
673 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
674 fatalerror("Ran out of memory.");
675 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
677 hostname[MAXHOSTNAMELEN - 1] = '\0';
679 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
680 fatalerror("Ran out of memory.");
681 hrp->hostname = hostname;
682 hrp->hostinfo = NULL;
684 memset(&hints, 0, sizeof(hints));
685 hints.ai_flags = AI_PASSIVE;
686 hints.ai_family = family;
687 hints.ai_socktype = SOCK_STREAM;
688 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
690 hrp->statfile = _PATH_FTPDSTATFILE;
691 hrp->welcome = _PATH_FTPWELCOME;
692 hrp->loginmsg = _PATH_FTPLOGINMESG;
693 hrp->anonuser = "ftp";
695 thishost = firsthost = lhrp = hrp;
696 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
697 int addrsize, gothost;
701 while ((line = fgetln(fp, &len)) != NULL) {
707 if (line[len - 1] == '\n') {
708 line[len - 1] = '\0';
711 if ((mp = malloc(len + 1)) == NULL)
712 fatalerror("Ran out of memory.");
713 memcpy(mp, line, len);
717 cp = strtok(line, " \t");
718 /* skip empty lines */
725 statfile = _PATH_FTPDSTATFILE;
726 welcome = _PATH_FTPWELCOME;
727 loginmsg = _PATH_FTPLOGINMESG;
730 * Preparse the line so we can use its info
731 * for all the addresses associated with
732 * the virtual host name.
733 * Field 0, the virtual host name, is special:
734 * it's already parsed off and will be strdup'ed
735 * later, after we know its canonical form.
737 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
738 if (*cp != '-' && (cp = strdup(cp)))
740 case 1: /* anon user permissions */
743 case 2: /* statistics file */
746 case 3: /* welcome message */
749 case 4: /* login message */
752 default: /* programming error */
757 hints.ai_flags = AI_PASSIVE;
758 hints.ai_family = family;
759 hints.ai_socktype = SOCK_STREAM;
760 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
762 for (ai = res; ai != NULL && ai->ai_addr != NULL;
766 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
769 for (hi = hrp->hostinfo; hi != NULL;
771 if (hi->ai_addrlen == ai->ai_addrlen &&
774 ai->ai_addr->sa_len) == 0) {
782 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
784 hrp->hostname = NULL;
787 if (hrp->hostinfo && hrp->hostinfo != res)
788 freeaddrinfo(hrp->hostinfo);
789 insert = 0; /* host already in the chain */
794 * determine hostname to use.
795 * force defined name if there is a valid alias
796 * otherwise fallback to primary hostname
798 /* XXX: getaddrinfo() can't do alias check */
799 switch(hrp->hostinfo->ai_family) {
801 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
802 addrsize = sizeof(struct in_addr);
805 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
806 addrsize = sizeof(struct in6_addr);
809 /* should not reach here */
810 freeaddrinfo(hrp->hostinfo);
812 free(hrp); /*not in chain, can free*/
814 hrp->hostinfo = NULL; /*mark as blank*/
818 if ((hp = getipnodebyaddr(addr, addrsize,
819 hrp->hostinfo->ai_family,
820 &hp_error)) != NULL) {
821 if (strcmp(vhost, hp->h_name) != 0) {
822 if (hp->h_aliases == NULL)
826 while (hp->h_aliases[i] &&
827 strcmp(vhost, hp->h_aliases[i]) != 0)
829 if (hp->h_aliases[i] == NULL)
835 strcmp(hrp->hostname, vhost) != 0) {
837 hrp->hostname = NULL;
839 if (hrp->hostname == NULL &&
840 (hrp->hostname = strdup(vhost)) == NULL) {
841 freeaddrinfo(hrp->hostinfo);
842 hrp->hostinfo = NULL; /* mark as blank */
847 hrp->anonuser = anonuser;
848 hrp->statfile = statfile;
849 hrp->welcome = welcome;
850 hrp->loginmsg = loginmsg;
868 selecthost(union sockunion *su)
873 struct in6_addr *mapped_in6 = NULL;
879 * XXX IPv4 mapped IPv6 addr consideraton,
880 * specified in rfc2373.
882 if (su->su_family == AF_INET6 &&
883 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
884 mapped_in6 = &su->su_sin6.sin6_addr;
887 hrp = thishost = firsthost; /* default */
890 while (hrp != NULL) {
891 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
892 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
897 /* XXX IPv4 mapped IPv6 addr consideraton */
898 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
899 (memcmp(&mapped_in6->s6_addr[12],
900 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
901 sizeof(struct in_addr)) == 0)) {
911 /* setup static variables as appropriate */
912 hostname = thishost->hostname;
913 ftpuser = thishost->anonuser;
918 * Helper function for sgetpwnam().
923 char *new = malloc(strlen(s) + 1);
926 reply(421, "Ran out of memory.");
935 * Save the result of a getpwnam. Used for USER command, since
936 * the data returned must not be clobbered by any other command
938 * NB: The data returned by sgetpwnam() will remain valid until
939 * the next call to this function. Its difference from getpwnam()
940 * is that sgetpwnam() is known to be called from ftpd code only.
942 static struct passwd *
943 sgetpwnam(char *name)
945 static struct passwd save;
948 if ((p = getpwnam(name)) == NULL)
952 free(save.pw_passwd);
958 save.pw_name = sgetsave(p->pw_name);
959 save.pw_passwd = sgetsave(p->pw_passwd);
960 save.pw_gecos = sgetsave(p->pw_gecos);
961 save.pw_dir = sgetsave(p->pw_dir);
962 save.pw_shell = sgetsave(p->pw_shell);
966 static int login_attempts; /* number of failed login attempts */
967 static int askpasswd; /* had user command, ask for passwd */
968 static char curname[MAXLOGNAME]; /* current USER name */
972 * Sets global passwd pointer pw if named account exists and is acceptable;
973 * sets askpasswd if a PASS command is expected. If logged in previously,
974 * need to reset state. If name is "ftp" or "anonymous", the name is not in
975 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
976 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
977 * requesting login privileges. Disallow anyone who does not have a standard
978 * shell as returned by getusershell(). Disallow anyone mentioned in the file
979 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
988 reply(530, "Can't change user from guest login.");
990 } else if (dochroot) {
991 reply(530, "Can't change user from chroot user.");
998 #ifdef VIRTUAL_HOSTING
999 pw = sgetpwnam(thishost->anonuser);
1001 pw = sgetpwnam("ftp");
1003 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1004 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL) ||
1005 checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL))
1006 reply(530, "User %s access denied.", name);
1007 else if (pw != NULL) {
1011 "Guest login ok, send your email address as password.");
1013 reply(530, "User %s unknown.", name);
1014 if (!askpasswd && logging)
1016 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1019 if (anon_only != 0) {
1020 reply(530, "Sorry, only anonymous ftp allowed.");
1024 if ((pw = sgetpwnam(name))) {
1025 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1026 shell = _PATH_BSHELL;
1028 while ((cp = getusershell()) != NULL)
1029 if (strcmp(cp, shell) == 0)
1033 if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1, NULL)) {
1034 reply(530, "User %s access denied.", name);
1037 "FTP LOGIN REFUSED FROM %s, %s",
1044 strncpy(curname, name, sizeof(curname)-1);
1048 /* XXX Kluge! The conversation mechanism needs to be fixed. */
1050 if (opiechallenge(&opiedata, name, opieprompt) == 0) {
1051 pwok = (pw != NULL) &&
1052 opieaccessfile(remotehost) &&
1053 opiealways(pw->pw_dir);
1054 reply(331, "Response to %s %s for %s.",
1055 opieprompt, pwok ? "requested" : "required", name);
1058 reply(331, "Password required for %s.", name);
1062 * Delay before reading passwd after first failed
1063 * attempt to slow down passwd-guessing programs.
1066 sleep(login_attempts);
1070 * Check if a user is in the file "fname",
1071 * return a pointer to a malloc'd string with the rest
1072 * of the matching line in "residue" if not NULL.
1075 checkuser(char *fname, char *name, int pwset, char **residue)
1080 char *line, *mp, *p;
1082 if ((fd = fopen(fname, "r")) != NULL) {
1083 while (!found && (line = fgetln(fd, &len)) != NULL) {
1087 if (line[len - 1] == '\n') {
1088 line[len - 1] = '\0';
1091 if ((mp = malloc(len + 1)) == NULL)
1092 fatalerror("Ran out of memory.");
1093 memcpy(mp, line, len);
1097 /* avoid possible leading and trailing whitespace */
1098 p = strtok(line, " \t");
1099 /* skip empty lines */
1103 * if first chr is '@', check group membership
1109 if (p[1] == '\0') /* single @ matches anyone */
1112 if ((grp = getgrnam(p+1)) == NULL)
1115 * Check user's default group
1117 if (pwset && grp->gr_gid == pw->pw_gid)
1120 * Check supplementary groups
1122 while (!found && grp->gr_mem[i])
1123 found = strcmp(name,
1129 * Otherwise, just check for username match
1132 found = strcmp(p, name) == 0;
1134 * Save the rest of line to "residue" if matched
1136 if (found && residue) {
1137 if ((p = strtok(NULL, "")) != NULL)
1138 p += strspn(p, " \t");
1140 if ((*residue = strdup(p)) == NULL)
1141 fatalerror("Ran out of memory.");
1155 * Terminate login as previous user, if any, resetting state;
1156 * used when USER command is given or login fails.
1166 if (logged_in && dowtmp)
1167 ftpd_logwtmp(ttyline, "", NULL);
1170 /* XXX Missing LOGIN_SETMAC */
1171 setusercontext(NULL, getpwuid(0), 0,
1172 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1176 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1177 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1178 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1179 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1180 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1181 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1193 * the following code is stolen from imap-uw PAM authentication module and
1196 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1199 const char *uname; /* user name */
1200 const char *pass; /* password */
1202 typedef struct cred_t cred_t;
1205 auth_conv(int num_msg, const struct pam_message **msg,
1206 struct pam_response **resp, void *appdata)
1209 cred_t *cred = (cred_t *) appdata;
1210 struct pam_response *reply;
1212 reply = calloc(num_msg, sizeof *reply);
1216 for (i = 0; i < num_msg; i++) {
1217 switch (msg[i]->msg_style) {
1218 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1219 reply[i].resp_retcode = PAM_SUCCESS;
1220 reply[i].resp = COPY_STRING(cred->uname);
1221 /* PAM frees resp. */
1223 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1224 reply[i].resp_retcode = PAM_SUCCESS;
1225 reply[i].resp = COPY_STRING(cred->pass);
1226 /* PAM frees resp. */
1230 reply[i].resp_retcode = PAM_SUCCESS;
1231 reply[i].resp = NULL;
1233 default: /* unknown message style */
1235 return PAM_CONV_ERR;
1244 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1245 * authenticated, or 1 if not authenticated. If some sort of PAM system
1246 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1247 * function returns -1. This can be used as an indication that we should
1248 * fall back to a different authentication mechanism.
1251 auth_pam(struct passwd **ppw, const char *pass)
1253 const char *tmpl_user;
1257 cred_t auth_cred = { (*ppw)->pw_name, pass };
1258 struct pam_conv conv = { &auth_conv, &auth_cred };
1260 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1261 if (e != PAM_SUCCESS) {
1263 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1264 * if context creation has failed in the first place.
1266 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
1270 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1271 if (e != PAM_SUCCESS) {
1272 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1273 pam_strerror(pamh, e));
1274 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1275 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1281 e = pam_authenticate(pamh, 0);
1285 * With PAM we support the concept of a "template"
1286 * user. The user enters a login name which is
1287 * authenticated by PAM, usually via a remote service
1288 * such as RADIUS or TACACS+. If authentication
1289 * succeeds, a different but related "template" name
1290 * is used for setting the credentials, shell, and
1291 * home directory. The name the user enters need only
1292 * exist on the remote authentication server, but the
1293 * template name must be present in the local password
1296 * This is supported by two various mechanisms in the
1297 * individual modules. However, from the application's
1298 * point of view, the template user is always passed
1299 * back as a changed value of the PAM_USER item.
1301 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1303 tmpl_user = (const char *) item;
1304 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1305 *ppw = getpwnam(tmpl_user);
1307 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1308 pam_strerror(pamh, e));
1313 case PAM_USER_UNKNOWN:
1319 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1325 e = pam_acct_mgmt(pamh, 0);
1326 if (e != PAM_SUCCESS) {
1327 syslog(LOG_ERR, "pam_acct_mgmt: %s",
1328 pam_strerror(pamh, e));
1334 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1335 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1342 #endif /* USE_PAM */
1350 login_cap_t *lc = NULL;
1355 char *residue = NULL;
1358 if (logged_in || askpasswd == 0) {
1359 reply(503, "Login with USER first.");
1363 if (!guest) { /* "ftp" is only account allowed no password */
1365 rval = 1; /* failure below */
1369 rval = auth_pam(&pw, passwd);
1375 if (opieverify(&opiedata, passwd) == 0)
1376 xpasswd = pw->pw_passwd;
1378 xpasswd = crypt(passwd, pw->pw_passwd);
1379 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1385 rval = strcmp(pw->pw_passwd, xpasswd);
1386 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1387 rval = 1; /* failure */
1390 * If rval == 1, the user failed the authentication check
1391 * above. If rval == 0, either PAM or local authentication
1395 reply(530, "Login incorrect.");
1398 "FTP LOGIN FAILED FROM %s",
1400 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1401 "FTP LOGIN FAILED FROM %s, %s",
1402 remotehost, curname);
1405 if (login_attempts++ >= 5) {
1407 "repeated login failures from %s",
1414 login_attempts = 0; /* this time successful */
1415 if (setegid(pw->pw_gid) < 0) {
1416 reply(550, "Can't set gid.");
1419 /* May be overridden by login.conf */
1422 if ((lc = login_getpwclass(pw)) != NULL) {
1423 char remote_ip[NI_MAXHOST];
1425 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1426 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1429 remote_ip[sizeof(remote_ip) - 1] = 0;
1430 if (!auth_hostok(lc, remotehost, remote_ip)) {
1431 syslog(LOG_INFO|LOG_AUTH,
1432 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1434 reply(530, "Permission denied.");
1438 if (!auth_timeok(lc, time(NULL))) {
1439 reply(530, "Login not available right now.");
1444 /* XXX Missing LOGIN_SETMAC */
1445 setusercontext(lc, pw, 0,
1446 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1447 LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1449 setlogin(pw->pw_name);
1450 initgroups(pw->pw_name, pw->pw_gid);
1455 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1456 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1457 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1458 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1463 /* open wtmp before chroot */
1465 ftpd_logwtmp(ttyline, pw->pw_name,
1466 (struct sockaddr *)&his_addr);
1469 if (guest && stats && statfd < 0)
1470 #ifdef VIRTUAL_HOSTING
1471 statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1473 statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1479 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue)
1480 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1481 || login_getcapbool(lc, "ftp-chroot", 0)
1486 * For a chrooted local user,
1487 * a) see whether ftpchroot(5) specifies a chroot directory,
1488 * b) extract the directory pathname from the line,
1489 * c) expand it to the absolute pathname if necessary.
1491 if (dochroot && residue &&
1492 (chrootdir = strtok(residue, " \t")) != NULL) {
1493 if (chrootdir[0] != '/')
1494 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1496 chrootdir = strdup(chrootdir); /* make it permanent */
1497 if (chrootdir == NULL)
1498 fatalerror("Ran out of memory.");
1500 if (guest || dochroot) {
1502 * If no chroot directory set yet, use the login directory.
1503 * Copy it so it can be modified while pw->pw_dir stays intact.
1505 if (chrootdir == NULL &&
1506 (chrootdir = strdup(pw->pw_dir)) == NULL)
1507 fatalerror("Ran out of memory.");
1509 * Check for the "/chroot/./home" syntax,
1510 * separate the chroot and home directory pathnames.
1512 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1513 *(homedir++) = '\0'; /* wipe '/' */
1514 homedir++; /* skip '.' */
1517 * We MUST do a chdir() after the chroot. Otherwise
1518 * the old current directory will be accessible as "."
1519 * outside the new root!
1524 * Finally, do chroot()
1526 if (chroot(chrootdir) < 0) {
1527 reply(550, "Can't change root.");
1530 } else /* real user w/o chroot */
1531 homedir = pw->pw_dir;
1533 * Set euid *before* doing chdir() so
1534 * a) the user won't be carried to a directory that he couldn't reach
1535 * on his own due to no permission to upper path components,
1536 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1537 * (uid 0 has no root power over NFS if not mapped explicitly.)
1539 if (seteuid(pw->pw_uid) < 0) {
1540 reply(550, "Can't set uid.");
1543 if (chdir(homedir) < 0) {
1544 if (guest || dochroot) {
1545 reply(550, "Can't change to base directory.");
1548 if (chdir("/") < 0) {
1549 reply(550, "Root is inaccessible.");
1552 lreply(230, "No directory! Logging in with home=/.");
1557 * Display a login message, if it exists.
1558 * N.B. reply(230,) must follow the message.
1560 #ifdef VIRTUAL_HOSTING
1561 fd = fopen(thishost->loginmsg, "r");
1563 fd = fopen(_PATH_FTPLOGINMESG, "r");
1566 char *cp, line[LINE_MAX];
1568 while (fgets(line, sizeof(line), fd) != NULL) {
1569 if ((cp = strchr(line, '\n')) != NULL)
1571 lreply(230, "%s", line);
1579 ident = strdup(passwd);
1581 fatalerror("Ran out of memory.");
1583 reply(230, "Guest login ok, access restrictions apply.");
1585 #ifdef VIRTUAL_HOSTING
1586 if (thishost != firsthost)
1587 snprintf(proctitle, sizeof(proctitle),
1588 "%s: anonymous(%s)/%s", remotehost, hostname,
1592 snprintf(proctitle, sizeof(proctitle),
1593 "%s: anonymous/%s", remotehost, passwd);
1594 setproctitle("%s", proctitle);
1595 #endif /* SETPROCTITLE */
1597 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1598 remotehost, passwd);
1601 reply(230, "User %s logged in, "
1602 "access restrictions apply.", pw->pw_name);
1604 reply(230, "User %s logged in.", pw->pw_name);
1607 snprintf(proctitle, sizeof(proctitle),
1608 "%s: user/%s", remotehost, pw->pw_name);
1609 setproctitle("%s", proctitle);
1610 #endif /* SETPROCTITLE */
1612 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1613 remotehost, pw->pw_name);
1615 if (logging && (guest || dochroot))
1616 syslog(LOG_INFO, "session root changed to %s", chrootdir);
1624 /* Forget all about it... */
1634 retrieve(char *cmd, char *name)
1638 int (*closefunc)(FILE *);
1642 fin = fopen(name, "r"), closefunc = fclose;
1647 snprintf(line, sizeof(line), cmd, name), name = line;
1648 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1650 st.st_blksize = BUFSIZ;
1654 perror_reply(550, name);
1656 LOGCMD("get", name);
1663 if (fstat(fileno(fin), &st) < 0) {
1664 perror_reply(550, name);
1667 if (!S_ISREG(st.st_mode)) {
1669 * Never sending a raw directory is a workaround
1670 * for buggy clients that will attempt to RETR
1671 * a directory before listing it, e.g., Mozilla.
1672 * Preventing a guest from getting irregular files
1673 * is a simple security measure.
1675 if (S_ISDIR(st.st_mode) || guest) {
1676 reply(550, "%s: not a plain file.", name);
1680 /* st.st_blksize is set for all descriptor types */
1683 if (restart_point) {
1684 if (type == TYPE_A) {
1691 if ((c=getc(fin)) == EOF) {
1692 perror_reply(550, name);
1698 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1699 perror_reply(550, name);
1703 dout = dataconn(name, st.st_size, "w");
1707 send_data(fin, dout, st.st_blksize, st.st_size,
1708 restart_point == 0 && cmd == NULL && S_ISREG(st.st_mode));
1709 if (cmd == NULL && guest && stats && byte_count > 0)
1710 logxfer(name, byte_count, start);
1716 LOGBYTES("get", name, byte_count);
1721 store(char *name, char *mode, int unique)
1725 int (*closefunc)(FILE *);
1727 if (*mode == 'a') { /* APPE */
1729 /* Programming error */
1730 syslog(LOG_ERR, "Internal: unique flag to APPE");
1733 if (guest && noguestmod) {
1734 reply(550, "Appending to existing file denied.");
1737 restart_point = 0; /* not affected by preceding REST */
1739 if (unique) /* STOU overrides REST */
1741 if (guest && noguestmod) {
1742 if (restart_point) { /* guest STOR w/REST */
1743 reply(550, "Modifying existing file denied.");
1745 } else /* treat guest STOR as STOU */
1750 mode = "r+"; /* so ASCII manual seek can work */
1752 if ((fd = guniquefd(name, &name)) < 0)
1754 fout = fdopen(fd, mode);
1756 fout = fopen(name, mode);
1759 perror_reply(553, name);
1763 if (restart_point) {
1764 if (type == TYPE_A) {
1771 if ((c=getc(fout)) == EOF) {
1772 perror_reply(550, name);
1779 * We must do this seek to "current" position
1780 * because we are changing from reading to
1783 if (fseeko(fout, 0, SEEK_CUR) < 0) {
1784 perror_reply(550, name);
1787 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1788 perror_reply(550, name);
1792 din = dataconn(name, -1, "r");
1795 if (receive_data(din, fout) == 0) {
1797 reply(226, "Transfer complete (unique file name:%s).",
1800 reply(226, "Transfer complete.");
1806 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1810 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1815 getdatasock(char *mode)
1817 int on = 1, s, t, tries;
1820 return (fdopen(data, mode));
1822 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1825 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1826 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1827 /* anchor socket to avoid multi-homing problems */
1828 data_source = ctrl_addr;
1829 data_source.su_port = htons(dataport);
1831 for (tries = 1; ; tries++) {
1833 * We should loop here since it's possible that
1834 * another ftpd instance has passed this point and is
1835 * trying to open a data connection in active mode now.
1836 * Until the other connection is opened, we'll be getting
1837 * EADDRINUSE because no SOCK_STREAM sockets in the system
1838 * can share both local and remote addresses, localIP:20
1839 * and *:* in this case.
1841 if (bind(s, (struct sockaddr *)&data_source,
1842 data_source.su_len) >= 0)
1844 if (errno != EADDRINUSE || tries > 10)
1848 seteuid(pw->pw_uid);
1850 if (data_source.su_family == AF_INET)
1852 on = IPTOS_THROUGHPUT;
1853 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1854 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1859 * Turn off push flag to keep sender TCP from sending short packets
1860 * at the boundaries of each write().
1863 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1864 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1866 return (fdopen(s, mode));
1868 /* Return the real value of errno (close may change it) */
1870 seteuid(pw->pw_uid);
1877 dataconn(char *name, off_t size, char *mode)
1881 int retry = 0, tos, conerrno;
1886 snprintf(sizebuf, sizeof(sizebuf),
1887 " (%jd bytes)", (intmax_t)size);
1891 union sockunion from;
1892 socklen_t fromlen = ctrl_addr.su_len;
1894 struct timeval timeout;
1898 FD_SET(pdata, &set);
1900 timeout.tv_usec = 0;
1901 timeout.tv_sec = 120;
1904 * Granted a socket is in the blocking I/O mode,
1905 * accept() will block after a successful select()
1906 * if the selected connection dies in between.
1907 * Therefore set the non-blocking I/O flag here.
1909 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1910 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1912 if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
1913 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1918 * Unset the inherited non-blocking I/O flag
1919 * on the child socket so stdio can work on it.
1921 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1922 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1925 if (from.su_family == AF_INET)
1927 tos = IPTOS_THROUGHPUT;
1928 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1929 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1932 reply(150, "Opening %s mode data connection for '%s'%s.",
1933 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1934 return (fdopen(pdata, mode));
1936 reply(425, "Can't open data connection.");
1942 reply(125, "Using existing data connection for '%s'%s.",
1945 return (fdopen(data, mode));
1948 data_dest = his_addr;
1951 file = getdatasock(mode);
1953 char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
1955 if (getnameinfo((struct sockaddr *)&data_source,
1957 hostbuf, sizeof(hostbuf) - 1,
1958 portbuf, sizeof(portbuf) - 1,
1959 NI_NUMERICHOST|NI_NUMERICSERV))
1960 *hostbuf = *portbuf = 0;
1961 hostbuf[sizeof(hostbuf) - 1] = 0;
1962 portbuf[sizeof(portbuf) - 1] = 0;
1963 reply(425, "Can't create data socket (%s,%s): %s.",
1964 hostbuf, portbuf, strerror(errno));
1967 data = fileno(file);
1969 if (connect(data, (struct sockaddr *)&data_dest,
1970 data_dest.su_len) == 0)
1975 if (conerrno == EADDRINUSE) {
1981 } while (retry <= swaitmax);
1982 if (conerrno != 0) {
1983 reply(425, "Can't build data connection: %s.",
1984 strerror(conerrno));
1987 reply(150, "Opening %s mode data connection for '%s'%s.",
1988 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1993 * A helper macro to avoid code duplication
1994 * in send_data() and receive_data().
1996 * XXX We have to block SIGURG during putc() because BSD stdio
1997 * is unable to restart interrupted write operations and hence
1998 * the entire buffer contents will be lost as soon as a write()
1999 * call indicates EINTR to stdio.
2001 #define FTPD_PUTC(ch, file, label) \
2007 ret = putc((ch), (file)); \
2009 CHECKOOB(return (-1)) \
2010 else if (ferror(file)) \
2013 } while (ret == EOF); \
2017 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
2018 * encapsulation of the data subject to Mode, Structure, and Type.
2020 * NB: Form isn't handled.
2023 send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2025 int c, cp, filefd, netfd;
2036 CHECKOOB(return (-1))
2037 else if (c == EOF && ferror(instr))
2040 if (ferror(instr)) { /* resume after OOB */
2044 if (feof(instr)) /* EOF */
2046 syslog(LOG_ERR, "Internal: impossible condition"
2047 " on file after getc()");
2050 if (c == '\n' && cp != '\r') {
2051 FTPD_PUTC('\r', outstr, data_err);
2054 FTPD_PUTC(c, outstr, data_err);
2058 #ifdef notyet /* BSD stdio isn't ready for that */
2059 while (fflush(outstr) == EOF) {
2060 CHECKOOB(return (-1))
2068 if (fflush(outstr) == EOF)
2071 reply(226, "Transfer complete.");
2077 * isreg is only set if we are not doing restart and we
2078 * are sending a regular file
2080 netfd = fileno(outstr);
2081 filefd = fileno(instr);
2084 char *msg = "Transfer complete.";
2090 while (filesize > 0) {
2091 err = sendfile(filefd, netfd, offset, 0,
2094 * Calculate byte_count before OOB processing.
2095 * It can be used in myoob() later.
2100 CHECKOOB(return (-1))
2101 else if (err == -1) {
2102 if (errno != EINTR &&
2103 cnt == 0 && offset == 0)
2107 if (err == -1) /* resume after OOB */
2110 * We hit the EOF prematurely.
2111 * Perhaps the file was externally truncated.
2114 msg = "Transfer finished due to "
2115 "premature end of file.";
2125 if ((buf = malloc(blksize)) == NULL) {
2127 reply(451, "Ran out of memory.");
2135 cnt = read(filefd, buf, blksize);
2136 CHECKOOB(free(buf); return (-1))
2141 if (cnt < 0) /* resume after OOB */
2143 if (cnt == 0) /* EOF */
2145 for (len = cnt, bp = buf; len > 0;) {
2146 cnt = write(netfd, bp, len);
2147 CHECKOOB(free(buf); return (-1))
2161 reply(226, "Transfer complete.");
2165 reply(550, "Unimplemented TYPE %d in send_data.", type);
2171 perror_reply(426, "Data connection");
2176 perror_reply(551, "Error on input file");
2181 * Transfer data from peer to "outstr" using the appropriate encapulation of
2182 * the data subject to Mode, Structure, and Type.
2184 * N.B.: Form isn't handled.
2187 receive_data(FILE *instr, FILE *outstr)
2203 cnt = read(fileno(instr), buf, sizeof(buf));
2204 CHECKOOB(return (-1))
2207 if (cnt < 0) /* resume after OOB */
2209 if (cnt == 0) /* EOF */
2211 for (len = cnt, bp = buf; len > 0;) {
2212 cnt = write(fileno(outstr), bp, len);
2213 CHECKOOB(return (-1))
2228 reply(553, "TYPE E not implemented.");
2235 CHECKOOB(return (-1))
2236 else if (c == EOF && ferror(instr))
2238 if (c == EOF && ferror(instr)) { /* resume after OOB */
2245 FTPD_PUTC('\r', outstr, file_err);
2255 /* Check for EOF here in order not to lose last \r. */
2257 if (feof(instr)) /* EOF */
2259 syslog(LOG_ERR, "Internal: impossible condition"
2260 " on data stream after getc()");
2265 FTPD_PUTC(c, outstr, file_err);
2268 #ifdef notyet /* BSD stdio isn't ready for that */
2269 while (fflush(outstr) == EOF) {
2270 CHECKOOB(return (-1))
2278 if (fflush(outstr) == EOF)
2283 "WARNING! %d bare linefeeds received in ASCII mode.",
2285 printf(" File may not have transferred correctly.\r\n");
2290 reply(550, "Unimplemented TYPE %d in receive_data.", type);
2296 perror_reply(426, "Data connection");
2301 perror_reply(452, "Error writing to file");
2306 statfilecmd(char *filename)
2311 char line[LINE_MAX];
2314 code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2315 snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2316 fin = ftpd_popen(line, "r");
2317 lreply(code, "Status of %s:", filename);
2319 while ((c = getc(fin)) != EOF) {
2321 if (ferror(stdout)){
2322 perror_reply(421, "Control connection");
2328 perror_reply(551, filename);
2335 * RFC 959 says neutral text should be prepended before
2336 * a leading 3-digit number followed by whitespace, but
2337 * many ftp clients can be confused by any leading digits,
2338 * as a matter of fact.
2340 if (atstart && isdigit(c))
2343 atstart = (c == '\n');
2346 reply(code, "End of status.");
2352 union sockunion *su;
2354 char hname[NI_MAXHOST];
2358 lreply(211, "%s FTP server status:", hostname);
2359 printf(" %s\r\n", version);
2361 lreply(211, "FTP server status:");
2362 printf(" Connected to %s", remotehost);
2363 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2364 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2365 hname[sizeof(hname) - 1] = 0;
2366 if (strcmp(hname, remotehost) != 0)
2367 printf(" (%s)", hname);
2372 printf(" Logged in anonymously\r\n");
2374 printf(" Logged in as %s\r\n", pw->pw_name);
2375 } else if (askpasswd)
2376 printf(" Waiting for password\r\n");
2378 printf(" Waiting for user name\r\n");
2379 printf(" TYPE: %s", typenames[type]);
2380 if (type == TYPE_A || type == TYPE_E)
2381 printf(", FORM: %s", formnames[form]);
2384 printf(" %d", CHAR_BIT);
2386 printf(" %d", bytesize); /* need definition! */
2388 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2389 strunames[stru], modenames[mode]);
2391 printf(" Data connection open\r\n");
2392 else if (pdata != -1) {
2396 } else if (usedefault == 0) {
2400 #define UC(b) (((int) b) & 0xff)
2402 printf(" EPSV only mode (EPSV ALL)\r\n");
2407 if (su->su_family == AF_INET) {
2408 a = (u_char *) &su->su_sin.sin_addr;
2409 p = (u_char *) &su->su_sin.sin_port;
2410 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2411 ispassive ? "PASV" : "PORT",
2412 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2413 UC(p[0]), UC(p[1]));
2420 switch (su->su_family) {
2422 a = (u_char *) &su->su_sin.sin_addr;
2423 p = (u_char *) &su->su_sin.sin_port;
2424 alen = sizeof(su->su_sin.sin_addr);
2428 a = (u_char *) &su->su_sin6.sin6_addr;
2429 p = (u_char *) &su->su_sin6.sin6_port;
2430 alen = sizeof(su->su_sin6.sin6_addr);
2438 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2440 for (i = 0; i < alen; i++)
2441 printf("%d,", UC(a[i]));
2442 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2451 switch (su->su_family) {
2463 union sockunion tmp;
2466 if (tmp.su_family == AF_INET6)
2467 tmp.su_sin6.sin6_scope_id = 0;
2468 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2469 hname, sizeof(hname) - 1, NULL, 0,
2471 hname[sizeof(hname) - 1] = 0;
2472 printf(" %s |%d|%s|%d|\r\n",
2473 ispassive ? "EPSV" : "EPRT",
2474 af, hname, htons(tmp.su_port));
2480 printf(" No data connection\r\n");
2481 reply(211, "End of status.");
2488 reply(451, "Error in server: %s", s);
2489 reply(221, "Closing connection due to server error.");
2495 reply(int n, const char *fmt, ...)
2506 syslog(LOG_DEBUG, "<--- %d ", n);
2508 vsyslog(LOG_DEBUG, fmt, ap);
2514 lreply(int n, const char *fmt, ...)
2525 syslog(LOG_DEBUG, "<--- %d- ", n);
2527 vsyslog(LOG_DEBUG, fmt, ap);
2536 reply(250, "%s command successful.", s);
2543 reply(502, "%s command not implemented.", s);
2552 if ((cp = strchr(cbuf,'\n')))
2554 reply(500, "%s: command not understood.", cbuf);
2562 LOGCMD("delete", name);
2563 if (lstat(name, &st) < 0) {
2564 perror_reply(550, name);
2567 if (S_ISDIR(st.st_mode)) {
2568 if (rmdir(name) < 0) {
2569 perror_reply(550, name);
2574 if (guest && noguestmod) {
2575 reply(550, "Operation not permitted.");
2578 if (unlink(name) < 0) {
2579 perror_reply(550, name);
2590 if (chdir(path) < 0)
2591 perror_reply(550, path);
2601 LOGCMD("mkdir", name);
2602 if (guest && noguestmkd)
2603 reply(550, "Operation not permitted.");
2604 else if (mkdir(name, 0777) < 0)
2605 perror_reply(550, name);
2607 if ((s = doublequote(name)) == NULL)
2608 fatalerror("Ran out of memory.");
2609 reply(257, "\"%s\" directory created.", s);
2615 removedir(char *name)
2618 LOGCMD("rmdir", name);
2619 if (rmdir(name) < 0)
2620 perror_reply(550, name);
2628 char *s, path[MAXPATHLEN + 1];
2630 if (getcwd(path, sizeof(path)) == NULL)
2631 perror_reply(550, "Get current directory");
2633 if ((s = doublequote(path)) == NULL)
2634 fatalerror("Ran out of memory.");
2635 reply(257, "\"%s\" is current directory.", s);
2641 renamefrom(char *name)
2645 if (guest && noguestmod) {
2646 reply(550, "Operation not permitted.");
2649 if (lstat(name, &st) < 0) {
2650 perror_reply(550, name);
2653 reply(350, "File exists, ready for destination name.");
2658 renamecmd(char *from, char *to)
2662 LOGCMD2("rename", from, to);
2664 if (guest && (stat(to, &st) == 0)) {
2665 reply(550, "%s: permission denied.", to);
2669 if (rename(from, to) < 0)
2670 perror_reply(550, "rename");
2676 dolog(struct sockaddr *who)
2678 char who_name[NI_MAXHOST];
2680 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2681 remotehost[sizeof(remotehost) - 1] = 0;
2682 if (getnameinfo(who, who->sa_len,
2683 who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
2685 who_name[sizeof(who_name) - 1] = 0;
2688 #ifdef VIRTUAL_HOSTING
2689 if (thishost != firsthost)
2690 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2691 remotehost, hostname);
2694 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2696 setproctitle("%s", proctitle);
2697 #endif /* SETPROCTITLE */
2700 #ifdef VIRTUAL_HOSTING
2701 if (thishost != firsthost)
2702 syslog(LOG_INFO, "connection from %s (%s) to %s",
2703 remotehost, who_name, hostname);
2706 syslog(LOG_INFO, "connection from %s (%s)",
2707 remotehost, who_name);
2712 * Record logout in wtmp file
2713 * and exit with supplied status.
2716 dologout(int status)
2719 if (logged_in && dowtmp) {
2721 ftpd_logwtmp(ttyline, "", NULL);
2723 /* beware of flushing buffers after a SIGPIPE */
2741 syslog(LOG_ERR, "Internal: maskurg() while no transfer");
2746 sigaddset(&sset, SIGURG);
2747 sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
2757 syslog(LOG_ERR, "Internal: flagxfer(1): "
2758 "transfer already under way");
2764 syslog(LOG_ERR, "Internal: flagxfer(0): "
2765 "no active transfer");
2772 * Returns 0 if OK to resume or -1 if abort requested.
2781 syslog(LOG_ERR, "Internal: myoob() while no transfer");
2785 ret = getline(cp, 7, stdin);
2787 reply(221, "You could at least say goodbye.");
2789 } else if (ret == -2) {
2790 /* Ignore truncated command. */
2794 if (strcmp(cp, "ABOR\r\n") == 0) {
2796 reply(426, "Transfer aborted. Data connection closed.");
2797 reply(226, "Abort successful.");
2800 if (strcmp(cp, "STAT\r\n") == 0) {
2802 if (file_size != -1)
2803 reply(213, "Status: %jd of %jd bytes transferred.",
2804 (intmax_t)byte_count, (intmax_t)file_size);
2806 reply(213, "Status: %jd bytes transferred.",
2807 (intmax_t)byte_count);
2813 * Note: a response of 425 is not mentioned as a possible response to
2814 * the PASV command in RFC959. However, it has been blessed as
2815 * a legitimate response by Jon Postel in a telephone conversation
2816 * with Rick Adams on 25 Jan 89.
2825 if (pdata >= 0) /* close old port if one set */
2828 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2830 perror_reply(425, "Can't open passive connection");
2834 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2835 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2840 if (ctrl_addr.su_family == AF_INET) {
2841 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2842 : IP_PORTRANGE_DEFAULT;
2844 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2845 &on, sizeof(on)) < 0)
2849 #ifdef IPV6_PORTRANGE
2850 if (ctrl_addr.su_family == AF_INET6) {
2851 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2852 : IPV6_PORTRANGE_DEFAULT;
2854 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2855 &on, sizeof(on)) < 0)
2860 pasv_addr = ctrl_addr;
2861 pasv_addr.su_port = 0;
2862 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2865 seteuid(pw->pw_uid);
2867 len = sizeof(pasv_addr);
2868 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2870 if (listen(pdata, 1) < 0)
2872 if (pasv_addr.su_family == AF_INET)
2873 a = (char *) &pasv_addr.su_sin.sin_addr;
2874 else if (pasv_addr.su_family == AF_INET6 &&
2875 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2876 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2880 p = (char *) &pasv_addr.su_port;
2882 #define UC(b) (((int) b) & 0xff)
2884 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2885 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2889 seteuid(pw->pw_uid);
2892 perror_reply(425, "Can't open passive connection");
2897 * Long Passive defined in RFC 1639.
2898 * 228 Entering Long Passive Mode
2899 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2903 long_passive(char *cmd, int pf)
2909 if (pdata >= 0) /* close old port if one set */
2912 if (pf != PF_UNSPEC) {
2913 if (ctrl_addr.su_family != pf) {
2914 switch (ctrl_addr.su_family) {
2927 * only EPRT/EPSV ready clients will understand this
2929 if (strcmp(cmd, "EPSV") == 0 && pf) {
2930 reply(522, "Network protocol mismatch, "
2933 reply(501, "Network protocol mismatch."); /*XXX*/
2939 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2941 perror_reply(425, "Can't open passive connection");
2945 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2946 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2950 pasv_addr = ctrl_addr;
2951 pasv_addr.su_port = 0;
2952 len = pasv_addr.su_len;
2955 if (ctrl_addr.su_family == AF_INET) {
2956 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2957 : IP_PORTRANGE_DEFAULT;
2959 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2960 &on, sizeof(on)) < 0)
2964 #ifdef IPV6_PORTRANGE
2965 if (ctrl_addr.su_family == AF_INET6) {
2966 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2967 : IPV6_PORTRANGE_DEFAULT;
2969 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2970 &on, sizeof(on)) < 0)
2975 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2978 seteuid(pw->pw_uid);
2980 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2982 if (listen(pdata, 1) < 0)
2985 #define UC(b) (((int) b) & 0xff)
2987 if (strcmp(cmd, "LPSV") == 0) {
2988 p = (char *)&pasv_addr.su_port;
2989 switch (pasv_addr.su_family) {
2991 a = (char *) &pasv_addr.su_sin.sin_addr;
2994 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2995 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2996 2, UC(p[0]), UC(p[1]));
2999 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
3000 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
3003 a = (char *) &pasv_addr.su_sin6.sin6_addr;
3005 "Entering Long Passive Mode "
3006 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3007 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3008 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3009 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3010 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3011 2, UC(p[0]), UC(p[1]));
3014 } else if (strcmp(cmd, "EPSV") == 0) {
3015 switch (pasv_addr.su_family) {
3018 reply(229, "Entering Extended Passive Mode (|||%d|)",
3019 ntohs(pasv_addr.su_port));
3023 /* more proper error code? */
3027 seteuid(pw->pw_uid);
3030 perror_reply(425, "Can't open passive connection");
3035 * Generate unique name for file with basename "local"
3036 * and open the file in order to avoid possible races.
3037 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3038 * Return descriptor to the file, set "name" to its name.
3040 * Generates failure reply on error.
3043 guniquefd(char *local, char **name)
3045 static char new[MAXPATHLEN];
3051 cp = strrchr(local, '/');
3054 if (stat(cp ? local : ".", &st) < 0) {
3055 perror_reply(553, cp ? local : ".");
3060 * Let not overwrite dirname with counter suffix.
3062 * In this extreme case dot won't be put in front of suffix.
3064 if (strlen(local) > sizeof(new) - 4) {
3065 reply(553, "Pathname too long.");
3070 /* -4 is for the .nn<null> we put on the end below */
3071 snprintf(new, sizeof(new) - 4, "%s", local);
3072 cp = new + strlen(new);
3074 * Don't generate dotfile unless requested explicitly.
3075 * This covers the case when basename gets truncated off
3078 if (cp > new && cp[-1] != '/')
3080 for (count = 0; count < 100; count++) {
3081 /* At count 0 try unmodified name */
3083 sprintf(cp, "%d", count);
3084 if ((fd = open(count ? new : local,
3085 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3086 *name = count ? new : local;
3089 if (errno != EEXIST) {
3090 perror_reply(553, count ? new : local);
3094 reply(452, "Unique file name cannot be created.");
3099 * Format and send reply containing system error number.
3102 perror_reply(int code, char *string)
3105 reply(code, "%s: %s.", string, strerror(errno));
3108 static char *onefile[] = {
3114 send_file_list(char *whichf)
3120 char **dirlist, *dirname;
3125 if (strpbrk(whichf, "~{[*?") != NULL) {
3126 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3128 memset(&gl, 0, sizeof(gl));
3129 gl.gl_matchc = MAXGLOBARGS;
3130 /*flags |= GLOB_LIMIT;*/
3132 if (glob(whichf, flags, 0, &gl)) {
3133 reply(550, "No matching files found.");
3135 } else if (gl.gl_pathc == 0) {
3137 perror_reply(550, whichf);
3140 dirlist = gl.gl_pathv;
3142 onefile[0] = whichf;
3147 while ((dirname = *dirlist++)) {
3148 if (stat(dirname, &st) < 0) {
3150 * If user typed "ls -l", etc, and the client
3151 * used NLST, do what the user meant.
3153 if (dirname[0] == '-' && *dirlist == NULL &&
3155 retrieve(_PATH_LS " %s", dirname);
3157 perror_reply(550, whichf);
3161 if (S_ISREG(st.st_mode)) {
3163 dout = dataconn("file list", -1, "w");
3169 fprintf(dout, "%s%s\n", dirname,
3170 type == TYPE_A ? "\r" : "");
3174 byte_count += strlen(dirname) +
3175 (type == TYPE_A ? 2 : 1);
3176 CHECKOOB(goto abrt);
3178 } else if (!S_ISDIR(st.st_mode))
3181 if ((dirp = opendir(dirname)) == NULL)
3184 while ((dir = readdir(dirp)) != NULL) {
3185 char nbuf[MAXPATHLEN];
3187 CHECKOOB(goto abrt);
3189 if (strcmp(dir->d_name, ".") == 0)
3191 if (strcmp(dir->d_name, "..") == 0)
3194 snprintf(nbuf, sizeof(nbuf),
3195 "%s/%s", dirname, dir->d_name);
3198 * We have to do a stat to insure it's
3199 * not a directory or special file.
3201 if (simple || (stat(nbuf, &st) == 0 &&
3202 S_ISREG(st.st_mode))) {
3204 dout = dataconn("file list", -1, "w");
3210 if (nbuf[0] == '.' && nbuf[1] == '/')
3211 fprintf(dout, "%s%s\n", &nbuf[2],
3212 type == TYPE_A ? "\r" : "");
3214 fprintf(dout, "%s%s\n", nbuf,
3215 type == TYPE_A ? "\r" : "");
3219 byte_count += strlen(nbuf) +
3220 (type == TYPE_A ? 2 : 1);
3221 CHECKOOB(goto abrt);
3229 reply(550, "No files found.");
3230 else if (ferror(dout))
3231 data_err: perror_reply(550, "Data connection");
3233 reply(226, "Transfer complete.");
3251 reapchild(int signo)
3253 while (waitpid(-1, NULL, WNOHANG) > 0);
3257 appendf(char **strp, char *fmt, ...)
3263 vasprintf(&p, fmt, ap);
3266 fatalerror("Ran out of memory.");
3271 asprintf(strp, "%s%s", ostr, p);
3273 fatalerror("Ran out of memory.");
3279 logcmd(char *cmd, char *file1, char *file2, off_t cnt)
3282 char wd[MAXPATHLEN + 1];
3287 if (getcwd(wd, sizeof(wd) - 1) == NULL)
3288 strcpy(wd, strerror(errno));
3290 appendf(&msg, "%s", cmd);
3292 appendf(&msg, " %s", file1);
3294 appendf(&msg, " %s", file2);
3296 appendf(&msg, " = %jd bytes", (intmax_t)cnt);
3297 appendf(&msg, " (wd: %s", wd);
3298 if (guest || dochroot)
3299 appendf(&msg, "; chrooted");
3301 syslog(LOG_INFO, "%s", msg);
3306 logxfer(char *name, off_t size, time_t start)
3308 char buf[MAXPATHLEN + 1024];
3309 char path[MAXPATHLEN + 1];
3314 if (realpath(name, path) == NULL) {
3315 syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
3318 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n",
3319 ctime(&now)+4, ident, remotehost,
3320 path, (intmax_t)size,
3321 (long)(now - start + (now == start)));
3322 write(statfd, buf, strlen(buf));
3327 doublequote(char *s)
3332 for (p = s, n = 0; *p; p++)
3336 if ((s2 = malloc(p - s + n + 1)) == NULL)
3339 for (p = s2; *s; s++, p++) {
3340 if ((*p = *s) == '"')
3348 /* setup server socket for specified address family */
3349 /* if af is PF_UNSPEC more than one socket may be returned */
3350 /* the returned list is dynamically allocated, so caller needs to free it */
3352 socksetup(int af, char *bindname, const char *bindport)
3354 struct addrinfo hints, *res, *r;
3355 int error, maxs, *s, *socks;
3358 memset(&hints, 0, sizeof(hints));
3359 hints.ai_flags = AI_PASSIVE;
3360 hints.ai_family = af;
3361 hints.ai_socktype = SOCK_STREAM;
3362 error = getaddrinfo(bindname, bindport, &hints, &res);
3364 syslog(LOG_ERR, "%s", gai_strerror(error));
3365 if (error == EAI_SYSTEM)
3366 syslog(LOG_ERR, "%s", strerror(errno));
3370 /* Count max number of sockets we may open */
3371 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3373 socks = malloc((maxs + 1) * sizeof(int));
3376 syslog(LOG_ERR, "couldn't allocate memory for sockets");
3380 *socks = 0; /* num of sockets counter at start of array */
3382 for (r = res; r; r = r->ai_next) {
3383 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3385 syslog(LOG_DEBUG, "control socket: %m");
3388 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3389 &on, sizeof(on)) < 0)
3391 "control setsockopt (SO_REUSEADDR): %m");
3392 if (r->ai_family == AF_INET6) {
3393 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3394 &on, sizeof(on)) < 0)
3396 "control setsockopt (IPV6_V6ONLY): %m");
3398 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3399 syslog(LOG_DEBUG, "control bind: %m");
3411 syslog(LOG_ERR, "control socket: Couldn't bind to any socket");