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