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