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