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