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