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