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