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