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