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