]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - libexec/ftpd/ftpd.c
Fix setting parameters for getipnodebyaddr(3):
[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
256 static char *
257 curdir(void)
258 {
259         static char path[MAXPATHLEN+1+1];       /* path + '/' + '\0' */
260
261         if (getcwd(path, sizeof(path)-2) == NULL)
262                 return ("");
263         if (path[1] != '\0')            /* special case for root dir. */
264                 strcat(path, "/");
265         /* For guest account, skip / since it's chrooted */
266         return (guest ? path+1 : path);
267 }
268
269 int
270 main(int argc, char *argv[], char **envp)
271 {
272         int addrlen, ch, on = 1, tos;
273         char *cp, line[LINE_MAX];
274         FILE *fd;
275         int error;
276         char    *bindname = NULL;
277         int     family = AF_UNSPEC;
278         int     enable_v4 = 0;
279         struct sigaction sa;
280
281         tzset();                /* in case no timezone database in ~ftp */
282         sigemptyset(&sa.sa_mask);
283         sa.sa_flags = SA_RESTART;
284
285 #ifdef OLD_SETPROCTITLE
286         /*
287          *  Save start and extent of argv for setproctitle.
288          */
289         Argv = argv;
290         while (*envp)
291                 envp++;
292         LastArgv = envp[-1] + strlen(envp[-1]);
293 #endif /* OLD_SETPROCTITLE */
294
295
296         while ((ch = getopt(argc, argv, "AdlDESURrt:T:u:vMOoa:p:46")) != -1) {
297                 switch (ch) {
298                 case 'D':
299                         daemon_mode++;
300                         break;
301
302                 case 'd':
303                         ftpdebug++;
304                         break;
305
306                 case 'E':
307                         noepsv = 1;
308                         break;
309
310                 case 'l':
311                         logging++;      /* > 1 == extra logging */
312                         break;
313
314                 case 'r':
315                         readonly = 1;
316                         break;
317
318                 case 'R':
319                         paranoid = 0;
320                         break;
321
322                 case 'S':
323                         stats++;
324                         break;
325
326                 case 'T':
327                         maxtimeout = atoi(optarg);
328                         if (timeout > maxtimeout)
329                                 timeout = maxtimeout;
330                         break;
331
332                 case 't':
333                         timeout = atoi(optarg);
334                         if (maxtimeout < timeout)
335                                 maxtimeout = timeout;
336                         break;
337
338                 case 'U':
339                         restricted_data_ports = 0;
340                         break;
341
342                 case 'a':
343                         bindname = optarg;
344                         break;
345
346                 case 'p':
347                         pid_file = optarg;
348                         break;
349
350                 case 'u':
351                     {
352                         long val = 0;
353
354                         val = strtol(optarg, &optarg, 8);
355                         if (*optarg != '\0' || val < 0)
356                                 warnx("bad value for -u");
357                         else
358                                 defumask = val;
359                         break;
360                     }
361                 case 'A':
362                         anon_only = 1;
363                         break;
364
365                 case 'v':
366                         ftpdebug = 1;
367                         break;
368
369                 case '4':
370                         enable_v4 = 1;
371                         if (family == AF_UNSPEC)
372                                 family = AF_INET;
373                         break;
374
375                 case '6':
376                         family = AF_INET6;
377                         break;
378
379                 case 'M':
380                         noguestmkd = 1;
381                         break;
382
383                 case 'O':
384                         noguestretr = 1;
385                         break;
386
387                 case 'o':
388                         noretr = 1;
389                         break;
390
391                 default:
392                         warnx("unknown flag -%c ignored", optopt);
393                         break;
394                 }
395         }
396
397 #ifdef VIRTUAL_HOSTING
398         inithosts();
399 #endif
400         (void) freopen(_PATH_DEVNULL, "w", stderr);
401
402         /*
403          * LOG_NDELAY sets up the logging connection immediately,
404          * necessary for anonymous ftp's that chroot and can't do it later.
405          */
406         openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
407
408         if (daemon_mode) {
409                 int ctl_sock, fd;
410                 struct addrinfo hints, *res;
411
412                 /*
413                  * Detach from parent.
414                  */
415                 if (daemon(1, 1) < 0) {
416                         syslog(LOG_ERR, "failed to become a daemon");
417                         exit(1);
418                 }
419                 sa.sa_handler = reapchild;
420                 (void)sigaction(SIGCHLD, &sa, NULL);
421                 /* init bind_sa */
422                 memset(&hints, 0, sizeof(hints));
423
424                 hints.ai_family = family == AF_UNSPEC ? AF_INET : family;
425                 hints.ai_socktype = SOCK_STREAM;
426                 hints.ai_protocol = 0;
427                 hints.ai_flags = AI_PASSIVE;
428                 error = getaddrinfo(bindname, "ftp", &hints, &res);
429                 if (error) {
430                         if (family == AF_UNSPEC) {
431                                 hints.ai_family = AF_UNSPEC;
432                                 error = getaddrinfo(bindname, "ftp", &hints,
433                                                     &res);
434                         }
435                 }
436                 if (error) {
437                         syslog(LOG_ERR, "%s", gai_strerror(error));
438                         if (error == EAI_SYSTEM)
439                                 syslog(LOG_ERR, "%s", strerror(errno));
440                         exit(1);
441                 }
442                 if (res->ai_addr == NULL) {
443                         syslog(LOG_ERR, "-a %s: getaddrinfo failed", hostname);
444                         exit(1);
445                 } else
446                         family = res->ai_addr->sa_family;
447                 /*
448                  * Open a socket, bind it to the FTP port, and start
449                  * listening.
450                  */
451                 ctl_sock = socket(family, SOCK_STREAM, 0);
452                 if (ctl_sock < 0) {
453                         syslog(LOG_ERR, "control socket: %m");
454                         exit(1);
455                 }
456                 if (setsockopt(ctl_sock, SOL_SOCKET, SO_REUSEADDR,
457                     (char *)&on, sizeof(on)) < 0)
458                         syslog(LOG_ERR, "control setsockopt: %m");
459 #ifdef IPV6_BINDV6ONLY
460                 if (family == AF_INET6 && enable_v4 == 0) {
461                         if (setsockopt(ctl_sock, IPPROTO_IPV6, IPV6_BINDV6ONLY,
462                                        (char *)&on, sizeof (on)) < 0)
463                                 syslog(LOG_ERR,
464                                        "control setsockopt(IPV6_BINDV6ONLY): %m");
465                 }
466 #endif /* IPV6_BINDV6ONLY */
467                 memcpy(&server_addr, res->ai_addr, res->ai_addr->sa_len);
468                 if (bind(ctl_sock, (struct sockaddr *)&server_addr,
469                          server_addr.su_len) < 0) {
470                         syslog(LOG_ERR, "control bind: %m");
471                         exit(1);
472                 }
473                 if (listen(ctl_sock, 32) < 0) {
474                         syslog(LOG_ERR, "control listen: %m");
475                         exit(1);
476                 }
477                 /*
478                  * Atomically write process ID
479                  */
480                 if (pid_file)
481                 {
482                         int fd;
483                         char buf[20];
484
485                         fd = open(pid_file, O_CREAT | O_WRONLY | O_TRUNC
486                                 | O_NONBLOCK | O_EXLOCK, 0644);
487                         if (fd < 0) {
488                                 if (errno == EAGAIN)
489                                         errx(1, "%s: file locked", pid_file);
490                                 else
491                                         err(1, "%s", pid_file);
492                         }
493                         snprintf(buf, sizeof(buf),
494                                 "%lu\n", (unsigned long) getpid());
495                         if (write(fd, buf, strlen(buf)) < 0)
496                                 err(1, "%s: write", pid_file);
497                         /* Leave the pid file open and locked */
498                 }
499                 /*
500                  * Loop forever accepting connection requests and forking off
501                  * children to handle them.
502                  */
503                 while (1) {
504                         addrlen = server_addr.su_len;
505                         fd = accept(ctl_sock, (struct sockaddr *)&his_addr, &addrlen);
506                         if (fork() == 0) {
507                                 /* child */
508                                 (void) dup2(fd, 0);
509                                 (void) dup2(fd, 1);
510                                 close(ctl_sock);
511                                 break;
512                         }
513                         close(fd);
514                 }
515         } else {
516                 addrlen = sizeof(his_addr);
517                 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
518                         syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
519                         exit(1);
520                 }
521         }
522
523         sa.sa_handler = SIG_DFL;
524         (void)sigaction(SIGCHLD, &sa, NULL);
525
526         sa.sa_handler = sigurg;
527         sa.sa_flags = 0;                /* don't restart syscalls for SIGURG */
528         (void)sigaction(SIGURG, &sa, NULL);
529
530         sigfillset(&sa.sa_mask);        /* block all signals in handler */
531         sa.sa_flags = SA_RESTART;
532         sa.sa_handler = sigquit;
533         (void)sigaction(SIGHUP, &sa, NULL);
534         (void)sigaction(SIGINT, &sa, NULL);
535         (void)sigaction(SIGQUIT, &sa, NULL);
536         (void)sigaction(SIGTERM, &sa, NULL);
537
538         sa.sa_handler = lostconn;
539         (void)sigaction(SIGPIPE, &sa, NULL);
540
541         addrlen = sizeof(ctrl_addr);
542         if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
543                 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
544                 exit(1);
545         }
546 #ifdef VIRTUAL_HOSTING
547         /* select our identity from virtual host table */
548         selecthost(&ctrl_addr);
549 #endif
550 #ifdef IP_TOS
551         if (ctrl_addr.su_family == AF_INET)
552       {
553         tos = IPTOS_LOWDELAY;
554         if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(int)) < 0)
555                 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
556       }
557 #endif
558         /*
559          * Disable Nagle on the control channel so that we don't have to wait
560          * for peer's ACK before issuing our next reply.
561          */
562         if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
563                 syslog(LOG_WARNING, "control setsockopt TCP_NODELAY: %m");
564
565         data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
566
567         /* set this here so klogin can use it... */
568         (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
569
570         /* Try to handle urgent data inline */
571 #ifdef SO_OOBINLINE
572         if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
573                 syslog(LOG_ERR, "setsockopt: %m");
574 #endif
575
576 #ifdef  F_SETOWN
577         if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
578                 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
579 #endif
580         dolog((struct sockaddr *)&his_addr);
581         /*
582          * Set up default state
583          */
584         data = -1;
585         type = TYPE_A;
586         form = FORM_N;
587         stru = STRU_F;
588         mode = MODE_S;
589         tmpline[0] = '\0';
590
591         /* If logins are disabled, print out the message. */
592         if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
593                 while (fgets(line, sizeof(line), fd) != NULL) {
594                         if ((cp = strchr(line, '\n')) != NULL)
595                                 *cp = '\0';
596                         lreply(530, "%s", line);
597                 }
598                 (void) fflush(stdout);
599                 (void) fclose(fd);
600                 reply(530, "System not available.");
601                 exit(0);
602         }
603 #ifdef VIRTUAL_HOSTING
604         if ((fd = fopen(thishost->welcome, "r")) != NULL) {
605 #else
606         if ((fd = fopen(_PATH_FTPWELCOME, "r")) != NULL) {
607 #endif
608                 while (fgets(line, sizeof(line), fd) != NULL) {
609                         if ((cp = strchr(line, '\n')) != NULL)
610                                 *cp = '\0';
611                         lreply(220, "%s", line);
612                 }
613                 (void) fflush(stdout);
614                 (void) fclose(fd);
615                 /* reply(220,) must follow */
616         }
617 #ifndef VIRTUAL_HOSTING
618         if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
619                 fatalerror("Ran out of memory.");
620         (void) gethostname(hostname, MAXHOSTNAMELEN - 1);
621         hostname[MAXHOSTNAMELEN - 1] = '\0';
622 #endif
623         reply(220, "%s FTP server (%s) ready.", hostname, version);
624         for (;;)
625                 (void) yyparse();
626         /* NOTREACHED */
627 }
628
629 static void
630 lostconn(int signo)
631 {
632
633         if (ftpdebug)
634                 syslog(LOG_DEBUG, "lost connection");
635         dologout(1);
636 }
637
638 static void
639 sigquit(int signo)
640 {
641
642         syslog(LOG_ERR, "got signal %d", signo);
643         dologout(1);
644 }
645
646 #ifdef VIRTUAL_HOSTING
647 /*
648  * read in virtual host tables (if they exist)
649  */
650
651 static void
652 inithosts(void)
653 {
654         int insert;
655         size_t len;
656         FILE *fp;
657         char *cp, *mp, *line;
658         char *hostname;
659         char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
660         struct ftphost *hrp, *lhrp;
661         struct addrinfo hints, *res, *ai;
662
663         /*
664          * Fill in the default host information
665          */
666         if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
667                 fatalerror("Ran out of memory.");
668         if (gethostname(hostname, MAXHOSTNAMELEN) < 0)
669                 hostname[0] = '\0';
670         hostname[MAXHOSTNAMELEN - 1] = '\0';
671         if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
672                 fatalerror("Ran out of memory.");
673         hrp->hostname = hostname;
674         hrp->hostinfo = NULL;
675
676         memset(&hints, 0, sizeof(hints));
677         hints.ai_flags = AI_CANONNAME;
678         hints.ai_family = AF_UNSPEC;
679         getaddrinfo(hrp->hostname, NULL, &hints, &res);
680         if (res)
681                 hrp->hostinfo = res;
682         hrp->statfile = _PATH_FTPDSTATFILE;
683         hrp->welcome  = _PATH_FTPWELCOME;
684         hrp->loginmsg = _PATH_FTPLOGINMESG;
685         hrp->anonuser = "ftp";
686         hrp->next = NULL;
687         thishost = firsthost = lhrp = hrp;
688         if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
689                 int addrsize, error, gothost;
690                 void *addr;
691                 struct hostent *hp;
692
693                 while ((line = fgetln(fp, &len)) != NULL) {
694                         int     i, hp_error;
695
696                         /* skip comments */
697                         if (line[0] == '#')
698                                 continue;
699                         if (line[len - 1] == '\n') {
700                                 line[len - 1] = '\0';
701                                 mp = NULL;
702                         } else {
703                                 if ((mp = malloc(len + 1)) == NULL)
704                                         fatalerror("Ran out of memory.");
705                                 memcpy(mp, line, len);
706                                 mp[len] = '\0';
707                                 line = mp;
708                         }
709                         cp = strtok(line, " \t");
710                         /* skip empty lines */
711                         if (cp == NULL)
712                                 goto nextline;
713                         vhost = cp;
714
715                         /* set defaults */
716                         anonuser = "ftp";
717                         statfile = _PATH_FTPDSTATFILE;
718                         welcome  = _PATH_FTPWELCOME;
719                         loginmsg = _PATH_FTPLOGINMESG;
720
721                         /*
722                          * Preparse the line so we can use its info
723                          * for all the addresses associated with
724                          * the virtual host name.
725                          * Field 0, the virtual host name, is special:
726                          * it's already parsed off and will be strdup'ed
727                          * later, after we know its canonical form.
728                          */
729                         for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
730                                 if (*cp != '-' && (cp = strdup(cp)))
731                                         switch (i) {
732                                         case 1: /* anon user permissions */
733                                                 anonuser = cp;
734                                                 break;
735                                         case 2: /* statistics file */
736                                                 statfile = cp;
737                                                 break;
738                                         case 3: /* welcome message */
739                                                 welcome  = cp;
740                                                 break;
741                                         case 4: /* login message */
742                                                 loginmsg = cp;
743                                                 break;
744                                         default: /* programming error */
745                                                 abort();
746                                                 /* NOTREACHED */
747                                         }
748
749                         hints.ai_flags = 0;
750                         hints.ai_family = AF_UNSPEC;
751                         hints.ai_flags = AI_PASSIVE;
752                         error = getaddrinfo(vhost, NULL, &hints, &res);
753                         if (error != NULL)
754                                 goto nextline;
755                         for (ai = res; ai != NULL && ai->ai_addr != NULL;
756                              ai = ai->ai_next) {
757
758                         gothost = 0;
759                         for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
760                                 struct addrinfo *hi;
761
762                                 for (hi = hrp->hostinfo; hi != NULL;
763                                      hi = hi->ai_next)
764                                         if (hi->ai_addrlen == ai->ai_addrlen &&
765                                             memcmp(hi->ai_addr,
766                                                    ai->ai_addr,
767                                                    ai->ai_addr->sa_len) == 0) {
768                                                 gothost++;
769                                                 break;
770                                         }
771                                 if (gothost)
772                                         break;
773                         }
774                         if (hrp == NULL) {
775                                 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
776                                         goto nextline;
777                                 insert = 1;
778                         } else
779                                 insert = 0; /* host already in the chain */
780                         hrp->hostinfo = res;
781
782                         /*
783                          * determine hostname to use.
784                          * force defined name if there is a valid alias
785                          * otherwise fallback to primary hostname
786                          */
787                         /* XXX: getaddrinfo() can't do alias check */
788                         switch(hrp->hostinfo->ai_family) {
789                         case AF_INET:
790                                 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
791                                 addrsize = sizeof(struct in_addr);
792                                 break;
793                         case AF_INET6:
794                                 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
795                                 addrsize = sizeof(struct in6_addr);
796                                 break;
797                         default:
798                                 /* should not reach here */
799                                 if (hrp->hostinfo != NULL)
800                                         freeaddrinfo(hrp->hostinfo);
801                                 free(hrp);
802                                 goto nextline;
803                                 /* NOTREACHED */
804                         }
805                         if ((hp = getipnodebyaddr((char*)addr, addrsize,
806                                                   hrp->hostinfo->ai_family,
807                                                   &hp_error)) != NULL) {
808                                 if (strcmp(vhost, hp->h_name) != 0) {
809                                         if (hp->h_aliases == NULL)
810                                                 vhost = hp->h_name;
811                                         else {
812                                                 i = 0;
813                                                 while (hp->h_aliases[i] &&
814                                                        strcmp(vhost, hp->h_aliases[i]) != 0)
815                                                         ++i;
816                                                 if (hp->h_aliases[i] == NULL)
817                                                         vhost = hp->h_name;
818                                         }
819                                 }
820                         }
821                         if ((hrp->hostname = strdup(vhost)) == NULL)
822                                 goto nextline;
823                         hrp->anonuser = anonuser;
824                         hrp->statfile = statfile;
825                         hrp->welcome  = welcome;
826                         hrp->loginmsg = loginmsg;
827                         if (insert) {
828                                 hrp->next  = NULL;
829                                 lhrp->next = hrp;
830                                 lhrp = hrp;
831                         }
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 (stat(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 path[MAXPATHLEN + 1];
2330
2331         if (getwd(path) == (char *)NULL)
2332                 reply(550, "%s.", path);
2333         else
2334                 reply(257, "\"%s\" is current directory.", path);
2335 }
2336
2337 char *
2338 renamefrom(char *name)
2339 {
2340         struct stat st;
2341
2342         if (stat(name, &st) < 0) {
2343                 perror_reply(550, name);
2344                 return ((char *)0);
2345         }
2346         reply(350, "File exists, ready for destination name");
2347         return (name);
2348 }
2349
2350 void
2351 renamecmd(char *from, char *to)
2352 {
2353         struct stat st;
2354
2355         LOGCMD2("rename", from, to);
2356
2357         if (guest && (stat(to, &st) == 0)) {
2358                 reply(550, "%s: permission denied", to);
2359                 return;
2360         }
2361
2362         if (rename(from, to) < 0)
2363                 perror_reply(550, "rename");
2364         else
2365                 ack("RNTO");
2366 }
2367
2368 static void
2369 dolog(struct sockaddr *who)
2370 {
2371         int error;
2372
2373         realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2374
2375 #ifdef SETPROCTITLE
2376 #ifdef VIRTUAL_HOSTING
2377         if (thishost != firsthost)
2378                 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2379                          remotehost, hostname);
2380         else
2381 #endif
2382                 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2383                          remotehost);
2384         setproctitle("%s", proctitle);
2385 #endif /* SETPROCTITLE */
2386
2387         if (logging) {
2388 #ifdef VIRTUAL_HOSTING
2389                 if (thishost != firsthost)
2390                         syslog(LOG_INFO, "connection from %s (to %s)",
2391                                remotehost, hostname);
2392                 else
2393 #endif
2394                 {
2395                         char    who_name[MAXHOSTNAMELEN];
2396
2397                         error = getnameinfo(who, who->sa_len,
2398                                             who_name, sizeof(who_name) - 1,
2399                                             NULL, 0, NI_NUMERICHOST);
2400                         syslog(LOG_INFO, "connection from %s (%s)", remotehost,
2401                                error == 0 ? who_name : "");
2402                 }
2403         }
2404 }
2405
2406 /*
2407  * Record logout in wtmp file
2408  * and exit with supplied status.
2409  */
2410 void
2411 dologout(int status)
2412 {
2413         /*
2414          * Prevent reception of SIGURG from resulting in a resumption
2415          * back to the main program loop.
2416          */
2417         transflag = 0;
2418
2419         if (logged_in) {
2420                 (void) seteuid((uid_t)0);
2421                 ftpd_logwtmp(ttyline, "", NULL);
2422         }
2423         /* beware of flushing buffers after a SIGPIPE */
2424         _exit(status);
2425 }
2426
2427 static void
2428 sigurg(int signo)
2429 {
2430
2431         recvurg = 1;
2432 }
2433
2434 static void
2435 myoob(void)
2436 {
2437         char *cp;
2438
2439         /* only process if transfer occurring */
2440         if (!transflag)
2441                 return;
2442         cp = tmpline;
2443         if (getline(cp, 7, stdin) == NULL) {
2444                 reply(221, "You could at least say goodbye.");
2445                 dologout(0);
2446         }
2447         upper(cp);
2448         if (strcmp(cp, "ABOR\r\n") == 0) {
2449                 tmpline[0] = '\0';
2450                 reply(426, "Transfer aborted. Data connection closed.");
2451                 reply(226, "Abort successful");
2452         }
2453         if (strcmp(cp, "STAT\r\n") == 0) {
2454                 tmpline[0] = '\0';
2455                 if (file_size != (off_t) -1)
2456                         reply(213, "Status: %qd of %qd bytes transferred",
2457                             byte_count, file_size);
2458                 else
2459                         reply(213, "Status: %qd bytes transferred", byte_count);
2460         }
2461 }
2462
2463 /*
2464  * Note: a response of 425 is not mentioned as a possible response to
2465  *      the PASV command in RFC959. However, it has been blessed as
2466  *      a legitimate response by Jon Postel in a telephone conversation
2467  *      with Rick Adams on 25 Jan 89.
2468  */
2469 void
2470 passive(void)
2471 {
2472         int len;
2473         char *p, *a;
2474
2475         if (pdata >= 0)         /* close old port if one set */
2476                 close(pdata);
2477
2478         pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2479         if (pdata < 0) {
2480                 perror_reply(425, "Can't open passive connection");
2481                 return;
2482         }
2483
2484         (void) seteuid((uid_t)0);
2485
2486 #ifdef IP_PORTRANGE
2487         if (ctrl_addr.su_family == AF_INET) {
2488             int on = restricted_data_ports ? IP_PORTRANGE_HIGH
2489                                            : IP_PORTRANGE_DEFAULT;
2490
2491             if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2492                             (char *)&on, sizeof(on)) < 0)
2493                     goto pasv_error;
2494         }
2495 #endif
2496 #ifdef IPV6_PORTRANGE
2497         if (ctrl_addr.su_family == AF_INET6) {
2498             int on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2499                                            : IPV6_PORTRANGE_DEFAULT;
2500
2501             if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2502                             (char *)&on, sizeof(on)) < 0)
2503                     goto pasv_error;
2504         }
2505 #endif
2506
2507         pasv_addr = ctrl_addr;
2508         pasv_addr.su_port = 0;
2509         if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2510                 goto pasv_error;
2511
2512         (void) seteuid((uid_t)pw->pw_uid);
2513
2514         len = sizeof(pasv_addr);
2515         if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2516                 goto pasv_error;
2517         if (listen(pdata, 1) < 0)
2518                 goto pasv_error;
2519         if (pasv_addr.su_family == AF_INET)
2520                 a = (char *) &pasv_addr.su_sin.sin_addr;
2521         else if (pasv_addr.su_family == AF_INET6 &&
2522                  IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2523                 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2524         else
2525                 goto pasv_error;
2526                 
2527         p = (char *) &pasv_addr.su_port;
2528
2529 #define UC(b) (((int) b) & 0xff)
2530
2531         reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2532                 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2533         return;
2534
2535 pasv_error:
2536         (void) seteuid((uid_t)pw->pw_uid);
2537         (void) close(pdata);
2538         pdata = -1;
2539         perror_reply(425, "Can't open passive connection");
2540         return;
2541 }
2542
2543 /*
2544  * Long Passive defined in RFC 1639.
2545  *     228 Entering Long Passive Mode
2546  *         (af, hal, h1, h2, h3,..., pal, p1, p2...)
2547  */
2548
2549 void
2550 long_passive(char *cmd, int pf)
2551 {
2552         int len;
2553         char *p, *a;
2554
2555         if (pdata >= 0)         /* close old port if one set */
2556                 close(pdata);
2557
2558         if (pf != PF_UNSPEC) {
2559                 if (ctrl_addr.su_family != pf) {
2560                         switch (ctrl_addr.su_family) {
2561                         case AF_INET:
2562                                 pf = 1;
2563                                 break;
2564                         case AF_INET6:
2565                                 pf = 2;
2566                                 break;
2567                         default:
2568                                 pf = 0;
2569                                 break;
2570                         }
2571                         /*
2572                          * XXX
2573                          * only EPRT/EPSV ready clients will understand this
2574                          */
2575                         if (strcmp(cmd, "EPSV") == 0 && pf) {
2576                                 reply(522, "Network protocol mismatch, "
2577                                         "use (%d)", pf);
2578                         } else
2579                                 reply(501, "Network protocol mismatch"); /*XXX*/
2580
2581                         return;
2582                 }
2583         }
2584                 
2585         pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2586         if (pdata < 0) {
2587                 perror_reply(425, "Can't open passive connection");
2588                 return;
2589         }
2590
2591         (void) seteuid((uid_t)0);
2592
2593         pasv_addr = ctrl_addr;
2594         pasv_addr.su_port = 0;
2595         len = pasv_addr.su_len;
2596
2597 #ifdef IP_PORTRANGE
2598         if (ctrl_addr.su_family == AF_INET) {
2599             int on = restricted_data_ports ? IP_PORTRANGE_HIGH
2600                                            : IP_PORTRANGE_DEFAULT;
2601
2602             if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2603                             (char *)&on, sizeof(on)) < 0)
2604                     goto pasv_error;
2605         }
2606 #endif
2607 #ifdef IPV6_PORTRANGE
2608         if (ctrl_addr.su_family == AF_INET6) {
2609             int on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2610                                            : IPV6_PORTRANGE_DEFAULT;
2611
2612             if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2613                             (char *)&on, sizeof(on)) < 0)
2614                     goto pasv_error;
2615         }
2616 #endif
2617
2618         if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2619                 goto pasv_error;
2620
2621         (void) seteuid((uid_t)pw->pw_uid);
2622
2623         if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2624                 goto pasv_error;
2625         if (listen(pdata, 1) < 0)
2626                 goto pasv_error;
2627
2628 #define UC(b) (((int) b) & 0xff)
2629
2630         if (strcmp(cmd, "LPSV") == 0) {
2631                 p = (char *)&pasv_addr.su_port;
2632                 switch (pasv_addr.su_family) {
2633                 case AF_INET:
2634                         a = (char *) &pasv_addr.su_sin.sin_addr;
2635                 v4_reply:
2636                         reply(228,
2637 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2638                               4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2639                               2, UC(p[0]), UC(p[1]));
2640                         return;
2641                 case AF_INET6:
2642                         if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
2643                                 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2644                                 goto v4_reply;
2645                         }
2646                         a = (char *) &pasv_addr.su_sin6.sin6_addr;
2647                         reply(228,
2648 "Entering Long Passive Mode "
2649 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2650                               6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2651                               UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2652                               UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2653                               UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2654                               2, UC(p[0]), UC(p[1]));
2655                         return;
2656                 }
2657         } else if (strcmp(cmd, "EPSV") == 0) {
2658                 switch (pasv_addr.su_family) {
2659                 case AF_INET:
2660                 case AF_INET6:
2661                         reply(229, "Entering Extended Passive Mode (|||%d|)",
2662                                 ntohs(pasv_addr.su_port));
2663                         return;
2664                 }
2665         } else {
2666                 /* more proper error code? */
2667         }
2668
2669 pasv_error:
2670         (void) seteuid((uid_t)pw->pw_uid);
2671         (void) close(pdata);
2672         pdata = -1;
2673         perror_reply(425, "Can't open passive connection");
2674         return;
2675 }
2676
2677 /*
2678  * Generate unique name for file with basename "local".
2679  * The file named "local" is already known to exist.
2680  * Generates failure reply on error.
2681  */
2682 static char *
2683 gunique(char *local)
2684 {
2685         static char new[MAXPATHLEN];
2686         struct stat st;
2687         int count;
2688         char *cp;
2689
2690         cp = strrchr(local, '/');
2691         if (cp)
2692                 *cp = '\0';
2693         if (stat(cp ? local : ".", &st) < 0) {
2694                 perror_reply(553, cp ? local : ".");
2695                 return ((char *) 0);
2696         }
2697         if (cp)
2698                 *cp = '/';
2699         /* -4 is for the .nn<null> we put on the end below */
2700         (void) snprintf(new, sizeof(new) - 4, "%s", local);
2701         cp = new + strlen(new);
2702         *cp++ = '.';
2703         for (count = 1; count < 100; count++) {
2704                 (void)sprintf(cp, "%d", count);
2705                 if (stat(new, &st) < 0)
2706                         return (new);
2707         }
2708         reply(452, "Unique file name cannot be created.");
2709         return (NULL);
2710 }
2711
2712 /*
2713  * Format and send reply containing system error number.
2714  */
2715 void
2716 perror_reply(int code, char *string)
2717 {
2718
2719         reply(code, "%s: %s.", string, strerror(errno));
2720 }
2721
2722 static char *onefile[] = {
2723         "",
2724         0
2725 };
2726
2727 void
2728 send_file_list(char *whichf)
2729 {
2730         struct stat st;
2731         DIR *dirp = NULL;
2732         struct dirent *dir;
2733         FILE *dout = NULL;
2734         char **dirlist, *dirname;
2735         int simple = 0;
2736         int freeglob = 0;
2737         glob_t gl;
2738
2739         if (strpbrk(whichf, "~{[*?") != NULL) {
2740                 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
2741
2742                 memset(&gl, 0, sizeof(gl));
2743                 gl.gl_matchc = MAXGLOBARGS;
2744                 flags |= GLOB_LIMIT;
2745                 freeglob = 1;
2746                 if (glob(whichf, flags, 0, &gl)) {
2747                         reply(550, "not found");
2748                         goto out;
2749                 } else if (gl.gl_pathc == 0) {
2750                         errno = ENOENT;
2751                         perror_reply(550, whichf);
2752                         goto out;
2753                 }
2754                 dirlist = gl.gl_pathv;
2755         } else {
2756                 onefile[0] = whichf;
2757                 dirlist = onefile;
2758                 simple = 1;
2759         }
2760
2761         while ((dirname = *dirlist++)) {
2762                 if (stat(dirname, &st) < 0) {
2763                         /*
2764                          * If user typed "ls -l", etc, and the client
2765                          * used NLST, do what the user meant.
2766                          */
2767                         if (dirname[0] == '-' && *dirlist == NULL &&
2768                             transflag == 0) {
2769                                 retrieve(_PATH_LS " %s", dirname);
2770                                 goto out;
2771                         }
2772                         perror_reply(550, whichf);
2773                         if (dout != NULL) {
2774                                 (void) fclose(dout);
2775                                 transflag = 0;
2776                                 data = -1;
2777                                 pdata = -1;
2778                         }
2779                         goto out;
2780                 }
2781
2782                 if (S_ISREG(st.st_mode)) {
2783                         if (dout == NULL) {
2784                                 dout = dataconn("file list", (off_t)-1, "w");
2785                                 if (dout == NULL)
2786                                         goto out;
2787                                 transflag++;
2788                         }
2789                         fprintf(dout, "%s%s\n", dirname,
2790                                 type == TYPE_A ? "\r" : "");
2791                         byte_count += strlen(dirname) + 1;
2792                         continue;
2793                 } else if (!S_ISDIR(st.st_mode))
2794                         continue;
2795
2796                 if ((dirp = opendir(dirname)) == NULL)
2797                         continue;
2798
2799                 while ((dir = readdir(dirp)) != NULL) {
2800                         char nbuf[MAXPATHLEN];
2801
2802                         if (recvurg) {
2803                                 myoob();
2804                                 recvurg = 0;
2805                                 transflag = 0;
2806                                 goto out;
2807                         }
2808
2809                         if (dir->d_name[0] == '.' && dir->d_namlen == 1)
2810                                 continue;
2811                         if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
2812                             dir->d_namlen == 2)
2813                                 continue;
2814
2815                         snprintf(nbuf, sizeof(nbuf),
2816                                 "%s/%s", dirname, dir->d_name);
2817
2818                         /*
2819                          * We have to do a stat to insure it's
2820                          * not a directory or special file.
2821                          */
2822                         if (simple || (stat(nbuf, &st) == 0 &&
2823                             S_ISREG(st.st_mode))) {
2824                                 if (dout == NULL) {
2825                                         dout = dataconn("file list", (off_t)-1,
2826                                                 "w");
2827                                         if (dout == NULL)
2828                                                 goto out;
2829                                         transflag++;
2830                                 }
2831                                 if (nbuf[0] == '.' && nbuf[1] == '/')
2832                                         fprintf(dout, "%s%s\n", &nbuf[2],
2833                                                 type == TYPE_A ? "\r" : "");
2834                                 else
2835                                         fprintf(dout, "%s%s\n", nbuf,
2836                                                 type == TYPE_A ? "\r" : "");
2837                                 byte_count += strlen(nbuf) + 1;
2838                         }
2839                 }
2840                 (void) closedir(dirp);
2841         }
2842
2843         if (dout == NULL)
2844                 reply(550, "No files found.");
2845         else if (ferror(dout) != 0)
2846                 perror_reply(550, "Data connection");
2847         else
2848                 reply(226, "Transfer complete.");
2849
2850         transflag = 0;
2851         if (dout != NULL)
2852                 (void) fclose(dout);
2853         data = -1;
2854         pdata = -1;
2855 out:
2856         if (freeglob) {
2857                 freeglob = 0;
2858                 globfree(&gl);
2859         }
2860 }
2861
2862 void
2863 reapchild(int signo)
2864 {
2865         while (wait3(NULL, WNOHANG, NULL) > 0);
2866 }
2867
2868 #ifdef OLD_SETPROCTITLE
2869 /*
2870  * Clobber argv so ps will show what we're doing.  (Stolen from sendmail.)
2871  * Warning, since this is usually started from inetd.conf, it often doesn't
2872  * have much of an environment or arglist to overwrite.
2873  */
2874 void
2875 setproctitle(const char *fmt, ...)
2876 {
2877         int i;
2878         va_list ap;
2879         char *p, *bp, ch;
2880         char buf[LINE_MAX];
2881
2882         va_start(ap, fmt);
2883         (void)vsnprintf(buf, sizeof(buf), fmt, ap);
2884
2885         /* make ps print our process name */
2886         p = Argv[0];
2887         *p++ = '-';
2888
2889         i = strlen(buf);
2890         if (i > LastArgv - p - 2) {
2891                 i = LastArgv - p - 2;
2892                 buf[i] = '\0';
2893         }
2894         bp = buf;
2895         while (ch = *bp++)
2896                 if (ch != '\n' && ch != '\r')
2897                         *p++ = ch;
2898         while (p < LastArgv)
2899                 *p++ = ' ';
2900 }
2901 #endif /* OLD_SETPROCTITLE */
2902
2903 static void
2904 logxfer(char *name, off_t size, time_t start)
2905 {
2906         char buf[1024];
2907         char path[MAXPATHLEN + 1];
2908         time_t now;
2909
2910         if (statfd >= 0 && getwd(path) != NULL) {
2911                 time(&now);
2912                 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s/%s!%qd!%ld\n",
2913                         ctime(&now)+4, ident, remotehost,
2914                         path, name, (long long)size,
2915                         (long)(now - start + (now == start)));
2916                 write(statfd, buf, strlen(buf));
2917         }
2918 }