]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - libexec/ftpd/ftpd.c
Fix ftpd privilege escalation via ftpchroot.
[FreeBSD/FreeBSD.git] / libexec / ftpd / ftpd.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31
32 #if 0
33 #ifndef lint
34 static char copyright[] =
35 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
36         The Regents of the University of California.  All rights reserved.\n";
37 #endif /* not lint */
38 #endif
39
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)ftpd.c      8.4 (Berkeley) 4/16/94";
43 #endif
44 #endif /* not lint */
45
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48
49 /*
50  * FTP server.
51  */
52 #include <sys/param.h>
53 #include <sys/ioctl.h>
54 #include <sys/mman.h>
55 #include <sys/socket.h>
56 #include <sys/stat.h>
57 #include <sys/time.h>
58 #include <sys/wait.h>
59
60 #include <netinet/in.h>
61 #include <netinet/in_systm.h>
62 #include <netinet/ip.h>
63 #include <netinet/tcp.h>
64
65 #define FTP_NAMES
66 #include <arpa/ftp.h>
67 #include <arpa/inet.h>
68 #include <arpa/telnet.h>
69
70 #include <ctype.h>
71 #include <dirent.h>
72 #include <err.h>
73 #include <errno.h>
74 #include <fcntl.h>
75 #include <glob.h>
76 #include <limits.h>
77 #include <netdb.h>
78 #include <pwd.h>
79 #include <grp.h>
80 #include <opie.h>
81 #include <signal.h>
82 #include <stdint.h>
83 #include <stdio.h>
84 #include <stdlib.h>
85 #include <string.h>
86 #include <syslog.h>
87 #include <time.h>
88 #include <unistd.h>
89 #include <libutil.h>
90 #ifdef  LOGIN_CAP
91 #include <login_cap.h>
92 #endif
93
94 #ifdef USE_PAM
95 #include <security/pam_appl.h>
96 #endif
97
98 #include "blacklist_client.h"
99 #include "pathnames.h"
100 #include "extern.h"
101
102 #include <stdarg.h>
103
104 static char version[] = "Version 6.00LS";
105 #undef main
106
107 union sockunion ctrl_addr;
108 union sockunion data_source;
109 union sockunion data_dest;
110 union sockunion his_addr;
111 union sockunion pasv_addr;
112
113 int     daemon_mode;
114 int     data;
115 int     dataport;
116 int     hostinfo = 1;   /* print host-specific info in messages */
117 int     logged_in;
118 struct  passwd *pw;
119 char    *homedir;
120 int     ftpdebug;
121 int     timeout = 900;    /* timeout after 15 minutes of inactivity */
122 int     maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
123 int     logging;
124 int     restricted_data_ports = 1;
125 int     paranoid = 1;     /* be extra careful about security */
126 int     anon_only = 0;    /* Only anonymous ftp allowed */
127 int     assumeutf8 = 0;   /* Assume that server file names are in UTF-8 */
128 int     guest;
129 int     dochroot;
130 char    *chrootdir;
131 int     dowtmp = 1;
132 int     stats;
133 int     statfd = -1;
134 int     type;
135 int     form;
136 int     stru;                   /* avoid C keyword */
137 int     mode;
138 int     usedefault = 1;         /* for data transfers */
139 int     pdata = -1;             /* for passive mode */
140 int     readonly = 0;           /* Server is in readonly mode.  */
141 int     noepsv = 0;             /* EPSV command is disabled.    */
142 int     noretr = 0;             /* RETR command is disabled.    */
143 int     noguestretr = 0;        /* RETR command is disabled for anon users. */
144 int     noguestmkd = 0;         /* MKD command is disabled for anon users. */
145 int     noguestmod = 1;         /* anon users may not modify existing files. */
146 int     use_blacklist = 0;
147
148 off_t   file_size;
149 off_t   byte_count;
150 #if !defined(CMASK) || CMASK == 0
151 #undef CMASK
152 #define CMASK 027
153 #endif
154 int     defumask = CMASK;               /* default umask value */
155 char    tmpline[7];
156 char    *hostname;
157 int     epsvall = 0;
158
159 #ifdef VIRTUAL_HOSTING
160 char    *ftpuser;
161
162 static struct ftphost {
163         struct ftphost  *next;
164         struct addrinfo *hostinfo;
165         char            *hostname;
166         char            *anonuser;
167         char            *statfile;
168         char            *welcome;
169         char            *loginmsg;
170 } *thishost, *firsthost;
171
172 #endif
173 char    remotehost[NI_MAXHOST];
174 char    *ident = NULL;
175
176 static char     wtmpid[20];
177
178 #ifdef USE_PAM
179 static int      auth_pam(struct passwd**, const char*);
180 pam_handle_t    *pamh = NULL;
181 #endif
182
183 static struct opie      opiedata;
184 static char             opieprompt[OPIE_CHALLENGE_MAX+1];
185 static int              pwok;
186
187 char    *pid_file = NULL; /* means default location to pidfile(3) */
188
189 /*
190  * Limit number of pathnames that glob can return.
191  * A limit of 0 indicates the number of pathnames is unlimited.
192  */
193 #define MAXGLOBARGS     16384
194 #
195
196 /*
197  * Timeout intervals for retrying connections
198  * to hosts that don't accept PORT cmds.  This
199  * is a kludge, but given the problems with TCP...
200  */
201 #define SWAITMAX        90      /* wait at most 90 seconds */
202 #define SWAITINT        5       /* interval between retries */
203
204 int     swaitmax = SWAITMAX;
205 int     swaitint = SWAITINT;
206
207 #ifdef SETPROCTITLE
208 #ifdef OLD_SETPROCTITLE
209 char    **Argv = NULL;          /* pointer to argument vector */
210 char    *LastArgv = NULL;       /* end of argv */
211 #endif /* OLD_SETPROCTITLE */
212 char    proctitle[LINE_MAX];    /* initial part of title */
213 #endif /* SETPROCTITLE */
214
215 #define LOGCMD(cmd, file)               logcmd((cmd), (file), NULL, -1)
216 #define LOGCMD2(cmd, file1, file2)      logcmd((cmd), (file1), (file2), -1)
217 #define LOGBYTES(cmd, file, cnt)        logcmd((cmd), (file), NULL, (cnt))
218
219 static  volatile sig_atomic_t recvurg;
220 static  int transflag;          /* NB: for debugging only */
221
222 #define STARTXFER       flagxfer(1)
223 #define ENDXFER         flagxfer(0)
224
225 #define START_UNSAFE    maskurg(1)
226 #define END_UNSAFE      maskurg(0)
227
228 /* It's OK to put an `else' clause after this macro. */
229 #define CHECKOOB(action)                                                \
230         if (recvurg) {                                                  \
231                 recvurg = 0;                                            \
232                 if (myoob()) {                                          \
233                         ENDXFER;                                        \
234                         action;                                         \
235                 }                                                       \
236         }
237
238 #ifdef VIRTUAL_HOSTING
239 static void      inithosts(int);
240 static void      selecthost(union sockunion *);
241 #endif
242 static void      ack(char *);
243 static void      sigurg(int);
244 static void      maskurg(int);
245 static void      flagxfer(int);
246 static int       myoob(void);
247 static int       checkuser(char *, char *, int, char **, int *);
248 static FILE     *dataconn(char *, off_t, char *);
249 static void      dolog(struct sockaddr *);
250 static void      end_login(void);
251 static FILE     *getdatasock(char *);
252 static int       guniquefd(char *, char **);
253 static void      lostconn(int);
254 static void      sigquit(int);
255 static int       receive_data(FILE *, FILE *);
256 static int       send_data(FILE *, FILE *, size_t, off_t, int);
257 static struct passwd *
258                  sgetpwnam(char *);
259 static char     *sgetsave(char *);
260 static void      reapchild(int);
261 static void      appendf(char **, char *, ...) __printflike(2, 3);
262 static void      logcmd(char *, char *, char *, off_t);
263 static void      logxfer(char *, off_t, time_t);
264 static char     *doublequote(char *);
265 static int      *socksetup(int, char *, const char *);
266
267 int
268 main(int argc, char *argv[], char **envp)
269 {
270         socklen_t addrlen;
271         int ch, on = 1, tos, s = STDIN_FILENO;
272         char *cp, line[LINE_MAX];
273         FILE *fd;
274         char    *bindname = NULL;
275         const char *bindport = "ftp";
276         int     family = AF_UNSPEC;
277         struct sigaction sa;
278
279         tzset();                /* in case no timezone database in ~ftp */
280         sigemptyset(&sa.sa_mask);
281         sa.sa_flags = SA_RESTART;
282
283 #ifdef OLD_SETPROCTITLE
284         /*
285          *  Save start and extent of argv for setproctitle.
286          */
287         Argv = argv;
288         while (*envp)
289                 envp++;
290         LastArgv = envp[-1] + strlen(envp[-1]);
291 #endif /* OLD_SETPROCTITLE */
292
293         /*
294          * Prevent diagnostic messages from appearing on stderr.
295          * We run as a daemon or from inetd; in both cases, there's
296          * more reason in logging to syslog.
297          */
298         (void) freopen(_PATH_DEVNULL, "w", stderr);
299         opterr = 0;
300
301         /*
302          * LOG_NDELAY sets up the logging connection immediately,
303          * necessary for anonymous ftp's that chroot and can't do it later.
304          */
305         openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
306
307         while ((ch = getopt(argc, argv,
308                             "468a:ABdDEhlmMoOp:P:rRSt:T:u:UvW")) != -1) {
309                 switch (ch) {
310                 case '4':
311                         family = (family == AF_INET6) ? AF_UNSPEC : AF_INET;
312                         break;
313
314                 case '6':
315                         family = (family == AF_INET) ? AF_UNSPEC : AF_INET6;
316                         break;
317
318                 case '8':
319                         assumeutf8 = 1;
320                         break;
321
322                 case 'a':
323                         bindname = optarg;
324                         break;
325
326                 case 'A':
327                         anon_only = 1;
328                         break;
329
330                 case 'B':
331 #ifdef USE_BLACKLIST
332                         use_blacklist = 1;
333 #else
334                         syslog(LOG_WARNING, "not compiled with USE_BLACKLIST support");
335 #endif
336                         break;
337
338                 case 'd':
339                         ftpdebug++;
340                         break;
341
342                 case 'D':
343                         daemon_mode++;
344                         break;
345
346                 case 'E':
347                         noepsv = 1;
348                         break;
349
350                 case 'h':
351                         hostinfo = 0;
352                         break;
353
354                 case 'l':
355                         logging++;      /* > 1 == extra logging */
356                         break;
357
358                 case 'm':
359                         noguestmod = 0;
360                         break;
361
362                 case 'M':
363                         noguestmkd = 1;
364                         break;
365
366                 case 'o':
367                         noretr = 1;
368                         break;
369
370                 case 'O':
371                         noguestretr = 1;
372                         break;
373
374                 case 'p':
375                         pid_file = optarg;
376                         break;
377
378                 case 'P':
379                         bindport = optarg;
380                         break;
381
382                 case 'r':
383                         readonly = 1;
384                         break;
385
386                 case 'R':
387                         paranoid = 0;
388                         break;
389
390                 case 'S':
391                         stats++;
392                         break;
393
394                 case 't':
395                         timeout = atoi(optarg);
396                         if (maxtimeout < timeout)
397                                 maxtimeout = timeout;
398                         break;
399
400                 case 'T':
401                         maxtimeout = atoi(optarg);
402                         if (timeout > maxtimeout)
403                                 timeout = maxtimeout;
404                         break;
405
406                 case 'u':
407                     {
408                         long val = 0;
409
410                         val = strtol(optarg, &optarg, 8);
411                         if (*optarg != '\0' || val < 0)
412                                 syslog(LOG_WARNING, "bad value for -u");
413                         else
414                                 defumask = val;
415                         break;
416                     }
417                 case 'U':
418                         restricted_data_ports = 0;
419                         break;
420
421                 case 'v':
422                         ftpdebug++;
423                         break;
424
425                 case 'W':
426                         dowtmp = 0;
427                         break;
428
429                 default:
430                         syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
431                         break;
432                 }
433         }
434
435         /* handle filesize limit gracefully */
436         sa.sa_handler = SIG_IGN;
437         (void)sigaction(SIGXFSZ, &sa, NULL);
438
439         if (daemon_mode) {
440                 int *ctl_sock, fd, maxfd = -1, nfds, i;
441                 fd_set defreadfds, readfds;
442                 pid_t pid;
443                 struct pidfh *pfh;
444
445                 if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
446                         if (errno == EEXIST) {
447                                 syslog(LOG_ERR, "%s already running, pid %d",
448                                        getprogname(), (int)pid);
449                                 exit(1);
450                         }
451                         syslog(LOG_WARNING, "pidfile_open: %m");
452                 }
453
454                 /*
455                  * Detach from parent.
456                  */
457                 if (daemon(1, 1) < 0) {
458                         syslog(LOG_ERR, "failed to become a daemon");
459                         exit(1);
460                 }
461
462                 if (pfh != NULL && pidfile_write(pfh) == -1)
463                         syslog(LOG_WARNING, "pidfile_write: %m");
464
465                 sa.sa_handler = reapchild;
466                 (void)sigaction(SIGCHLD, &sa, NULL);
467
468 #ifdef VIRTUAL_HOSTING
469                 inithosts(family);
470 #endif
471
472                 /*
473                  * Open a socket, bind it to the FTP port, and start
474                  * listening.
475                  */
476                 ctl_sock = socksetup(family, bindname, bindport);
477                 if (ctl_sock == NULL)
478                         exit(1);
479
480                 FD_ZERO(&defreadfds);
481                 for (i = 1; i <= *ctl_sock; i++) {
482                         FD_SET(ctl_sock[i], &defreadfds);
483                         if (listen(ctl_sock[i], 32) < 0) {
484                                 syslog(LOG_ERR, "control listen: %m");
485                                 exit(1);
486                         }
487                         if (maxfd < ctl_sock[i])
488                                 maxfd = ctl_sock[i];
489                 }
490
491                 /*
492                  * Loop forever accepting connection requests and forking off
493                  * children to handle them.
494                  */
495                 while (1) {
496                         FD_COPY(&defreadfds, &readfds);
497                         nfds = select(maxfd + 1, &readfds, NULL, NULL, 0);
498                         if (nfds <= 0) {
499                                 if (nfds < 0 && errno != EINTR)
500                                         syslog(LOG_WARNING, "select: %m");
501                                 continue;
502                         }
503
504                         pid = -1;
505                         for (i = 1; i <= *ctl_sock; i++)
506                                 if (FD_ISSET(ctl_sock[i], &readfds)) {
507                                         addrlen = sizeof(his_addr);
508                                         fd = accept(ctl_sock[i],
509                                             (struct sockaddr *)&his_addr,
510                                             &addrlen);
511                                         if (fd == -1) {
512                                                 syslog(LOG_WARNING,
513                                                        "accept: %m");
514                                                 continue;
515                                         }
516                                         switch (pid = fork()) {
517                                         case 0:
518                                                 /* child */
519                                                 (void) dup2(fd, s);
520                                                 (void) dup2(fd, STDOUT_FILENO);
521                                                 (void) close(fd);
522                                                 for (i = 1; i <= *ctl_sock; i++)
523                                                         close(ctl_sock[i]);
524                                                 if (pfh != NULL)
525                                                         pidfile_close(pfh);
526                                                 goto gotchild;
527                                         case -1:
528                                                 syslog(LOG_WARNING, "fork: %m");
529                                                 /* FALLTHROUGH */
530                                         default:
531                                                 close(fd);
532                                         }
533                                 }
534                 }
535         } else {
536                 addrlen = sizeof(his_addr);
537                 if (getpeername(s, (struct sockaddr *)&his_addr, &addrlen) < 0) {
538                         syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
539                         exit(1);
540                 }
541
542 #ifdef VIRTUAL_HOSTING
543                 if (his_addr.su_family == AF_INET6 &&
544                     IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))
545                         family = AF_INET;
546                 else
547                         family = his_addr.su_family;
548                 inithosts(family);
549 #endif
550         }
551
552 gotchild:
553         sa.sa_handler = SIG_DFL;
554         (void)sigaction(SIGCHLD, &sa, NULL);
555
556         sa.sa_handler = sigurg;
557         sa.sa_flags = 0;                /* don't restart syscalls for SIGURG */
558         (void)sigaction(SIGURG, &sa, NULL);
559
560         sigfillset(&sa.sa_mask);        /* block all signals in handler */
561         sa.sa_flags = SA_RESTART;
562         sa.sa_handler = sigquit;
563         (void)sigaction(SIGHUP, &sa, NULL);
564         (void)sigaction(SIGINT, &sa, NULL);
565         (void)sigaction(SIGQUIT, &sa, NULL);
566         (void)sigaction(SIGTERM, &sa, NULL);
567
568         sa.sa_handler = lostconn;
569         (void)sigaction(SIGPIPE, &sa, NULL);
570
571         addrlen = sizeof(ctrl_addr);
572         if (getsockname(s, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
573                 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
574                 exit(1);
575         }
576         dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
577 #ifdef VIRTUAL_HOSTING
578         /* select our identity from virtual host table */
579         selecthost(&ctrl_addr);
580 #endif
581 #ifdef IP_TOS
582         if (ctrl_addr.su_family == AF_INET)
583       {
584         tos = IPTOS_LOWDELAY;
585         if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
586                 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
587       }
588 #endif
589         /*
590          * Disable Nagle on the control channel so that we don't have to wait
591          * for peer's ACK before issuing our next reply.
592          */
593         if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
594                 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
595
596         data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
597
598         (void)snprintf(wtmpid, sizeof(wtmpid), "%xftpd", getpid());
599
600         /* Try to handle urgent data inline */
601 #ifdef SO_OOBINLINE
602         if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
603                 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
604 #endif
605
606 #ifdef  F_SETOWN
607         if (fcntl(s, F_SETOWN, getpid()) == -1)
608                 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
609 #endif
610         dolog((struct sockaddr *)&his_addr);
611         /*
612          * Set up default state
613          */
614         data = -1;
615         type = TYPE_A;
616         form = FORM_N;
617         stru = STRU_F;
618         mode = MODE_S;
619         tmpline[0] = '\0';
620
621         /* If logins are disabled, print out the message. */
622         if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
623                 while (fgets(line, sizeof(line), fd) != NULL) {
624                         if ((cp = strchr(line, '\n')) != NULL)
625                                 *cp = '\0';
626                         lreply(530, "%s", line);
627                 }
628                 (void) fflush(stdout);
629                 (void) fclose(fd);
630                 reply(530, "System not available.");
631                 exit(0);
632         }
633 #ifdef VIRTUAL_HOSTING
634         fd = fopen(thishost->welcome, "r");
635 #else
636         fd = fopen(_PATH_FTPWELCOME, "r");
637 #endif
638         if (fd != NULL) {
639                 while (fgets(line, sizeof(line), fd) != NULL) {
640                         if ((cp = strchr(line, '\n')) != NULL)
641                                 *cp = '\0';
642                         lreply(220, "%s", line);
643                 }
644                 (void) fflush(stdout);
645                 (void) fclose(fd);
646                 /* reply(220,) must follow */
647         }
648 #ifndef VIRTUAL_HOSTING
649         if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
650                 fatalerror("Ran out of memory.");
651         if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
652                 hostname[0] = '\0';
653         hostname[MAXHOSTNAMELEN - 1] = '\0';
654 #endif
655         if (hostinfo)
656                 reply(220, "%s FTP server (%s) ready.", hostname, version);
657         else
658                 reply(220, "FTP server ready.");
659         BLACKLIST_INIT();
660         for (;;)
661                 (void) yyparse();
662         /* NOTREACHED */
663 }
664
665 static void
666 lostconn(int signo)
667 {
668
669         if (ftpdebug)
670                 syslog(LOG_DEBUG, "lost connection");
671         dologout(1);
672 }
673
674 static void
675 sigquit(int signo)
676 {
677
678         syslog(LOG_ERR, "got signal %d", signo);
679         dologout(1);
680 }
681
682 #ifdef VIRTUAL_HOSTING
683 /*
684  * read in virtual host tables (if they exist)
685  */
686
687 static void
688 inithosts(int family)
689 {
690         int insert;
691         size_t len;
692         FILE *fp;
693         char *cp, *mp, *line;
694         char *hostname;
695         char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
696         struct ftphost *hrp, *lhrp;
697         struct addrinfo hints, *res, *ai;
698
699         /*
700          * Fill in the default host information
701          */
702         if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
703                 fatalerror("Ran out of memory.");
704         if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
705                 hostname[0] = '\0';
706         hostname[MAXHOSTNAMELEN - 1] = '\0';
707         if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
708                 fatalerror("Ran out of memory.");
709         hrp->hostname = hostname;
710         hrp->hostinfo = NULL;
711
712         memset(&hints, 0, sizeof(hints));
713         hints.ai_flags = AI_PASSIVE;
714         hints.ai_family = family;
715         hints.ai_socktype = SOCK_STREAM;
716         if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
717                 hrp->hostinfo = res;
718         hrp->statfile = _PATH_FTPDSTATFILE;
719         hrp->welcome  = _PATH_FTPWELCOME;
720         hrp->loginmsg = _PATH_FTPLOGINMESG;
721         hrp->anonuser = "ftp";
722         hrp->next = NULL;
723         thishost = firsthost = lhrp = hrp;
724         if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
725                 int addrsize, gothost;
726                 void *addr;
727                 struct hostent *hp;
728
729                 while ((line = fgetln(fp, &len)) != NULL) {
730                         int     i, hp_error;
731
732                         /* skip comments */
733                         if (line[0] == '#')
734                                 continue;
735                         if (line[len - 1] == '\n') {
736                                 line[len - 1] = '\0';
737                                 mp = NULL;
738                         } else {
739                                 if ((mp = malloc(len + 1)) == NULL)
740                                         fatalerror("Ran out of memory.");
741                                 memcpy(mp, line, len);
742                                 mp[len] = '\0';
743                                 line = mp;
744                         }
745                         cp = strtok(line, " \t");
746                         /* skip empty lines */
747                         if (cp == NULL)
748                                 goto nextline;
749                         vhost = cp;
750
751                         /* set defaults */
752                         anonuser = "ftp";
753                         statfile = _PATH_FTPDSTATFILE;
754                         welcome  = _PATH_FTPWELCOME;
755                         loginmsg = _PATH_FTPLOGINMESG;
756
757                         /*
758                          * Preparse the line so we can use its info
759                          * for all the addresses associated with
760                          * the virtual host name.
761                          * Field 0, the virtual host name, is special:
762                          * it's already parsed off and will be strdup'ed
763                          * later, after we know its canonical form.
764                          */
765                         for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
766                                 if (*cp != '-' && (cp = strdup(cp)))
767                                         switch (i) {
768                                         case 1: /* anon user permissions */
769                                                 anonuser = cp;
770                                                 break;
771                                         case 2: /* statistics file */
772                                                 statfile = cp;
773                                                 break;
774                                         case 3: /* welcome message */
775                                                 welcome  = cp;
776                                                 break;
777                                         case 4: /* login message */
778                                                 loginmsg = cp;
779                                                 break;
780                                         default: /* programming error */
781                                                 abort();
782                                                 /* NOTREACHED */
783                                         }
784
785                         hints.ai_flags = AI_PASSIVE;
786                         hints.ai_family = family;
787                         hints.ai_socktype = SOCK_STREAM;
788                         if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
789                                 goto nextline;
790                         for (ai = res; ai != NULL && ai->ai_addr != NULL;
791                              ai = ai->ai_next) {
792
793                         gothost = 0;
794                         for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
795                                 struct addrinfo *hi;
796
797                                 for (hi = hrp->hostinfo; hi != NULL;
798                                      hi = hi->ai_next)
799                                         if (hi->ai_addrlen == ai->ai_addrlen &&
800                                             memcmp(hi->ai_addr,
801                                                    ai->ai_addr,
802                                                    ai->ai_addr->sa_len) == 0) {
803                                                 gothost++;
804                                                 break;
805                                         }
806                                 if (gothost)
807                                         break;
808                         }
809                         if (hrp == NULL) {
810                                 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
811                                         goto nextline;
812                                 hrp->hostname = NULL;
813                                 insert = 1;
814                         } else {
815                                 if (hrp->hostinfo && hrp->hostinfo != res)
816                                         freeaddrinfo(hrp->hostinfo);
817                                 insert = 0; /* host already in the chain */
818                         }
819                         hrp->hostinfo = res;
820
821                         /*
822                          * determine hostname to use.
823                          * force defined name if there is a valid alias
824                          * otherwise fallback to primary hostname
825                          */
826                         /* XXX: getaddrinfo() can't do alias check */
827                         switch(hrp->hostinfo->ai_family) {
828                         case AF_INET:
829                                 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
830                                 addrsize = sizeof(struct in_addr);
831                                 break;
832                         case AF_INET6:
833                                 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
834                                 addrsize = sizeof(struct in6_addr);
835                                 break;
836                         default:
837                                 /* should not reach here */
838                                 freeaddrinfo(hrp->hostinfo);
839                                 if (insert)
840                                         free(hrp); /*not in chain, can free*/
841                                 else
842                                         hrp->hostinfo = NULL; /*mark as blank*/
843                                 goto nextline;
844                                 /* NOTREACHED */
845                         }
846                         if ((hp = getipnodebyaddr(addr, addrsize,
847                                                   hrp->hostinfo->ai_family,
848                                                   &hp_error)) != NULL) {
849                                 if (strcmp(vhost, hp->h_name) != 0) {
850                                         if (hp->h_aliases == NULL)
851                                                 vhost = hp->h_name;
852                                         else {
853                                                 i = 0;
854                                                 while (hp->h_aliases[i] &&
855                                                        strcmp(vhost, hp->h_aliases[i]) != 0)
856                                                         ++i;
857                                                 if (hp->h_aliases[i] == NULL)
858                                                         vhost = hp->h_name;
859                                         }
860                                 }
861                         }
862                         if (hrp->hostname &&
863                             strcmp(hrp->hostname, vhost) != 0) {
864                                 free(hrp->hostname);
865                                 hrp->hostname = NULL;
866                         }
867                         if (hrp->hostname == NULL &&
868                             (hrp->hostname = strdup(vhost)) == NULL) {
869                                 freeaddrinfo(hrp->hostinfo);
870                                 hrp->hostinfo = NULL; /* mark as blank */
871                                 if (hp)
872                                         freehostent(hp);
873                                 goto nextline;
874                         }
875                         hrp->anonuser = anonuser;
876                         hrp->statfile = statfile;
877                         hrp->welcome  = welcome;
878                         hrp->loginmsg = loginmsg;
879                         if (insert) {
880                                 hrp->next  = NULL;
881                                 lhrp->next = hrp;
882                                 lhrp = hrp;
883                         }
884                         if (hp)
885                                 freehostent(hp);
886                       }
887 nextline:
888                         if (mp)
889                                 free(mp);
890                 }
891                 (void) fclose(fp);
892         }
893 }
894
895 static void
896 selecthost(union sockunion *su)
897 {
898         struct ftphost  *hrp;
899         u_int16_t port;
900 #ifdef INET6
901         struct in6_addr *mapped_in6 = NULL;
902 #endif
903         struct addrinfo *hi;
904
905 #ifdef INET6
906         /*
907          * XXX IPv4 mapped IPv6 addr consideraton,
908          * specified in rfc2373.
909          */
910         if (su->su_family == AF_INET6 &&
911             IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
912                 mapped_in6 = &su->su_sin6.sin6_addr;
913 #endif
914
915         hrp = thishost = firsthost;     /* default */
916         port = su->su_port;
917         su->su_port = 0;
918         while (hrp != NULL) {
919             for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
920                 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
921                         thishost = hrp;
922                         goto found;
923                 }
924 #ifdef INET6
925                 /* XXX IPv4 mapped IPv6 addr consideraton */
926                 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
927                     (memcmp(&mapped_in6->s6_addr[12],
928                             &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
929                             sizeof(struct in_addr)) == 0)) {
930                         thishost = hrp;
931                         goto found;
932                 }
933 #endif
934             }
935             hrp = hrp->next;
936         }
937 found:
938         su->su_port = port;
939         /* setup static variables as appropriate */
940         hostname = thishost->hostname;
941         ftpuser = thishost->anonuser;
942 }
943 #endif
944
945 /*
946  * Helper function for sgetpwnam().
947  */
948 static char *
949 sgetsave(char *s)
950 {
951         char *new = malloc(strlen(s) + 1);
952
953         if (new == NULL) {
954                 reply(421, "Ran out of memory.");
955                 dologout(1);
956                 /* NOTREACHED */
957         }
958         (void) strcpy(new, s);
959         return (new);
960 }
961
962 /*
963  * Save the result of a getpwnam.  Used for USER command, since
964  * the data returned must not be clobbered by any other command
965  * (e.g., globbing).
966  * NB: The data returned by sgetpwnam() will remain valid until
967  * the next call to this function.  Its difference from getpwnam()
968  * is that sgetpwnam() is known to be called from ftpd code only.
969  */
970 static struct passwd *
971 sgetpwnam(char *name)
972 {
973         static struct passwd save;
974         struct passwd *p;
975
976         if ((p = getpwnam(name)) == NULL)
977                 return (p);
978         if (save.pw_name) {
979                 free(save.pw_name);
980                 free(save.pw_passwd);
981                 free(save.pw_class);
982                 free(save.pw_gecos);
983                 free(save.pw_dir);
984                 free(save.pw_shell);
985         }
986         save = *p;
987         save.pw_name = sgetsave(p->pw_name);
988         save.pw_passwd = sgetsave(p->pw_passwd);
989         save.pw_class = sgetsave(p->pw_class);
990         save.pw_gecos = sgetsave(p->pw_gecos);
991         save.pw_dir = sgetsave(p->pw_dir);
992         save.pw_shell = sgetsave(p->pw_shell);
993         return (&save);
994 }
995
996 static int login_attempts;      /* number of failed login attempts */
997 static int askpasswd;           /* had user command, ask for passwd */
998 static char curname[MAXLOGNAME];        /* current USER name */
999
1000 /*
1001  * USER command.
1002  * Sets global passwd pointer pw if named account exists and is acceptable;
1003  * sets askpasswd if a PASS command is expected.  If logged in previously,
1004  * need to reset state.  If name is "ftp" or "anonymous", the name is not in
1005  * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
1006  * If account doesn't exist, ask for passwd anyway.  Otherwise, check user
1007  * requesting login privileges.  Disallow anyone who does not have a standard
1008  * shell as returned by getusershell().  Disallow anyone mentioned in the file
1009  * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
1010  */
1011 void
1012 user(char *name)
1013 {
1014         int ecode;
1015         char *cp, *shell;
1016
1017         if (logged_in) {
1018                 if (guest) {
1019                         reply(530, "Can't change user from guest login.");
1020                         return;
1021                 } else if (dochroot) {
1022                         reply(530, "Can't change user from chroot user.");
1023                         return;
1024                 }
1025                 end_login();
1026         }
1027
1028         guest = 0;
1029 #ifdef VIRTUAL_HOSTING
1030         pw = sgetpwnam(thishost->anonuser);
1031 #else
1032         pw = sgetpwnam("ftp");
1033 #endif
1034         if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1035                 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL, &ecode) ||
1036                     (ecode != 0 && ecode != ENOENT))
1037                         reply(530, "User %s access denied.", name);
1038                 else if (checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL, &ecode) ||
1039                     (ecode != 0 && ecode != ENOENT))
1040                         reply(530, "User %s access denied.", name);
1041                 else if (pw != NULL) {
1042                         guest = 1;
1043                         askpasswd = 1;
1044                         reply(331,
1045                         "Guest login ok, send your email address as password.");
1046                 } else
1047                         reply(530, "User %s unknown.", name);
1048                 if (!askpasswd && logging)
1049                         syslog(LOG_NOTICE,
1050                             "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1051                 return;
1052         }
1053         if (anon_only != 0) {
1054                 reply(530, "Sorry, only anonymous ftp allowed.");
1055                 return;
1056         }
1057                 
1058         if ((pw = sgetpwnam(name))) {
1059                 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1060                         shell = _PATH_BSHELL;
1061                 setusershell();
1062                 while ((cp = getusershell()) != NULL)
1063                         if (strcmp(cp, shell) == 0)
1064                                 break;
1065                 endusershell();
1066
1067                 if (cp == NULL || 
1068                     (checkuser(_PATH_FTPUSERS, name, 1, NULL, &ecode) ||
1069                     (ecode != 0 && ecode != ENOENT))) {
1070                         reply(530, "User %s access denied.", name);
1071                         if (logging)
1072                                 syslog(LOG_NOTICE,
1073                                     "FTP LOGIN REFUSED FROM %s, %s",
1074                                     remotehost, name);
1075                         pw = NULL;
1076                         return;
1077                 }
1078         }
1079         if (logging)
1080                 strlcpy(curname, name, sizeof(curname));
1081
1082         pwok = 0;
1083 #ifdef USE_PAM
1084         /* XXX Kluge! The conversation mechanism needs to be fixed. */
1085 #endif
1086         if (opiechallenge(&opiedata, name, opieprompt) == 0) {
1087                 pwok = (pw != NULL) &&
1088                        opieaccessfile(remotehost) &&
1089                        opiealways(pw->pw_dir);
1090                 reply(331, "Response to %s %s for %s.",
1091                       opieprompt, pwok ? "requested" : "required", name);
1092         } else {
1093                 pwok = 1;
1094                 reply(331, "Password required for %s.", name);
1095         }
1096         askpasswd = 1;
1097         /*
1098          * Delay before reading passwd after first failed
1099          * attempt to slow down passwd-guessing programs.
1100          */
1101         if (login_attempts)
1102                 sleep(login_attempts);
1103 }
1104
1105 /*
1106  * Check if a user is in the file "fname",
1107  * return a pointer to a malloc'd string with the rest
1108  * of the matching line in "residue" if not NULL.
1109  */
1110 static int
1111 checkuser(char *fname, char *name, int pwset, char **residue, int *ecode)
1112 {
1113         FILE *fd;
1114         int found = 0;
1115         size_t len;
1116         char *line, *mp, *p;
1117
1118         if (ecode != NULL)
1119                 *ecode = 0;
1120         if ((fd = fopen(fname, "r")) != NULL) {
1121                 while (!found && (line = fgetln(fd, &len)) != NULL) {
1122                         /* skip comments */
1123                         if (line[0] == '#')
1124                                 continue;
1125                         if (line[len - 1] == '\n') {
1126                                 line[len - 1] = '\0';
1127                                 mp = NULL;
1128                         } else {
1129                                 if ((mp = malloc(len + 1)) == NULL)
1130                                         fatalerror("Ran out of memory.");
1131                                 memcpy(mp, line, len);
1132                                 mp[len] = '\0';
1133                                 line = mp;
1134                         }
1135                         /* avoid possible leading and trailing whitespace */
1136                         p = strtok(line, " \t");
1137                         /* skip empty lines */
1138                         if (p == NULL)
1139                                 goto nextline;
1140                         /*
1141                          * if first chr is '@', check group membership
1142                          */
1143                         if (p[0] == '@') {
1144                                 int i = 0;
1145                                 struct group *grp;
1146
1147                                 if (p[1] == '\0') /* single @ matches anyone */
1148                                         found = 1;
1149                                 else {
1150                                         if ((grp = getgrnam(p+1)) == NULL)
1151                                                 goto nextline;
1152                                         /*
1153                                          * Check user's default group
1154                                          */
1155                                         if (pwset && grp->gr_gid == pw->pw_gid)
1156                                                 found = 1;
1157                                         /*
1158                                          * Check supplementary groups
1159                                          */
1160                                         while (!found && grp->gr_mem[i])
1161                                                 found = strcmp(name,
1162                                                         grp->gr_mem[i++])
1163                                                         == 0;
1164                                 }
1165                         }
1166                         /*
1167                          * Otherwise, just check for username match
1168                          */
1169                         else
1170                                 found = strcmp(p, name) == 0;
1171                         /*
1172                          * Save the rest of line to "residue" if matched
1173                          */
1174                         if (found && residue) {
1175                                 if ((p = strtok(NULL, "")) != NULL)
1176                                         p += strspn(p, " \t");
1177                                 if (p && *p) {
1178                                         if ((*residue = strdup(p)) == NULL)
1179                                                 fatalerror("Ran out of memory.");
1180                                 } else
1181                                         *residue = NULL;
1182                         }
1183 nextline:
1184                         if (mp)
1185                                 free(mp);
1186                 }
1187                 (void) fclose(fd);
1188         } else if (ecode != NULL)
1189                 *ecode = errno;
1190         return (found);
1191 }
1192
1193 /*
1194  * Terminate login as previous user, if any, resetting state;
1195  * used when USER command is given or login fails.
1196  */
1197 static void
1198 end_login(void)
1199 {
1200 #ifdef USE_PAM
1201         int e;
1202 #endif
1203
1204         (void) seteuid(0);
1205 #ifdef  LOGIN_CAP
1206         setusercontext(NULL, getpwuid(0), 0, LOGIN_SETALL & ~(LOGIN_SETLOGIN |
1207                        LOGIN_SETUSER | LOGIN_SETGROUP | LOGIN_SETPATH |
1208                        LOGIN_SETENV));
1209 #endif
1210         if (logged_in && dowtmp)
1211                 ftpd_logwtmp(wtmpid, NULL, NULL);
1212         pw = NULL;
1213 #ifdef USE_PAM
1214         if (pamh) {
1215                 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1216                         syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1217                 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1218                         syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1219                 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1220                         syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1221                 pamh = NULL;
1222         }
1223 #endif
1224         logged_in = 0;
1225         guest = 0;
1226         dochroot = 0;
1227 }
1228
1229 #ifdef USE_PAM
1230
1231 /*
1232  * the following code is stolen from imap-uw PAM authentication module and
1233  * login.c
1234  */
1235 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1236
1237 struct cred_t {
1238         const char *uname;              /* user name */
1239         const char *pass;               /* password */
1240 };
1241 typedef struct cred_t cred_t;
1242
1243 static int
1244 auth_conv(int num_msg, const struct pam_message **msg,
1245           struct pam_response **resp, void *appdata)
1246 {
1247         int i;
1248         cred_t *cred = (cred_t *) appdata;
1249         struct pam_response *reply;
1250
1251         reply = calloc(num_msg, sizeof *reply);
1252         if (reply == NULL)
1253                 return PAM_BUF_ERR;
1254
1255         for (i = 0; i < num_msg; i++) {
1256                 switch (msg[i]->msg_style) {
1257                 case PAM_PROMPT_ECHO_ON:        /* assume want user name */
1258                         reply[i].resp_retcode = PAM_SUCCESS;
1259                         reply[i].resp = COPY_STRING(cred->uname);
1260                         /* PAM frees resp. */
1261                         break;
1262                 case PAM_PROMPT_ECHO_OFF:       /* assume want password */
1263                         reply[i].resp_retcode = PAM_SUCCESS;
1264                         reply[i].resp = COPY_STRING(cred->pass);
1265                         /* PAM frees resp. */
1266                         break;
1267                 case PAM_TEXT_INFO:
1268                 case PAM_ERROR_MSG:
1269                         reply[i].resp_retcode = PAM_SUCCESS;
1270                         reply[i].resp = NULL;
1271                         break;
1272                 default:                        /* unknown message style */
1273                         free(reply);
1274                         return PAM_CONV_ERR;
1275                 }
1276         }
1277
1278         *resp = reply;
1279         return PAM_SUCCESS;
1280 }
1281
1282 /*
1283  * Attempt to authenticate the user using PAM.  Returns 0 if the user is
1284  * authenticated, or 1 if not authenticated.  If some sort of PAM system
1285  * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1286  * function returns -1.  This can be used as an indication that we should
1287  * fall back to a different authentication mechanism.
1288  */
1289 static int
1290 auth_pam(struct passwd **ppw, const char *pass)
1291 {
1292         const char *tmpl_user;
1293         const void *item;
1294         int rval;
1295         int e;
1296         cred_t auth_cred = { (*ppw)->pw_name, pass };
1297         struct pam_conv conv = { &auth_conv, &auth_cred };
1298
1299         e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1300         if (e != PAM_SUCCESS) {
1301                 /*
1302                  * In OpenPAM, it's OK to pass NULL to pam_strerror()
1303                  * if context creation has failed in the first place.
1304                  */
1305                 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
1306                 return -1;
1307         }
1308
1309         e = pam_set_item(pamh, PAM_RHOST, remotehost);
1310         if (e != PAM_SUCCESS) {
1311                 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1312                         pam_strerror(pamh, e));
1313                 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1314                         syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1315                 }
1316                 pamh = NULL;
1317                 return -1;
1318         }
1319
1320         e = pam_authenticate(pamh, 0);
1321         switch (e) {
1322         case PAM_SUCCESS:
1323                 /*
1324                  * With PAM we support the concept of a "template"
1325                  * user.  The user enters a login name which is
1326                  * authenticated by PAM, usually via a remote service
1327                  * such as RADIUS or TACACS+.  If authentication
1328                  * succeeds, a different but related "template" name
1329                  * is used for setting the credentials, shell, and
1330                  * home directory.  The name the user enters need only
1331                  * exist on the remote authentication server, but the
1332                  * template name must be present in the local password
1333                  * database.
1334                  *
1335                  * This is supported by two various mechanisms in the
1336                  * individual modules.  However, from the application's
1337                  * point of view, the template user is always passed
1338                  * back as a changed value of the PAM_USER item.
1339                  */
1340                 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1341                     PAM_SUCCESS) {
1342                         tmpl_user = (const char *) item;
1343                         if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1344                                 *ppw = getpwnam(tmpl_user);
1345                 } else
1346                         syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1347                             pam_strerror(pamh, e));
1348                 rval = 0;
1349                 break;
1350
1351         case PAM_AUTH_ERR:
1352         case PAM_USER_UNKNOWN:
1353         case PAM_MAXTRIES:
1354                 rval = 1;
1355                 break;
1356
1357         default:
1358                 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1359                 rval = -1;
1360                 break;
1361         }
1362
1363         if (rval == 0) {
1364                 e = pam_acct_mgmt(pamh, 0);
1365                 if (e != PAM_SUCCESS) {
1366                         syslog(LOG_ERR, "pam_acct_mgmt: %s",
1367                                                 pam_strerror(pamh, e));
1368                         rval = 1;
1369                 }
1370         }
1371
1372         if (rval != 0) {
1373                 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1374                         syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1375                 }
1376                 pamh = NULL;
1377         }
1378         return rval;
1379 }
1380
1381 #endif /* USE_PAM */
1382
1383 void
1384 pass(char *passwd)
1385 {
1386         int rval, ecode;
1387         FILE *fd;
1388 #ifdef  LOGIN_CAP
1389         login_cap_t *lc = NULL;
1390 #endif
1391 #ifdef USE_PAM
1392         int e;
1393 #endif
1394         char *residue = NULL;
1395         char *xpasswd;
1396
1397         if (logged_in || askpasswd == 0) {
1398                 reply(503, "Login with USER first.");
1399                 return;
1400         }
1401         askpasswd = 0;
1402         if (!guest) {           /* "ftp" is only account allowed no password */
1403                 if (pw == NULL) {
1404                         rval = 1;       /* failure below */
1405                         goto skip;
1406                 }
1407 #ifdef USE_PAM
1408                 rval = auth_pam(&pw, passwd);
1409                 if (rval >= 0) {
1410                         opieunlock();
1411                         goto skip;
1412                 }
1413 #endif
1414                 if (opieverify(&opiedata, passwd) == 0)
1415                         xpasswd = pw->pw_passwd;
1416                 else if (pwok) {
1417                         xpasswd = crypt(passwd, pw->pw_passwd);
1418                         if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1419                                 xpasswd = ":";
1420                 } else {
1421                         rval = 1;
1422                         goto skip;
1423                 }
1424                 rval = strcmp(pw->pw_passwd, xpasswd);
1425                 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1426                         rval = 1;       /* failure */
1427 skip:
1428                 /*
1429                  * If rval == 1, the user failed the authentication check
1430                  * above.  If rval == 0, either PAM or local authentication
1431                  * succeeded.
1432                  */
1433                 if (rval) {
1434                         reply(530, "Login incorrect.");
1435                         BLACKLIST_NOTIFY(BLACKLIST_AUTH_FAIL, STDIN_FILENO, "Login incorrect");
1436                         if (logging) {
1437                                 syslog(LOG_NOTICE,
1438                                     "FTP LOGIN FAILED FROM %s",
1439                                     remotehost);
1440                                 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1441                                     "FTP LOGIN FAILED FROM %s, %s",
1442                                     remotehost, curname);
1443                         }
1444                         pw = NULL;
1445                         if (login_attempts++ >= 5) {
1446                                 syslog(LOG_NOTICE,
1447                                     "repeated login failures from %s",
1448                                     remotehost);
1449                                 exit(0);
1450                         }
1451                         return;
1452                 } else {
1453                         BLACKLIST_NOTIFY(BLACKLIST_AUTH_OK, STDIN_FILENO, "Login successful");
1454                 }
1455         }
1456         login_attempts = 0;             /* this time successful */
1457         if (setegid(pw->pw_gid) < 0) {
1458                 reply(550, "Can't set gid.");
1459                 return;
1460         }
1461         /* May be overridden by login.conf */
1462         (void) umask(defumask);
1463 #ifdef  LOGIN_CAP
1464         if ((lc = login_getpwclass(pw)) != NULL) {
1465                 char    remote_ip[NI_MAXHOST];
1466
1467                 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1468                         remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1469                         NI_NUMERICHOST))
1470                                 *remote_ip = 0;
1471                 remote_ip[sizeof(remote_ip) - 1] = 0;
1472                 if (!auth_hostok(lc, remotehost, remote_ip)) {
1473                         syslog(LOG_INFO|LOG_AUTH,
1474                             "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1475                             pw->pw_name);
1476                         reply(530, "Permission denied.");
1477                         pw = NULL;
1478                         return;
1479                 }
1480                 if (!auth_timeok(lc, time(NULL))) {
1481                         reply(530, "Login not available right now.");
1482                         pw = NULL;
1483                         return;
1484                 }
1485         }
1486         setusercontext(lc, pw, 0, LOGIN_SETALL &
1487                        ~(LOGIN_SETRESOURCES | LOGIN_SETUSER | LOGIN_SETPATH | LOGIN_SETENV));
1488 #else
1489         setlogin(pw->pw_name);
1490         (void) initgroups(pw->pw_name, pw->pw_gid);
1491 #endif
1492
1493 #ifdef USE_PAM
1494         if (pamh) {
1495                 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1496                         syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1497                 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1498                         syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1499                 }
1500         }
1501 #endif
1502
1503         dochroot =
1504                 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue, &ecode)
1505 #ifdef  LOGIN_CAP       /* Allow login.conf configuration as well */
1506                 || login_getcapbool(lc, "ftp-chroot", 0)
1507 #endif
1508         ;
1509         /*
1510          * It is possible that checkuser() failed to open the chroot file.
1511          * If this is the case, report that logins are un-available, since we
1512          * have no way of checking whether or not the user should be chrooted.
1513          * We ignore ENOENT since it is not required that this file be present.
1514          */
1515         if (ecode != 0 && ecode != ENOENT) {
1516                 reply(530, "Login not available right now.");
1517                 return;
1518         }
1519         chrootdir = NULL;
1520
1521         /* Disable wtmp logging when chrooting. */
1522         if (dochroot || guest)
1523                 dowtmp = 0;
1524         if (dowtmp)
1525                 ftpd_logwtmp(wtmpid, pw->pw_name,
1526                     (struct sockaddr *)&his_addr);
1527         logged_in = 1;
1528
1529 #ifdef  LOGIN_CAP
1530         setusercontext(lc, pw, 0, LOGIN_SETRESOURCES);
1531 #endif
1532
1533         if (guest && stats && statfd < 0)
1534 #ifdef VIRTUAL_HOSTING
1535                 statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1536 #else
1537                 statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1538 #endif
1539                 if (statfd < 0)
1540                         stats = 0;
1541
1542         /*
1543          * For a chrooted local user,
1544          * a) see whether ftpchroot(5) specifies a chroot directory,
1545          * b) extract the directory pathname from the line,
1546          * c) expand it to the absolute pathname if necessary.
1547          */
1548         if (dochroot && residue &&
1549             (chrootdir = strtok(residue, " \t")) != NULL) {
1550                 if (chrootdir[0] != '/')
1551                         asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1552                 else
1553                         chrootdir = strdup(chrootdir); /* make it permanent */
1554                 if (chrootdir == NULL)
1555                         fatalerror("Ran out of memory.");
1556         }
1557         if (guest || dochroot) {
1558                 /*
1559                  * If no chroot directory set yet, use the login directory.
1560                  * Copy it so it can be modified while pw->pw_dir stays intact.
1561                  */
1562                 if (chrootdir == NULL &&
1563                     (chrootdir = strdup(pw->pw_dir)) == NULL)
1564                         fatalerror("Ran out of memory.");
1565                 /*
1566                  * Check for the "/chroot/./home" syntax,
1567                  * separate the chroot and home directory pathnames.
1568                  */
1569                 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1570                         *(homedir++) = '\0';    /* wipe '/' */
1571                         homedir++;              /* skip '.' */
1572                 } else {
1573                         /*
1574                          * We MUST do a chdir() after the chroot. Otherwise
1575                          * the old current directory will be accessible as "."
1576                          * outside the new root!
1577                          */
1578                         homedir = "/";
1579                 }
1580                 /*
1581                  * Finally, do chroot()
1582                  */
1583                 if (chroot(chrootdir) < 0) {
1584                         reply(550, "Can't change root.");
1585                         goto bad;
1586                 }
1587                 __FreeBSD_libc_enter_restricted_mode();
1588         } else  /* real user w/o chroot */
1589                 homedir = pw->pw_dir;
1590         /*
1591          * Set euid *before* doing chdir() so
1592          * a) the user won't be carried to a directory that he couldn't reach
1593          *    on his own due to no permission to upper path components,
1594          * b) NFS mounted homedirs w/restrictive permissions will be accessible
1595          *    (uid 0 has no root power over NFS if not mapped explicitly.)
1596          */
1597         if (seteuid(pw->pw_uid) < 0) {
1598                 if (guest || dochroot) {
1599                         fatalerror("Can't set uid.");
1600                 } else {
1601                         reply(550, "Can't set uid.");
1602                         goto bad;
1603                 }
1604         }
1605         /*
1606          * Do not allow the session to live if we're chroot()'ed and chdir()
1607          * fails. Otherwise the chroot jail can be escaped.
1608          */
1609         if (chdir(homedir) < 0) {
1610                 if (guest || dochroot) {
1611                         fatalerror("Can't change to base directory.");
1612                 } else {
1613                         if (chdir("/") < 0) {
1614                                 reply(550, "Root is inaccessible.");
1615                                 goto bad;
1616                         }
1617                         lreply(230, "No directory! Logging in with home=/.");
1618                 }
1619         }
1620
1621         /*
1622          * Display a login message, if it exists.
1623          * N.B. reply(230,) must follow the message.
1624          */
1625 #ifdef VIRTUAL_HOSTING
1626         fd = fopen(thishost->loginmsg, "r");
1627 #else
1628         fd = fopen(_PATH_FTPLOGINMESG, "r");
1629 #endif
1630         if (fd != NULL) {
1631                 char *cp, line[LINE_MAX];
1632
1633                 while (fgets(line, sizeof(line), fd) != NULL) {
1634                         if ((cp = strchr(line, '\n')) != NULL)
1635                                 *cp = '\0';
1636                         lreply(230, "%s", line);
1637                 }
1638                 (void) fflush(stdout);
1639                 (void) fclose(fd);
1640         }
1641         if (guest) {
1642                 if (ident != NULL)
1643                         free(ident);
1644                 ident = strdup(passwd);
1645                 if (ident == NULL)
1646                         fatalerror("Ran out of memory.");
1647
1648                 reply(230, "Guest login ok, access restrictions apply.");
1649 #ifdef SETPROCTITLE
1650 #ifdef VIRTUAL_HOSTING
1651                 if (thishost != firsthost)
1652                         snprintf(proctitle, sizeof(proctitle),
1653                                  "%s: anonymous(%s)/%s", remotehost, hostname,
1654                                  passwd);
1655                 else
1656 #endif
1657                         snprintf(proctitle, sizeof(proctitle),
1658                                  "%s: anonymous/%s", remotehost, passwd);
1659                 setproctitle("%s", proctitle);
1660 #endif /* SETPROCTITLE */
1661                 if (logging)
1662                         syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1663                             remotehost, passwd);
1664         } else {
1665                 if (dochroot)
1666                         reply(230, "User %s logged in, "
1667                                    "access restrictions apply.", pw->pw_name);
1668                 else
1669                         reply(230, "User %s logged in.", pw->pw_name);
1670
1671 #ifdef SETPROCTITLE
1672                 snprintf(proctitle, sizeof(proctitle),
1673                          "%s: user/%s", remotehost, pw->pw_name);
1674                 setproctitle("%s", proctitle);
1675 #endif /* SETPROCTITLE */
1676                 if (logging)
1677                         syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1678                             remotehost, pw->pw_name);
1679         }
1680         if (logging && (guest || dochroot))
1681                 syslog(LOG_INFO, "session root changed to %s", chrootdir);
1682 #ifdef  LOGIN_CAP
1683         login_close(lc);
1684 #endif
1685         if (residue)
1686                 free(residue);
1687         return;
1688 bad:
1689         /* Forget all about it... */
1690 #ifdef  LOGIN_CAP
1691         login_close(lc);
1692 #endif
1693         if (residue)
1694                 free(residue);
1695         end_login();
1696 }
1697
1698 void
1699 retrieve(char *cmd, char *name)
1700 {
1701         FILE *fin, *dout;
1702         struct stat st;
1703         int (*closefunc)(FILE *);
1704         time_t start;
1705         char line[BUFSIZ];
1706
1707         if (cmd == 0) {
1708                 fin = fopen(name, "r"), closefunc = fclose;
1709                 st.st_size = 0;
1710         } else {
1711                 (void) snprintf(line, sizeof(line), cmd, name);
1712                 name = line;
1713                 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1714                 st.st_size = -1;
1715                 st.st_blksize = BUFSIZ;
1716         }
1717         if (fin == NULL) {
1718                 if (errno != 0) {
1719                         perror_reply(550, name);
1720                         if (cmd == 0) {
1721                                 LOGCMD("get", name);
1722                         }
1723                 }
1724                 return;
1725         }
1726         byte_count = -1;
1727         if (cmd == 0) {
1728                 if (fstat(fileno(fin), &st) < 0) {
1729                         perror_reply(550, name);
1730                         goto done;
1731                 }
1732                 if (!S_ISREG(st.st_mode)) {
1733                         /*
1734                          * Never sending a raw directory is a workaround
1735                          * for buggy clients that will attempt to RETR
1736                          * a directory before listing it, e.g., Mozilla.
1737                          * Preventing a guest from getting irregular files
1738                          * is a simple security measure.
1739                          */
1740                         if (S_ISDIR(st.st_mode) || guest) {
1741                                 reply(550, "%s: not a plain file.", name);
1742                                 goto done;
1743                         }
1744                         st.st_size = -1;
1745                         /* st.st_blksize is set for all descriptor types */
1746                 }
1747         }
1748         if (restart_point) {
1749                 if (type == TYPE_A) {
1750                         off_t i, n;
1751                         int c;
1752
1753                         n = restart_point;
1754                         i = 0;
1755                         while (i++ < n) {
1756                                 if ((c=getc(fin)) == EOF) {
1757                                         perror_reply(550, name);
1758                                         goto done;
1759                                 }
1760                                 if (c == '\n')
1761                                         i++;
1762                         }
1763                 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1764                         perror_reply(550, name);
1765                         goto done;
1766                 }
1767         }
1768         dout = dataconn(name, st.st_size, "w");
1769         if (dout == NULL)
1770                 goto done;
1771         time(&start);
1772         send_data(fin, dout, st.st_blksize, st.st_size,
1773                   restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1774         if (cmd == 0 && guest && stats && byte_count > 0)
1775                 logxfer(name, byte_count, start);
1776         (void) fclose(dout);
1777         data = -1;
1778         pdata = -1;
1779 done:
1780         if (cmd == 0)
1781                 LOGBYTES("get", name, byte_count);
1782         (*closefunc)(fin);
1783 }
1784
1785 void
1786 store(char *name, char *mode, int unique)
1787 {
1788         int fd;
1789         FILE *fout, *din;
1790         int (*closefunc)(FILE *);
1791
1792         if (*mode == 'a') {             /* APPE */
1793                 if (unique) {
1794                         /* Programming error */
1795                         syslog(LOG_ERR, "Internal: unique flag to APPE");
1796                         unique = 0;
1797                 }
1798                 if (guest && noguestmod) {
1799                         reply(550, "Appending to existing file denied.");
1800                         goto err;
1801                 }
1802                 restart_point = 0;      /* not affected by preceding REST */
1803         }
1804         if (unique)                     /* STOU overrides REST */
1805                 restart_point = 0;
1806         if (guest && noguestmod) {
1807                 if (restart_point) {    /* guest STOR w/REST */
1808                         reply(550, "Modifying existing file denied.");
1809                         goto err;
1810                 } else                  /* treat guest STOR as STOU */
1811                         unique = 1;
1812         }
1813
1814         if (restart_point)
1815                 mode = "r+";    /* so ASCII manual seek can work */
1816         if (unique) {
1817                 if ((fd = guniquefd(name, &name)) < 0)
1818                         goto err;
1819                 fout = fdopen(fd, mode);
1820         } else
1821                 fout = fopen(name, mode);
1822         closefunc = fclose;
1823         if (fout == NULL) {
1824                 perror_reply(553, name);
1825                 goto err;
1826         }
1827         byte_count = -1;
1828         if (restart_point) {
1829                 if (type == TYPE_A) {
1830                         off_t i, n;
1831                         int c;
1832
1833                         n = restart_point;
1834                         i = 0;
1835                         while (i++ < n) {
1836                                 if ((c=getc(fout)) == EOF) {
1837                                         perror_reply(550, name);
1838                                         goto done;
1839                                 }
1840                                 if (c == '\n')
1841                                         i++;
1842                         }
1843                         /*
1844                          * We must do this seek to "current" position
1845                          * because we are changing from reading to
1846                          * writing.
1847                          */
1848                         if (fseeko(fout, 0, SEEK_CUR) < 0) {
1849                                 perror_reply(550, name);
1850                                 goto done;
1851                         }
1852                 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1853                         perror_reply(550, name);
1854                         goto done;
1855                 }
1856         }
1857         din = dataconn(name, -1, "r");
1858         if (din == NULL)
1859                 goto done;
1860         if (receive_data(din, fout) == 0) {
1861                 if (unique)
1862                         reply(226, "Transfer complete (unique file name:%s).",
1863                             name);
1864                 else
1865                         reply(226, "Transfer complete.");
1866         }
1867         (void) fclose(din);
1868         data = -1;
1869         pdata = -1;
1870 done:
1871         LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1872         (*closefunc)(fout);
1873         return;
1874 err:
1875         LOGCMD(*mode == 'a' ? "append" : "put" , name);
1876         return;
1877 }
1878
1879 static FILE *
1880 getdatasock(char *mode)
1881 {
1882         int on = 1, s, t, tries;
1883
1884         if (data >= 0)
1885                 return (fdopen(data, mode));
1886
1887         s = socket(data_dest.su_family, SOCK_STREAM, 0);
1888         if (s < 0)
1889                 goto bad;
1890         if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1891                 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1892         /* anchor socket to avoid multi-homing problems */
1893         data_source = ctrl_addr;
1894         data_source.su_port = htons(dataport);
1895         (void) seteuid(0);
1896         for (tries = 1; ; tries++) {
1897                 /*
1898                  * We should loop here since it's possible that
1899                  * another ftpd instance has passed this point and is
1900                  * trying to open a data connection in active mode now.
1901                  * Until the other connection is opened, we'll be getting
1902                  * EADDRINUSE because no SOCK_STREAM sockets in the system
1903                  * can share both local and remote addresses, localIP:20
1904                  * and *:* in this case.
1905                  */
1906                 if (bind(s, (struct sockaddr *)&data_source,
1907                     data_source.su_len) >= 0)
1908                         break;
1909                 if (errno != EADDRINUSE || tries > 10)
1910                         goto bad;
1911                 sleep(tries);
1912         }
1913         (void) seteuid(pw->pw_uid);
1914 #ifdef IP_TOS
1915         if (data_source.su_family == AF_INET)
1916       {
1917         on = IPTOS_THROUGHPUT;
1918         if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1919                 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1920       }
1921 #endif
1922 #ifdef TCP_NOPUSH
1923         /*
1924          * Turn off push flag to keep sender TCP from sending short packets
1925          * at the boundaries of each write().
1926          */
1927         on = 1;
1928         if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1929                 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1930 #endif
1931         return (fdopen(s, mode));
1932 bad:
1933         /* Return the real value of errno (close may change it) */
1934         t = errno;
1935         (void) seteuid(pw->pw_uid);
1936         (void) close(s);
1937         errno = t;
1938         return (NULL);
1939 }
1940
1941 static FILE *
1942 dataconn(char *name, off_t size, char *mode)
1943 {
1944         char sizebuf[32];
1945         FILE *file;
1946         int retry = 0, tos, conerrno;
1947
1948         file_size = size;
1949         byte_count = 0;
1950         if (size != -1)
1951                 (void) snprintf(sizebuf, sizeof(sizebuf),
1952                                 " (%jd bytes)", (intmax_t)size);
1953         else
1954                 *sizebuf = '\0';
1955         if (pdata >= 0) {
1956                 union sockunion from;
1957                 socklen_t fromlen = ctrl_addr.su_len;
1958                 int flags, s;
1959                 struct timeval timeout;
1960                 fd_set set;
1961
1962                 FD_ZERO(&set);
1963                 FD_SET(pdata, &set);
1964
1965                 timeout.tv_usec = 0;
1966                 timeout.tv_sec = 120;
1967
1968                 /*
1969                  * Granted a socket is in the blocking I/O mode,
1970                  * accept() will block after a successful select()
1971                  * if the selected connection dies in between.
1972                  * Therefore set the non-blocking I/O flag here.
1973                  */
1974                 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1975                     fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1976                         goto pdata_err;
1977                 if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
1978                     (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1979                         goto pdata_err;
1980                 (void) close(pdata);
1981                 pdata = s;
1982                 /*
1983                  * Unset the inherited non-blocking I/O flag
1984                  * on the child socket so stdio can work on it.
1985                  */
1986                 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1987                     fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1988                         goto pdata_err;
1989 #ifdef IP_TOS
1990                 if (from.su_family == AF_INET)
1991               {
1992                 tos = IPTOS_THROUGHPUT;
1993                 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1994                         syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1995               }
1996 #endif
1997                 reply(150, "Opening %s mode data connection for '%s'%s.",
1998                      type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1999                 return (fdopen(pdata, mode));
2000 pdata_err:
2001                 reply(425, "Can't open data connection.");
2002                 (void) close(pdata);
2003                 pdata = -1;
2004                 return (NULL);
2005         }
2006         if (data >= 0) {
2007                 reply(125, "Using existing data connection for '%s'%s.",
2008                     name, sizebuf);
2009                 usedefault = 1;
2010                 return (fdopen(data, mode));
2011         }
2012         if (usedefault)
2013                 data_dest = his_addr;
2014         usedefault = 1;
2015         do {
2016                 file = getdatasock(mode);
2017                 if (file == NULL) {
2018                         char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
2019
2020                         if (getnameinfo((struct sockaddr *)&data_source,
2021                                 data_source.su_len,
2022                                 hostbuf, sizeof(hostbuf) - 1,
2023                                 portbuf, sizeof(portbuf) - 1,
2024                                 NI_NUMERICHOST|NI_NUMERICSERV))
2025                                         *hostbuf = *portbuf = 0;
2026                         hostbuf[sizeof(hostbuf) - 1] = 0;
2027                         portbuf[sizeof(portbuf) - 1] = 0;
2028                         reply(425, "Can't create data socket (%s,%s): %s.",
2029                                 hostbuf, portbuf, strerror(errno));
2030                         return (NULL);
2031                 }
2032                 data = fileno(file);
2033                 conerrno = 0;
2034                 if (connect(data, (struct sockaddr *)&data_dest,
2035                     data_dest.su_len) == 0)
2036                         break;
2037                 conerrno = errno;
2038                 (void) fclose(file);
2039                 data = -1;
2040                 if (conerrno == EADDRINUSE) {
2041                         sleep(swaitint);
2042                         retry += swaitint;
2043                 } else {
2044                         break;
2045                 }
2046         } while (retry <= swaitmax);
2047         if (conerrno != 0) {
2048                 reply(425, "Can't build data connection: %s.",
2049                            strerror(conerrno));
2050                 return (NULL);
2051         }
2052         reply(150, "Opening %s mode data connection for '%s'%s.",
2053              type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2054         return (file);
2055 }
2056
2057 /*
2058  * A helper macro to avoid code duplication
2059  * in send_data() and receive_data().
2060  *
2061  * XXX We have to block SIGURG during putc() because BSD stdio
2062  * is unable to restart interrupted write operations and hence
2063  * the entire buffer contents will be lost as soon as a write()
2064  * call indicates EINTR to stdio.
2065  */
2066 #define FTPD_PUTC(ch, file, label)                                      \
2067         do {                                                            \
2068                 int ret;                                                \
2069                                                                         \
2070                 do {                                                    \
2071                         START_UNSAFE;                                   \
2072                         ret = putc((ch), (file));                       \
2073                         END_UNSAFE;                                     \
2074                         CHECKOOB(return (-1))                           \
2075                         else if (ferror(file))                          \
2076                                 goto label;                             \
2077                         clearerr(file);                                 \
2078                 } while (ret == EOF);                                   \
2079         } while (0)
2080
2081 /*
2082  * Transfer the contents of "instr" to "outstr" peer using the appropriate
2083  * encapsulation of the data subject to Mode, Structure, and Type.
2084  *
2085  * NB: Form isn't handled.
2086  */
2087 static int
2088 send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2089 {
2090         int c, cp, filefd, netfd;
2091         char *buf;
2092
2093         STARTXFER;
2094
2095         switch (type) {
2096
2097         case TYPE_A:
2098                 cp = EOF;
2099                 for (;;) {
2100                         c = getc(instr);
2101                         CHECKOOB(return (-1))
2102                         else if (c == EOF && ferror(instr))
2103                                 goto file_err;
2104                         if (c == EOF) {
2105                                 if (ferror(instr)) {    /* resume after OOB */
2106                                         clearerr(instr);
2107                                         continue;
2108                                 }
2109                                 if (feof(instr))        /* EOF */
2110                                         break;
2111                                 syslog(LOG_ERR, "Internal: impossible condition"
2112                                                 " on file after getc()");
2113                                 goto file_err;
2114                         }
2115                         if (c == '\n' && cp != '\r') {
2116                                 FTPD_PUTC('\r', outstr, data_err);
2117                                 byte_count++;
2118                         }
2119                         FTPD_PUTC(c, outstr, data_err);
2120                         byte_count++;
2121                         cp = c;
2122                 }
2123 #ifdef notyet   /* BSD stdio isn't ready for that */
2124                 while (fflush(outstr) == EOF) {
2125                         CHECKOOB(return (-1))
2126                         else
2127                                 goto data_err;
2128                         clearerr(outstr);
2129                 }
2130                 ENDXFER;
2131 #else
2132                 ENDXFER;
2133                 if (fflush(outstr) == EOF)
2134                         goto data_err;
2135 #endif
2136                 reply(226, "Transfer complete.");
2137                 return (0);
2138
2139         case TYPE_I:
2140         case TYPE_L:
2141                 /*
2142                  * isreg is only set if we are not doing restart and we
2143                  * are sending a regular file
2144                  */
2145                 netfd = fileno(outstr);
2146                 filefd = fileno(instr);
2147
2148                 if (isreg) {
2149                         char *msg = "Transfer complete.";
2150                         off_t cnt, offset;
2151                         int err;
2152
2153                         cnt = offset = 0;
2154
2155                         while (filesize > 0) {
2156                                 err = sendfile(filefd, netfd, offset, 0,
2157                                                NULL, &cnt, 0);
2158                                 /*
2159                                  * Calculate byte_count before OOB processing.
2160                                  * It can be used in myoob() later.
2161                                  */
2162                                 byte_count += cnt;
2163                                 offset += cnt;
2164                                 filesize -= cnt;
2165                                 CHECKOOB(return (-1))
2166                                 else if (err == -1) {
2167                                         if (errno != EINTR &&
2168                                             cnt == 0 && offset == 0)
2169                                                 goto oldway;
2170                                         goto data_err;
2171                                 }
2172                                 if (err == -1)  /* resume after OOB */
2173                                         continue;
2174                                 /*
2175                                  * We hit the EOF prematurely.
2176                                  * Perhaps the file was externally truncated.
2177                                  */
2178                                 if (cnt == 0) {
2179                                         msg = "Transfer finished due to "
2180                                               "premature end of file.";
2181                                         break;
2182                                 }
2183                         }
2184                         ENDXFER;
2185                         reply(226, "%s", msg);
2186                         return (0);
2187                 }
2188
2189 oldway:
2190                 if ((buf = malloc(blksize)) == NULL) {
2191                         ENDXFER;
2192                         reply(451, "Ran out of memory.");
2193                         return (-1);
2194                 }
2195
2196                 for (;;) {
2197                         int cnt, len;
2198                         char *bp;
2199
2200                         cnt = read(filefd, buf, blksize);
2201                         CHECKOOB(free(buf); return (-1))
2202                         else if (cnt < 0) {
2203                                 free(buf);
2204                                 goto file_err;
2205                         }
2206                         if (cnt < 0)    /* resume after OOB */
2207                                 continue;
2208                         if (cnt == 0)   /* EOF */
2209                                 break;
2210                         for (len = cnt, bp = buf; len > 0;) {
2211                                 cnt = write(netfd, bp, len);
2212                                 CHECKOOB(free(buf); return (-1))
2213                                 else if (cnt < 0) {
2214                                         free(buf);
2215                                         goto data_err;
2216                                 }
2217                                 if (cnt <= 0)
2218                                         continue;
2219                                 len -= cnt;
2220                                 bp += cnt;
2221                                 byte_count += cnt;
2222                         }
2223                 }
2224                 ENDXFER;
2225                 free(buf);
2226                 reply(226, "Transfer complete.");
2227                 return (0);
2228         default:
2229                 ENDXFER;
2230                 reply(550, "Unimplemented TYPE %d in send_data.", type);
2231                 return (-1);
2232         }
2233
2234 data_err:
2235         ENDXFER;
2236         perror_reply(426, "Data connection");
2237         return (-1);
2238
2239 file_err:
2240         ENDXFER;
2241         perror_reply(551, "Error on input file");
2242         return (-1);
2243 }
2244
2245 /*
2246  * Transfer data from peer to "outstr" using the appropriate encapulation of
2247  * the data subject to Mode, Structure, and Type.
2248  *
2249  * N.B.: Form isn't handled.
2250  */
2251 static int
2252 receive_data(FILE *instr, FILE *outstr)
2253 {
2254         int c, cp;
2255         int bare_lfs = 0;
2256
2257         STARTXFER;
2258
2259         switch (type) {
2260
2261         case TYPE_I:
2262         case TYPE_L:
2263                 for (;;) {
2264                         int cnt, len;
2265                         char *bp;
2266                         char buf[BUFSIZ];
2267
2268                         cnt = read(fileno(instr), buf, sizeof(buf));
2269                         CHECKOOB(return (-1))
2270                         else if (cnt < 0)
2271                                 goto data_err;
2272                         if (cnt < 0)    /* resume after OOB */
2273                                 continue;
2274                         if (cnt == 0)   /* EOF */
2275                                 break;
2276                         for (len = cnt, bp = buf; len > 0;) {
2277                                 cnt = write(fileno(outstr), bp, len);
2278                                 CHECKOOB(return (-1))
2279                                 else if (cnt < 0)
2280                                         goto file_err;
2281                                 if (cnt <= 0)
2282                                         continue;
2283                                 len -= cnt;
2284                                 bp += cnt;
2285                                 byte_count += cnt;
2286                         }
2287                 }
2288                 ENDXFER;
2289                 return (0);
2290
2291         case TYPE_E:
2292                 ENDXFER;
2293                 reply(553, "TYPE E not implemented.");
2294                 return (-1);
2295
2296         case TYPE_A:
2297                 cp = EOF;
2298                 for (;;) {
2299                         c = getc(instr);
2300                         CHECKOOB(return (-1))
2301                         else if (c == EOF && ferror(instr))
2302                                 goto data_err;
2303                         if (c == EOF && ferror(instr)) { /* resume after OOB */
2304                                 clearerr(instr);
2305                                 continue;
2306                         }
2307
2308                         if (cp == '\r') {
2309                                 if (c != '\n')
2310                                         FTPD_PUTC('\r', outstr, file_err);
2311                         } else
2312                                 if (c == '\n')
2313                                         bare_lfs++;
2314                         if (c == '\r') {
2315                                 byte_count++;
2316                                 cp = c;
2317                                 continue;
2318                         }
2319
2320                         /* Check for EOF here in order not to lose last \r. */
2321                         if (c == EOF) {
2322                                 if (feof(instr))        /* EOF */
2323                                         break;
2324                                 syslog(LOG_ERR, "Internal: impossible condition"
2325                                                 " on data stream after getc()");
2326                                 goto data_err;
2327                         }
2328
2329                         byte_count++;
2330                         FTPD_PUTC(c, outstr, file_err);
2331                         cp = c;
2332                 }
2333 #ifdef notyet   /* BSD stdio isn't ready for that */
2334                 while (fflush(outstr) == EOF) {
2335                         CHECKOOB(return (-1))
2336                         else
2337                                 goto file_err;
2338                         clearerr(outstr);
2339                 }
2340                 ENDXFER;
2341 #else
2342                 ENDXFER;
2343                 if (fflush(outstr) == EOF)
2344                         goto file_err;
2345 #endif
2346                 if (bare_lfs) {
2347                         lreply(226,
2348                 "WARNING! %d bare linefeeds received in ASCII mode.",
2349                             bare_lfs);
2350                 (void)printf("   File may not have transferred correctly.\r\n");
2351                 }
2352                 return (0);
2353         default:
2354                 ENDXFER;
2355                 reply(550, "Unimplemented TYPE %d in receive_data.", type);
2356                 return (-1);
2357         }
2358
2359 data_err:
2360         ENDXFER;
2361         perror_reply(426, "Data connection");
2362         return (-1);
2363
2364 file_err:
2365         ENDXFER;
2366         perror_reply(452, "Error writing to file");
2367         return (-1);
2368 }
2369
2370 void
2371 statfilecmd(char *filename)
2372 {
2373         FILE *fin;
2374         int atstart;
2375         int c, code;
2376         char line[LINE_MAX];
2377         struct stat st;
2378
2379         code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2380         (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2381         fin = ftpd_popen(line, "r");
2382         if (fin == NULL) {
2383                 perror_reply(551, filename);
2384                 return;
2385         }
2386         lreply(code, "Status of %s:", filename);
2387         atstart = 1;
2388         while ((c = getc(fin)) != EOF) {
2389                 if (c == '\n') {
2390                         if (ferror(stdout)){
2391                                 perror_reply(421, "Control connection");
2392                                 (void) ftpd_pclose(fin);
2393                                 dologout(1);
2394                                 /* NOTREACHED */
2395                         }
2396                         if (ferror(fin)) {
2397                                 perror_reply(551, filename);
2398                                 (void) ftpd_pclose(fin);
2399                                 return;
2400                         }
2401                         (void) putc('\r', stdout);
2402                 }
2403                 /*
2404                  * RFC 959 says neutral text should be prepended before
2405                  * a leading 3-digit number followed by whitespace, but
2406                  * many ftp clients can be confused by any leading digits,
2407                  * as a matter of fact.
2408                  */
2409                 if (atstart && isdigit(c))
2410                         (void) putc(' ', stdout);
2411                 (void) putc(c, stdout);
2412                 atstart = (c == '\n');
2413         }
2414         (void) ftpd_pclose(fin);
2415         reply(code, "End of status.");
2416 }
2417
2418 void
2419 statcmd(void)
2420 {
2421         union sockunion *su;
2422         u_char *a, *p;
2423         char hname[NI_MAXHOST];
2424         int ispassive;
2425
2426         if (hostinfo) {
2427                 lreply(211, "%s FTP server status:", hostname);
2428                 printf("     %s\r\n", version);
2429         } else
2430                 lreply(211, "FTP server status:");
2431         printf("     Connected to %s", remotehost);
2432         if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2433                          hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2434                 hname[sizeof(hname) - 1] = 0;
2435                 if (strcmp(hname, remotehost) != 0)
2436                         printf(" (%s)", hname);
2437         }
2438         printf("\r\n");
2439         if (logged_in) {
2440                 if (guest)
2441                         printf("     Logged in anonymously\r\n");
2442                 else
2443                         printf("     Logged in as %s\r\n", pw->pw_name);
2444         } else if (askpasswd)
2445                 printf("     Waiting for password\r\n");
2446         else
2447                 printf("     Waiting for user name\r\n");
2448         printf("     TYPE: %s", typenames[type]);
2449         if (type == TYPE_A || type == TYPE_E)
2450                 printf(", FORM: %s", formnames[form]);
2451         if (type == TYPE_L)
2452 #if CHAR_BIT == 8
2453                 printf(" %d", CHAR_BIT);
2454 #else
2455                 printf(" %d", bytesize);        /* need definition! */
2456 #endif
2457         printf("; STRUcture: %s; transfer MODE: %s\r\n",
2458             strunames[stru], modenames[mode]);
2459         if (data != -1)
2460                 printf("     Data connection open\r\n");
2461         else if (pdata != -1) {
2462                 ispassive = 1;
2463                 su = &pasv_addr;
2464                 goto printaddr;
2465         } else if (usedefault == 0) {
2466                 ispassive = 0;
2467                 su = &data_dest;
2468 printaddr:
2469 #define UC(b) (((int) b) & 0xff)
2470                 if (epsvall) {
2471                         printf("     EPSV only mode (EPSV ALL)\r\n");
2472                         goto epsvonly;
2473                 }
2474
2475                 /* PORT/PASV */
2476                 if (su->su_family == AF_INET) {
2477                         a = (u_char *) &su->su_sin.sin_addr;
2478                         p = (u_char *) &su->su_sin.sin_port;
2479                         printf("     %s (%d,%d,%d,%d,%d,%d)\r\n",
2480                                 ispassive ? "PASV" : "PORT",
2481                                 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2482                                 UC(p[0]), UC(p[1]));
2483                 }
2484
2485                 /* LPRT/LPSV */
2486             {
2487                 int alen, af, i;
2488
2489                 switch (su->su_family) {
2490                 case AF_INET:
2491                         a = (u_char *) &su->su_sin.sin_addr;
2492                         p = (u_char *) &su->su_sin.sin_port;
2493                         alen = sizeof(su->su_sin.sin_addr);
2494                         af = 4;
2495                         break;
2496                 case AF_INET6:
2497                         a = (u_char *) &su->su_sin6.sin6_addr;
2498                         p = (u_char *) &su->su_sin6.sin6_port;
2499                         alen = sizeof(su->su_sin6.sin6_addr);
2500                         af = 6;
2501                         break;
2502                 default:
2503                         af = 0;
2504                         break;
2505                 }
2506                 if (af) {
2507                         printf("     %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2508                                 af, alen);
2509                         for (i = 0; i < alen; i++)
2510                                 printf("%d,", UC(a[i]));
2511                         printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2512                 }
2513             }
2514
2515 epsvonly:;
2516                 /* EPRT/EPSV */
2517             {
2518                 int af;
2519
2520                 switch (su->su_family) {
2521                 case AF_INET:
2522                         af = 1;
2523                         break;
2524                 case AF_INET6:
2525                         af = 2;
2526                         break;
2527                 default:
2528                         af = 0;
2529                         break;
2530                 }
2531                 if (af) {
2532                         union sockunion tmp;
2533
2534                         tmp = *su;
2535                         if (tmp.su_family == AF_INET6)
2536                                 tmp.su_sin6.sin6_scope_id = 0;
2537                         if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2538                                         hname, sizeof(hname) - 1, NULL, 0,
2539                                         NI_NUMERICHOST)) {
2540                                 hname[sizeof(hname) - 1] = 0;
2541                                 printf("     %s |%d|%s|%d|\r\n",
2542                                         ispassive ? "EPSV" : "EPRT",
2543                                         af, hname, htons(tmp.su_port));
2544                         }
2545                 }
2546             }
2547 #undef UC
2548         } else
2549                 printf("     No data connection\r\n");
2550         reply(211, "End of status.");
2551 }
2552
2553 void
2554 fatalerror(char *s)
2555 {
2556
2557         reply(451, "Error in server: %s", s);
2558         reply(221, "Closing connection due to server error.");
2559         dologout(0);
2560         /* NOTREACHED */
2561 }
2562
2563 void
2564 reply(int n, const char *fmt, ...)
2565 {
2566         va_list ap;
2567
2568         (void)printf("%d ", n);
2569         va_start(ap, fmt);
2570         (void)vprintf(fmt, ap);
2571         va_end(ap);
2572         (void)printf("\r\n");
2573         (void)fflush(stdout);
2574         if (ftpdebug) {
2575                 syslog(LOG_DEBUG, "<--- %d ", n);
2576                 va_start(ap, fmt);
2577                 vsyslog(LOG_DEBUG, fmt, ap);
2578                 va_end(ap);
2579         }
2580 }
2581
2582 void
2583 lreply(int n, const char *fmt, ...)
2584 {
2585         va_list ap;
2586
2587         (void)printf("%d- ", n);
2588         va_start(ap, fmt);
2589         (void)vprintf(fmt, ap);
2590         va_end(ap);
2591         (void)printf("\r\n");
2592         (void)fflush(stdout);
2593         if (ftpdebug) {
2594                 syslog(LOG_DEBUG, "<--- %d- ", n);
2595                 va_start(ap, fmt);
2596                 vsyslog(LOG_DEBUG, fmt, ap);
2597                 va_end(ap);
2598         }
2599 }
2600
2601 static void
2602 ack(char *s)
2603 {
2604
2605         reply(250, "%s command successful.", s);
2606 }
2607
2608 void
2609 nack(char *s)
2610 {
2611
2612         reply(502, "%s command not implemented.", s);
2613 }
2614
2615 /* ARGSUSED */
2616 void
2617 yyerror(char *s)
2618 {
2619         char *cp;
2620
2621         if ((cp = strchr(cbuf,'\n')))
2622                 *cp = '\0';
2623         reply(500, "%s: command not understood.", cbuf);
2624 }
2625
2626 void
2627 delete(char *name)
2628 {
2629         struct stat st;
2630
2631         LOGCMD("delete", name);
2632         if (lstat(name, &st) < 0) {
2633                 perror_reply(550, name);
2634                 return;
2635         }
2636         if (S_ISDIR(st.st_mode)) {
2637                 if (rmdir(name) < 0) {
2638                         perror_reply(550, name);
2639                         return;
2640                 }
2641                 goto done;
2642         }
2643         if (guest && noguestmod) {
2644                 reply(550, "Operation not permitted.");
2645                 return;
2646         }
2647         if (unlink(name) < 0) {
2648                 perror_reply(550, name);
2649                 return;
2650         }
2651 done:
2652         ack("DELE");
2653 }
2654
2655 void
2656 cwd(char *path)
2657 {
2658
2659         if (chdir(path) < 0)
2660                 perror_reply(550, path);
2661         else
2662                 ack("CWD");
2663 }
2664
2665 void
2666 makedir(char *name)
2667 {
2668         char *s;
2669
2670         LOGCMD("mkdir", name);
2671         if (guest && noguestmkd)
2672                 reply(550, "Operation not permitted.");
2673         else if (mkdir(name, 0777) < 0)
2674                 perror_reply(550, name);
2675         else {
2676                 if ((s = doublequote(name)) == NULL)
2677                         fatalerror("Ran out of memory.");
2678                 reply(257, "\"%s\" directory created.", s);
2679                 free(s);
2680         }
2681 }
2682
2683 void
2684 removedir(char *name)
2685 {
2686
2687         LOGCMD("rmdir", name);
2688         if (rmdir(name) < 0)
2689                 perror_reply(550, name);
2690         else
2691                 ack("RMD");
2692 }
2693
2694 void
2695 pwd(void)
2696 {
2697         char *s, path[MAXPATHLEN + 1];
2698
2699         if (getcwd(path, sizeof(path)) == NULL)
2700                 perror_reply(550, "Get current directory");
2701         else {
2702                 if ((s = doublequote(path)) == NULL)
2703                         fatalerror("Ran out of memory.");
2704                 reply(257, "\"%s\" is current directory.", s);
2705                 free(s);
2706         }
2707 }
2708
2709 char *
2710 renamefrom(char *name)
2711 {
2712         struct stat st;
2713
2714         if (guest && noguestmod) {
2715                 reply(550, "Operation not permitted.");
2716                 return (NULL);
2717         }
2718         if (lstat(name, &st) < 0) {
2719                 perror_reply(550, name);
2720                 return (NULL);
2721         }
2722         reply(350, "File exists, ready for destination name.");
2723         return (name);
2724 }
2725
2726 void
2727 renamecmd(char *from, char *to)
2728 {
2729         struct stat st;
2730
2731         LOGCMD2("rename", from, to);
2732
2733         if (guest && (stat(to, &st) == 0)) {
2734                 reply(550, "%s: permission denied.", to);
2735                 return;
2736         }
2737
2738         if (rename(from, to) < 0)
2739                 perror_reply(550, "rename");
2740         else
2741                 ack("RNTO");
2742 }
2743
2744 static void
2745 dolog(struct sockaddr *who)
2746 {
2747         char who_name[NI_MAXHOST];
2748
2749         realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2750         remotehost[sizeof(remotehost) - 1] = 0;
2751         if (getnameinfo(who, who->sa_len,
2752                 who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
2753                         *who_name = 0;
2754         who_name[sizeof(who_name) - 1] = 0;
2755
2756 #ifdef SETPROCTITLE
2757 #ifdef VIRTUAL_HOSTING
2758         if (thishost != firsthost)
2759                 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2760                          remotehost, hostname);
2761         else
2762 #endif
2763                 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2764                          remotehost);
2765         setproctitle("%s", proctitle);
2766 #endif /* SETPROCTITLE */
2767
2768         if (logging) {
2769 #ifdef VIRTUAL_HOSTING
2770                 if (thishost != firsthost)
2771                         syslog(LOG_INFO, "connection from %s (%s) to %s",
2772                                remotehost, who_name, hostname);
2773                 else
2774 #endif
2775                         syslog(LOG_INFO, "connection from %s (%s)",
2776                                remotehost, who_name);
2777         }
2778 }
2779
2780 /*
2781  * Record logout in wtmp file
2782  * and exit with supplied status.
2783  */
2784 void
2785 dologout(int status)
2786 {
2787
2788         if (logged_in && dowtmp) {
2789                 (void) seteuid(0);
2790 #ifdef          LOGIN_CAP
2791                 setusercontext(NULL, getpwuid(0), 0, LOGIN_SETALL & ~(LOGIN_SETLOGIN |
2792                        LOGIN_SETUSER | LOGIN_SETGROUP | LOGIN_SETPATH |
2793                        LOGIN_SETENV));
2794 #endif
2795                 ftpd_logwtmp(wtmpid, NULL, NULL);
2796         }
2797         /* beware of flushing buffers after a SIGPIPE */
2798         _exit(status);
2799 }
2800
2801 static void
2802 sigurg(int signo)
2803 {
2804
2805         recvurg = 1;
2806 }
2807
2808 static void
2809 maskurg(int flag)
2810 {
2811         int oerrno;
2812         sigset_t sset;
2813
2814         if (!transflag) {
2815                 syslog(LOG_ERR, "Internal: maskurg() while no transfer");
2816                 return;
2817         }
2818         oerrno = errno;
2819         sigemptyset(&sset);
2820         sigaddset(&sset, SIGURG);
2821         sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
2822         errno = oerrno;
2823 }
2824
2825 static void
2826 flagxfer(int flag)
2827 {
2828
2829         if (flag) {
2830                 if (transflag)
2831                         syslog(LOG_ERR, "Internal: flagxfer(1): "
2832                                         "transfer already under way");
2833                 transflag = 1;
2834                 maskurg(0);
2835                 recvurg = 0;
2836         } else {
2837                 if (!transflag)
2838                         syslog(LOG_ERR, "Internal: flagxfer(0): "
2839                                         "no active transfer");
2840                 maskurg(1);
2841                 transflag = 0;
2842         }
2843 }
2844
2845 /*
2846  * Returns 0 if OK to resume or -1 if abort requested.
2847  */
2848 static int
2849 myoob(void)
2850 {
2851         char *cp;
2852         int ret;
2853
2854         if (!transflag) {
2855                 syslog(LOG_ERR, "Internal: myoob() while no transfer");
2856                 return (0);
2857         }
2858         cp = tmpline;
2859         ret = get_line(cp, 7, stdin);
2860         if (ret == -1) {
2861                 reply(221, "You could at least say goodbye.");
2862                 dologout(0);
2863         } else if (ret == -2) {
2864                 /* Ignore truncated command. */
2865                 return (0);
2866         }
2867         upper(cp);
2868         if (strcmp(cp, "ABOR\r\n") == 0) {
2869                 tmpline[0] = '\0';
2870                 reply(426, "Transfer aborted. Data connection closed.");
2871                 reply(226, "Abort successful.");
2872                 return (-1);
2873         }
2874         if (strcmp(cp, "STAT\r\n") == 0) {
2875                 tmpline[0] = '\0';
2876                 if (file_size != -1)
2877                         reply(213, "Status: %jd of %jd bytes transferred.",
2878                                    (intmax_t)byte_count, (intmax_t)file_size);
2879                 else
2880                         reply(213, "Status: %jd bytes transferred.",
2881                                    (intmax_t)byte_count);
2882         }
2883         return (0);
2884 }
2885
2886 /*
2887  * Note: a response of 425 is not mentioned as a possible response to
2888  *      the PASV command in RFC959. However, it has been blessed as
2889  *      a legitimate response by Jon Postel in a telephone conversation
2890  *      with Rick Adams on 25 Jan 89.
2891  */
2892 void
2893 passive(void)
2894 {
2895         socklen_t len;
2896         int on;
2897         char *p, *a;
2898
2899         if (pdata >= 0)         /* close old port if one set */
2900                 close(pdata);
2901
2902         pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2903         if (pdata < 0) {
2904                 perror_reply(425, "Can't open passive connection");
2905                 return;
2906         }
2907         on = 1;
2908         if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2909                 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2910
2911         (void) seteuid(0);
2912
2913 #ifdef IP_PORTRANGE
2914         if (ctrl_addr.su_family == AF_INET) {
2915             on = restricted_data_ports ? IP_PORTRANGE_HIGH
2916                                        : IP_PORTRANGE_DEFAULT;
2917
2918             if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2919                             &on, sizeof(on)) < 0)
2920                     goto pasv_error;
2921         }
2922 #endif
2923 #ifdef IPV6_PORTRANGE
2924         if (ctrl_addr.su_family == AF_INET6) {
2925             on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2926                                        : IPV6_PORTRANGE_DEFAULT;
2927
2928             if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2929                             &on, sizeof(on)) < 0)
2930                     goto pasv_error;
2931         }
2932 #endif
2933
2934         pasv_addr = ctrl_addr;
2935         pasv_addr.su_port = 0;
2936         if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2937                 goto pasv_error;
2938
2939         (void) seteuid(pw->pw_uid);
2940
2941         len = sizeof(pasv_addr);
2942         if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2943                 goto pasv_error;
2944         if (listen(pdata, 1) < 0)
2945                 goto pasv_error;
2946         if (pasv_addr.su_family == AF_INET)
2947                 a = (char *) &pasv_addr.su_sin.sin_addr;
2948         else if (pasv_addr.su_family == AF_INET6 &&
2949                  IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2950                 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2951         else
2952                 goto pasv_error;
2953                 
2954         p = (char *) &pasv_addr.su_port;
2955
2956 #define UC(b) (((int) b) & 0xff)
2957
2958         reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2959                 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2960         return;
2961
2962 pasv_error:
2963         (void) seteuid(pw->pw_uid);
2964         (void) close(pdata);
2965         pdata = -1;
2966         perror_reply(425, "Can't open passive connection");
2967         return;
2968 }
2969
2970 /*
2971  * Long Passive defined in RFC 1639.
2972  *     228 Entering Long Passive Mode
2973  *         (af, hal, h1, h2, h3,..., pal, p1, p2...)
2974  */
2975
2976 void
2977 long_passive(char *cmd, int pf)
2978 {
2979         socklen_t len;
2980         int on;
2981         char *p, *a;
2982
2983         if (pdata >= 0)         /* close old port if one set */
2984                 close(pdata);
2985
2986         if (pf != PF_UNSPEC) {
2987                 if (ctrl_addr.su_family != pf) {
2988                         switch (ctrl_addr.su_family) {
2989                         case AF_INET:
2990                                 pf = 1;
2991                                 break;
2992                         case AF_INET6:
2993                                 pf = 2;
2994                                 break;
2995                         default:
2996                                 pf = 0;
2997                                 break;
2998                         }
2999                         /*
3000                          * XXX
3001                          * only EPRT/EPSV ready clients will understand this
3002                          */
3003                         if (strcmp(cmd, "EPSV") == 0 && pf) {
3004                                 reply(522, "Network protocol mismatch, "
3005                                         "use (%d)", pf);
3006                         } else
3007                                 reply(501, "Network protocol mismatch."); /*XXX*/
3008
3009                         return;
3010                 }
3011         }
3012                 
3013         pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
3014         if (pdata < 0) {
3015                 perror_reply(425, "Can't open passive connection");
3016                 return;
3017         }
3018         on = 1;
3019         if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
3020                 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
3021
3022         (void) seteuid(0);
3023
3024         pasv_addr = ctrl_addr;
3025         pasv_addr.su_port = 0;
3026         len = pasv_addr.su_len;
3027
3028 #ifdef IP_PORTRANGE
3029         if (ctrl_addr.su_family == AF_INET) {
3030             on = restricted_data_ports ? IP_PORTRANGE_HIGH
3031                                        : IP_PORTRANGE_DEFAULT;
3032
3033             if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
3034                             &on, sizeof(on)) < 0)
3035                     goto pasv_error;
3036         }
3037 #endif
3038 #ifdef IPV6_PORTRANGE
3039         if (ctrl_addr.su_family == AF_INET6) {
3040             on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
3041                                        : IPV6_PORTRANGE_DEFAULT;
3042
3043             if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
3044                             &on, sizeof(on)) < 0)
3045                     goto pasv_error;
3046         }
3047 #endif
3048
3049         if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
3050                 goto pasv_error;
3051
3052         (void) seteuid(pw->pw_uid);
3053
3054         if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
3055                 goto pasv_error;
3056         if (listen(pdata, 1) < 0)
3057                 goto pasv_error;
3058
3059 #define UC(b) (((int) b) & 0xff)
3060
3061         if (strcmp(cmd, "LPSV") == 0) {
3062                 p = (char *)&pasv_addr.su_port;
3063                 switch (pasv_addr.su_family) {
3064                 case AF_INET:
3065                         a = (char *) &pasv_addr.su_sin.sin_addr;
3066                 v4_reply:
3067                         reply(228,
3068 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3069                               4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3070                               2, UC(p[0]), UC(p[1]));
3071                         return;
3072                 case AF_INET6:
3073                         if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
3074                                 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
3075                                 goto v4_reply;
3076                         }
3077                         a = (char *) &pasv_addr.su_sin6.sin6_addr;
3078                         reply(228,
3079 "Entering Long Passive Mode "
3080 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3081                               6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3082                               UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3083                               UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3084                               UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3085                               2, UC(p[0]), UC(p[1]));
3086                         return;
3087                 }
3088         } else if (strcmp(cmd, "EPSV") == 0) {
3089                 switch (pasv_addr.su_family) {
3090                 case AF_INET:
3091                 case AF_INET6:
3092                         reply(229, "Entering Extended Passive Mode (|||%d|)",
3093                                 ntohs(pasv_addr.su_port));
3094                         return;
3095                 }
3096         } else {
3097                 /* more proper error code? */
3098         }
3099
3100 pasv_error:
3101         (void) seteuid(pw->pw_uid);
3102         (void) close(pdata);
3103         pdata = -1;
3104         perror_reply(425, "Can't open passive connection");
3105         return;
3106 }
3107
3108 /*
3109  * Generate unique name for file with basename "local"
3110  * and open the file in order to avoid possible races.
3111  * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3112  * Return descriptor to the file, set "name" to its name.
3113  *
3114  * Generates failure reply on error.
3115  */
3116 static int
3117 guniquefd(char *local, char **name)
3118 {
3119         static char new[MAXPATHLEN];
3120         struct stat st;
3121         char *cp;
3122         int count;
3123         int fd;
3124
3125         cp = strrchr(local, '/');
3126         if (cp)
3127                 *cp = '\0';
3128         if (stat(cp ? local : ".", &st) < 0) {
3129                 perror_reply(553, cp ? local : ".");
3130                 return (-1);
3131         }
3132         if (cp) {
3133                 /*
3134                  * Let not overwrite dirname with counter suffix.
3135                  * -4 is for /nn\0
3136                  * In this extreme case dot won't be put in front of suffix.
3137                  */
3138                 if (strlen(local) > sizeof(new) - 4) {
3139                         reply(553, "Pathname too long.");
3140                         return (-1);
3141                 }
3142                 *cp = '/';
3143         }
3144         /* -4 is for the .nn<null> we put on the end below */
3145         (void) snprintf(new, sizeof(new) - 4, "%s", local);
3146         cp = new + strlen(new);
3147         /* 
3148          * Don't generate dotfile unless requested explicitly.
3149          * This covers the case when basename gets truncated off
3150          * by buffer size.
3151          */
3152         if (cp > new && cp[-1] != '/')
3153                 *cp++ = '.';
3154         for (count = 0; count < 100; count++) {
3155                 /* At count 0 try unmodified name */
3156                 if (count)
3157                         (void)sprintf(cp, "%d", count);
3158                 if ((fd = open(count ? new : local,
3159                     O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3160                         *name = count ? new : local;
3161                         return (fd);
3162                 }
3163                 if (errno != EEXIST) {
3164                         perror_reply(553, count ? new : local);
3165                         return (-1);
3166                 }
3167         }
3168         reply(452, "Unique file name cannot be created.");
3169         return (-1);
3170 }
3171
3172 /*
3173  * Format and send reply containing system error number.
3174  */
3175 void
3176 perror_reply(int code, char *string)
3177 {
3178
3179         reply(code, "%s: %s.", string, strerror(errno));
3180 }
3181
3182 static char *onefile[] = {
3183         "",
3184         0
3185 };
3186
3187 void
3188 send_file_list(char *whichf)
3189 {
3190         struct stat st;
3191         DIR *dirp = NULL;
3192         struct dirent *dir;
3193         FILE *dout = NULL;
3194         char **dirlist, *dirname;
3195         int simple = 0;
3196         int freeglob = 0;
3197         glob_t gl;
3198
3199         if (strpbrk(whichf, "~{[*?") != NULL) {
3200                 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3201
3202                 memset(&gl, 0, sizeof(gl));
3203                 gl.gl_matchc = MAXGLOBARGS;
3204                 flags |= GLOB_LIMIT;
3205                 freeglob = 1;
3206                 if (glob(whichf, flags, 0, &gl)) {
3207                         reply(550, "No matching files found.");
3208                         goto out;
3209                 } else if (gl.gl_pathc == 0) {
3210                         errno = ENOENT;
3211                         perror_reply(550, whichf);
3212                         goto out;
3213                 }
3214                 dirlist = gl.gl_pathv;
3215         } else {
3216                 onefile[0] = whichf;
3217                 dirlist = onefile;
3218                 simple = 1;
3219         }
3220
3221         while ((dirname = *dirlist++)) {
3222                 if (stat(dirname, &st) < 0) {
3223                         /*
3224                          * If user typed "ls -l", etc, and the client
3225                          * used NLST, do what the user meant.
3226                          */
3227                         if (dirname[0] == '-' && *dirlist == NULL &&
3228                             dout == NULL)
3229                                 retrieve(_PATH_LS " %s", dirname);
3230                         else
3231                                 perror_reply(550, whichf);
3232                         goto out;
3233                 }
3234
3235                 if (S_ISREG(st.st_mode)) {
3236                         if (dout == NULL) {
3237                                 dout = dataconn("file list", -1, "w");
3238                                 if (dout == NULL)
3239                                         goto out;
3240                                 STARTXFER;
3241                         }
3242                         START_UNSAFE;
3243                         fprintf(dout, "%s%s\n", dirname,
3244                                 type == TYPE_A ? "\r" : "");
3245                         END_UNSAFE;
3246                         if (ferror(dout))
3247                                 goto data_err;
3248                         byte_count += strlen(dirname) +
3249                                       (type == TYPE_A ? 2 : 1);
3250                         CHECKOOB(goto abrt);
3251                         continue;
3252                 } else if (!S_ISDIR(st.st_mode))
3253                         continue;
3254
3255                 if ((dirp = opendir(dirname)) == NULL)
3256                         continue;
3257
3258                 while ((dir = readdir(dirp)) != NULL) {
3259                         char nbuf[MAXPATHLEN];
3260
3261                         CHECKOOB(goto abrt);
3262
3263                         if (dir->d_name[0] == '.' && dir->d_namlen == 1)
3264                                 continue;
3265                         if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3266                             dir->d_namlen == 2)
3267                                 continue;
3268
3269                         snprintf(nbuf, sizeof(nbuf),
3270                                 "%s/%s", dirname, dir->d_name);
3271
3272                         /*
3273                          * We have to do a stat to insure it's
3274                          * not a directory or special file.
3275                          */
3276                         if (simple || (stat(nbuf, &st) == 0 &&
3277                             S_ISREG(st.st_mode))) {
3278                                 if (dout == NULL) {
3279                                         dout = dataconn("file list", -1, "w");
3280                                         if (dout == NULL)
3281                                                 goto out;
3282                                         STARTXFER;
3283                                 }
3284                                 START_UNSAFE;
3285                                 if (nbuf[0] == '.' && nbuf[1] == '/')
3286                                         fprintf(dout, "%s%s\n", &nbuf[2],
3287                                                 type == TYPE_A ? "\r" : "");
3288                                 else
3289                                         fprintf(dout, "%s%s\n", nbuf,
3290                                                 type == TYPE_A ? "\r" : "");
3291                                 END_UNSAFE;
3292                                 if (ferror(dout))
3293                                         goto data_err;
3294                                 byte_count += strlen(nbuf) +
3295                                               (type == TYPE_A ? 2 : 1);
3296                                 CHECKOOB(goto abrt);
3297                         }
3298                 }
3299                 (void) closedir(dirp);
3300                 dirp = NULL;
3301         }
3302
3303         if (dout == NULL)
3304                 reply(550, "No files found.");
3305         else if (ferror(dout))
3306 data_err:       perror_reply(550, "Data connection");
3307         else
3308                 reply(226, "Transfer complete.");
3309 out:
3310         if (dout) {
3311                 ENDXFER;
3312 abrt:
3313                 (void) fclose(dout);
3314                 data = -1;
3315                 pdata = -1;
3316         }
3317         if (dirp)
3318                 (void) closedir(dirp);
3319         if (freeglob) {
3320                 freeglob = 0;
3321                 globfree(&gl);
3322         }
3323 }
3324
3325 void
3326 reapchild(int signo)
3327 {
3328         while (waitpid(-1, NULL, WNOHANG) > 0);
3329 }
3330
3331 #ifdef OLD_SETPROCTITLE
3332 /*
3333  * Clobber argv so ps will show what we're doing.  (Stolen from sendmail.)
3334  * Warning, since this is usually started from inetd.conf, it often doesn't
3335  * have much of an environment or arglist to overwrite.
3336  */
3337 void
3338 setproctitle(const char *fmt, ...)
3339 {
3340         int i;
3341         va_list ap;
3342         char *p, *bp, ch;
3343         char buf[LINE_MAX];
3344
3345         va_start(ap, fmt);
3346         (void)vsnprintf(buf, sizeof(buf), fmt, ap);
3347
3348         /* make ps print our process name */
3349         p = Argv[0];
3350         *p++ = '-';
3351
3352         i = strlen(buf);
3353         if (i > LastArgv - p - 2) {
3354                 i = LastArgv - p - 2;
3355                 buf[i] = '\0';
3356         }
3357         bp = buf;
3358         while (ch = *bp++)
3359                 if (ch != '\n' && ch != '\r')
3360                         *p++ = ch;
3361         while (p < LastArgv)
3362                 *p++ = ' ';
3363 }
3364 #endif /* OLD_SETPROCTITLE */
3365
3366 static void
3367 appendf(char **strp, char *fmt, ...)
3368 {
3369         va_list ap;
3370         char *ostr, *p;
3371
3372         va_start(ap, fmt);
3373         vasprintf(&p, fmt, ap);
3374         va_end(ap);
3375         if (p == NULL)
3376                 fatalerror("Ran out of memory.");
3377         if (*strp == NULL)
3378                 *strp = p;
3379         else {
3380                 ostr = *strp;
3381                 asprintf(strp, "%s%s", ostr, p);
3382                 if (*strp == NULL)
3383                         fatalerror("Ran out of memory.");
3384                 free(ostr);
3385         }
3386 }
3387
3388 static void
3389 logcmd(char *cmd, char *file1, char *file2, off_t cnt)
3390 {
3391         char *msg = NULL;
3392         char wd[MAXPATHLEN + 1];
3393
3394         if (logging <= 1)
3395                 return;
3396
3397         if (getcwd(wd, sizeof(wd) - 1) == NULL)
3398                 strcpy(wd, strerror(errno));
3399
3400         appendf(&msg, "%s", cmd);
3401         if (file1)
3402                 appendf(&msg, " %s", file1);
3403         if (file2)
3404                 appendf(&msg, " %s", file2);
3405         if (cnt >= 0)
3406                 appendf(&msg, " = %jd bytes", (intmax_t)cnt);
3407         appendf(&msg, " (wd: %s", wd);
3408         if (guest || dochroot)
3409                 appendf(&msg, "; chrooted");
3410         appendf(&msg, ")");
3411         syslog(LOG_INFO, "%s", msg);
3412         free(msg);
3413 }
3414
3415 static void
3416 logxfer(char *name, off_t size, time_t start)
3417 {
3418         char buf[MAXPATHLEN + 1024];
3419         char path[MAXPATHLEN + 1];
3420         time_t now;
3421
3422         if (statfd >= 0) {
3423                 time(&now);
3424                 if (realpath(name, path) == NULL) {
3425                         syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
3426                         return;
3427                 }
3428                 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n",
3429                         ctime(&now)+4, ident, remotehost,
3430                         path, (intmax_t)size,
3431                         (long)(now - start + (now == start)));
3432                 write(statfd, buf, strlen(buf));
3433         }
3434 }
3435
3436 static char *
3437 doublequote(char *s)
3438 {
3439         int n;
3440         char *p, *s2;
3441
3442         for (p = s, n = 0; *p; p++)
3443                 if (*p == '"')
3444                         n++;
3445
3446         if ((s2 = malloc(p - s + n + 1)) == NULL)
3447                 return (NULL);
3448
3449         for (p = s2; *s; s++, p++) {
3450                 if ((*p = *s) == '"')
3451                         *(++p) = '"';
3452         }
3453         *p = '\0';
3454
3455         return (s2);
3456 }
3457
3458 /* setup server socket for specified address family */
3459 /* if af is PF_UNSPEC more than one socket may be returned */
3460 /* the returned list is dynamically allocated, so caller needs to free it */
3461 static int *
3462 socksetup(int af, char *bindname, const char *bindport)
3463 {
3464         struct addrinfo hints, *res, *r;
3465         int error, maxs, *s, *socks;
3466         const int on = 1;
3467
3468         memset(&hints, 0, sizeof(hints));
3469         hints.ai_flags = AI_PASSIVE;
3470         hints.ai_family = af;
3471         hints.ai_socktype = SOCK_STREAM;
3472         error = getaddrinfo(bindname, bindport, &hints, &res);
3473         if (error) {
3474                 syslog(LOG_ERR, "%s", gai_strerror(error));
3475                 if (error == EAI_SYSTEM)
3476                         syslog(LOG_ERR, "%s", strerror(errno));
3477                 return NULL;
3478         }
3479
3480         /* Count max number of sockets we may open */
3481         for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3482                 ;
3483         socks = malloc((maxs + 1) * sizeof(int));
3484         if (!socks) {
3485                 freeaddrinfo(res);
3486                 syslog(LOG_ERR, "couldn't allocate memory for sockets");
3487                 return NULL;
3488         }
3489
3490         *socks = 0;   /* num of sockets counter at start of array */
3491         s = socks + 1;
3492         for (r = res; r; r = r->ai_next) {
3493                 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3494                 if (*s < 0) {
3495                         syslog(LOG_DEBUG, "control socket: %m");
3496                         continue;
3497                 }
3498                 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3499                     &on, sizeof(on)) < 0)
3500                         syslog(LOG_WARNING,
3501                             "control setsockopt (SO_REUSEADDR): %m");
3502                 if (r->ai_family == AF_INET6) {
3503                         if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3504                             &on, sizeof(on)) < 0)
3505                                 syslog(LOG_WARNING,
3506                                     "control setsockopt (IPV6_V6ONLY): %m");
3507                 }
3508                 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3509                         syslog(LOG_DEBUG, "control bind: %m");
3510                         close(*s);
3511                         continue;
3512                 }
3513                 (*socks)++;
3514                 s++;
3515         }
3516
3517         if (res)
3518                 freeaddrinfo(res);
3519
3520         if (*socks == 0) {
3521                 syslog(LOG_ERR, "control socket: Couldn't bind to any socket");
3522                 free(socks);
3523                 return NULL;
3524         }
3525         return(socks);
3526 }