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