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