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