Home | History | Annotate | Line # | Download | only in ftpd
ftpd.c revision 1.203
      1  1.203       shm /*	$NetBSD: ftpd.c,v 1.203 2016/07/19 21:25:38 shm Exp $	*/
      2   1.67    itojun 
      3   1.67    itojun /*
      4  1.192     lukem  * Copyright (c) 1997-2009 The NetBSD Foundation, Inc.
      5   1.67    itojun  * All rights reserved.
      6   1.73     lukem  *
      7   1.73     lukem  * This code is derived from software contributed to The NetBSD Foundation
      8   1.73     lukem  * by Luke Mewburn.
      9   1.73     lukem  *
     10   1.67    itojun  * Redistribution and use in source and binary forms, with or without
     11   1.67    itojun  * modification, are permitted provided that the following conditions
     12   1.67    itojun  * are met:
     13   1.67    itojun  * 1. Redistributions of source code must retain the above copyright
     14   1.67    itojun  *    notice, this list of conditions and the following disclaimer.
     15   1.67    itojun  * 2. Redistributions in binary form must reproduce the above copyright
     16   1.67    itojun  *    notice, this list of conditions and the following disclaimer in the
     17   1.67    itojun  *    documentation and/or other materials provided with the distribution.
     18   1.73     lukem  *
     19   1.73     lukem  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20   1.73     lukem  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21   1.73     lukem  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22   1.73     lukem  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23   1.73     lukem  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24   1.73     lukem  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25   1.73     lukem  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26   1.73     lukem  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27   1.73     lukem  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28   1.73     lukem  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29   1.73     lukem  * POSSIBILITY OF SUCH DAMAGE.
     30   1.67    itojun  */
     31   1.13       cgd 
     32    1.1       cgd /*
     33    1.8   deraadt  * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
     34    1.8   deraadt  *	The Regents of the University of California.  All rights reserved.
     35    1.1       cgd  *
     36    1.1       cgd  * Redistribution and use in source and binary forms, with or without
     37    1.1       cgd  * modification, are permitted provided that the following conditions
     38    1.1       cgd  * are met:
     39    1.1       cgd  * 1. Redistributions of source code must retain the above copyright
     40    1.1       cgd  *    notice, this list of conditions and the following disclaimer.
     41    1.1       cgd  * 2. Redistributions in binary form must reproduce the above copyright
     42    1.1       cgd  *    notice, this list of conditions and the following disclaimer in the
     43    1.1       cgd  *    documentation and/or other materials provided with the distribution.
     44  1.156       agc  * 3. Neither the name of the University nor the names of its contributors
     45    1.1       cgd  *    may be used to endorse or promote products derived from this software
     46    1.1       cgd  *    without specific prior written permission.
     47    1.1       cgd  *
     48    1.1       cgd  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     49    1.1       cgd  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     50    1.1       cgd  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     51    1.1       cgd  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     52    1.1       cgd  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     53    1.1       cgd  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     54    1.1       cgd  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     55    1.1       cgd  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     56    1.1       cgd  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     57    1.1       cgd  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     58    1.1       cgd  * SUCH DAMAGE.
     59    1.1       cgd  */
     60    1.1       cgd 
     61   1.62     lukem /*
     62   1.73     lukem  * Copyright (C) 1997 and 1998 WIDE Project.
     63   1.62     lukem  * All rights reserved.
     64   1.73     lukem  *
     65   1.62     lukem  * Redistribution and use in source and binary forms, with or without
     66   1.62     lukem  * modification, are permitted provided that the following conditions
     67   1.62     lukem  * are met:
     68   1.62     lukem  * 1. Redistributions of source code must retain the above copyright
     69   1.62     lukem  *    notice, this list of conditions and the following disclaimer.
     70   1.62     lukem  * 2. Redistributions in binary form must reproduce the above copyright
     71   1.62     lukem  *    notice, this list of conditions and the following disclaimer in the
     72   1.62     lukem  *    documentation and/or other materials provided with the distribution.
     73   1.73     lukem  * 3. Neither the name of the project nor the names of its contributors
     74   1.73     lukem  *    may be used to endorse or promote products derived from this software
     75   1.73     lukem  *    without specific prior written permission.
     76   1.73     lukem  *
     77   1.73     lukem  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     78   1.73     lukem  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     79   1.73     lukem  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     80   1.73     lukem  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     81   1.73     lukem  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     82   1.73     lukem  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     83   1.73     lukem  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     84   1.73     lukem  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     85   1.73     lukem  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     86   1.73     lukem  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     87   1.73     lukem  * SUCH DAMAGE.
     88   1.62     lukem  */
     89   1.62     lukem 
     90   1.25  christos #include <sys/cdefs.h>
     91    1.1       cgd #ifndef lint
     92  1.186     lukem __COPYRIGHT("@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\
     93  1.186     lukem  The Regents of the University of California.  All rights reserved.");
     94    1.1       cgd #endif /* not lint */
     95    1.1       cgd 
     96    1.1       cgd #ifndef lint
     97   1.13       cgd #if 0
     98   1.17       cjs static char sccsid[] = "@(#)ftpd.c	8.5 (Berkeley) 4/28/95";
     99   1.13       cgd #else
    100  1.203       shm __RCSID("$NetBSD: ftpd.c,v 1.203 2016/07/19 21:25:38 shm Exp $");
    101   1.13       cgd #endif
    102    1.1       cgd #endif /* not lint */
    103    1.1       cgd 
    104    1.1       cgd /*
    105    1.1       cgd  * FTP server.
    106    1.1       cgd  */
    107    1.1       cgd #include <sys/param.h>
    108    1.1       cgd #include <sys/stat.h>
    109    1.1       cgd #include <sys/ioctl.h>
    110    1.1       cgd #include <sys/socket.h>
    111    1.1       cgd #include <sys/wait.h>
    112  1.139     enami #include <sys/mman.h>
    113  1.139     enami #include <sys/resource.h>
    114    1.1       cgd 
    115    1.1       cgd #include <netinet/in.h>
    116    1.1       cgd #include <netinet/in_systm.h>
    117    1.1       cgd #include <netinet/ip.h>
    118    1.1       cgd 
    119    1.1       cgd #define	FTP_NAMES
    120    1.1       cgd #include <arpa/ftp.h>
    121    1.1       cgd #include <arpa/inet.h>
    122    1.1       cgd #include <arpa/telnet.h>
    123    1.1       cgd 
    124    1.8   deraadt #include <ctype.h>
    125    1.1       cgd #include <dirent.h>
    126    1.8   deraadt #include <err.h>
    127    1.8   deraadt #include <errno.h>
    128    1.1       cgd #include <fcntl.h>
    129   1.21       cjs #include <fnmatch.h>
    130    1.8   deraadt #include <glob.h>
    131   1.81     lukem #include <grp.h>
    132    1.8   deraadt #include <limits.h>
    133    1.8   deraadt #include <netdb.h>
    134    1.1       cgd #include <pwd.h>
    135  1.167     peter #include <poll.h>
    136    1.8   deraadt #include <signal.h>
    137   1.93     lukem #include <stdarg.h>
    138    1.1       cgd #include <stdio.h>
    139    1.1       cgd #include <stdlib.h>
    140    1.1       cgd #include <string.h>
    141    1.8   deraadt #include <syslog.h>
    142    1.8   deraadt #include <time.h>
    143  1.118     lukem #include <tzfile.h>
    144    1.8   deraadt #include <unistd.h>
    145   1.73     lukem #include <util.h>
    146  1.141  christos #ifdef SUPPORT_UTMP
    147   1.78     lukem #include <utmp.h>
    148  1.141  christos #endif
    149  1.141  christos #ifdef SUPPORT_UTMPX
    150  1.141  christos #include <utmpx.h>
    151  1.141  christos #endif
    152   1.25  christos #ifdef SKEY
    153   1.25  christos #include <skey.h>
    154   1.25  christos #endif
    155   1.38   mycroft #ifdef KERBEROS5
    156   1.86     aidan #include <com_err.h>
    157   1.69  christos #include <krb5/krb5.h>
    158   1.38   mycroft #endif
    159    1.8   deraadt 
    160  1.164  christos #ifdef	LOGIN_CAP
    161  1.164  christos #include <login_cap.h>
    162  1.164  christos #endif
    163  1.164  christos 
    164  1.164  christos #ifdef USE_PAM
    165  1.164  christos #include <security/pam_appl.h>
    166  1.164  christos #endif
    167  1.164  christos 
    168  1.201  christos #include "pfilter.h"
    169  1.201  christos 
    170   1.84     lukem #define	GLOBAL
    171   1.24     lukem #include "extern.h"
    172    1.1       cgd #include "pathnames.h"
    173   1.78     lukem #include "version.h"
    174    1.1       cgd 
    175  1.178  christos static sig_atomic_t	transflag;
    176  1.178  christos static sig_atomic_t	urgflag;
    177  1.158     lukem 
    178    1.1       cgd int	data;
    179  1.167     peter int	Dflag;
    180   1.51   msaitoh int	sflag;
    181    1.1       cgd int	stru;			/* avoid C keyword */
    182    1.1       cgd int	mode;
    183  1.111     lukem int	dataport;		/* use specific data port */
    184  1.111     lukem int	dopidfile;		/* maintain pid file */
    185  1.101     lukem int	doutmp;			/* update utmp file */
    186  1.102     lukem int	dowtmp;			/* update wtmp file */
    187  1.154     lukem int	doxferlog;		/* syslog/write wu-ftpd style xferlog entries */
    188  1.154     lukem int	xferlogfd;		/* fd to write wu-ftpd xferlog entries to */
    189  1.180  christos int	getnameopts;		/* flags for use with getname() */
    190  1.101     lukem int	dropprivs;		/* if privileges should or have been dropped */
    191  1.101     lukem int	mapped;			/* IPv4 connection on AF_INET6 socket */
    192    1.1       cgd off_t	file_size;
    193    1.1       cgd off_t	byte_count;
    194   1.13       cgd static char ttyline[20];
    195  1.164  christos 
    196  1.164  christos #ifdef USE_PAM
    197  1.183     lukem static int	auth_pam(void);
    198  1.164  christos pam_handle_t	*pamh = NULL;
    199  1.164  christos #endif
    200  1.164  christos 
    201  1.141  christos #ifdef SUPPORT_UTMP
    202   1.78     lukem static struct utmp utmp;	/* for utmp */
    203  1.141  christos #endif
    204  1.141  christos #ifdef SUPPORT_UTMPX
    205  1.141  christos static struct utmpx utmpx;	/* for utmpx */
    206  1.141  christos #endif
    207   1.57     lukem 
    208  1.111     lukem static const char *anondir = NULL;
    209  1.117     lukem static const char *confdir = _DEFAULT_CONFDIR;
    210   1.24     lukem 
    211  1.157     lukem static char	*curname;		/* current USER name */
    212  1.157     lukem static size_t	curname_len;		/* length of curname (include NUL) */
    213  1.157     lukem 
    214   1.38   mycroft #if defined(KERBEROS) || defined(KERBEROS5)
    215   1.91     fredb int	has_ccache = 0;
    216   1.13       cgd int	notickets = 1;
    217   1.13       cgd char	*krbtkfile_env = NULL;
    218   1.91     fredb char	*tty = ttyline;
    219   1.92  explorer int	login_krb5_forwardable_tgt = 0;
    220   1.73     lukem #endif
    221    1.4       cgd 
    222   1.67    itojun int epsvall = 0;
    223   1.67    itojun 
    224    1.1       cgd /*
    225    1.1       cgd  * Timeout intervals for retrying connections
    226    1.1       cgd  * to hosts that don't accept PORT cmds.  This
    227    1.1       cgd  * is a kludge, but given the problems with TCP...
    228    1.1       cgd  */
    229    1.1       cgd #define	SWAITMAX	90	/* wait at most 90 seconds */
    230    1.1       cgd #define	SWAITINT	5	/* interval between retries */
    231    1.1       cgd 
    232    1.1       cgd int	swaitmax = SWAITMAX;
    233    1.1       cgd int	swaitint = SWAITINT;
    234    1.1       cgd 
    235  1.139     enami enum send_status {
    236  1.139     enami 	SS_SUCCESS,
    237  1.158     lukem 	SS_ABORTED,			/* transfer aborted */
    238  1.139     enami 	SS_NO_TRANSFER,			/* no transfer made yet */
    239  1.139     enami 	SS_FILE_ERROR,			/* file read error */
    240  1.139     enami 	SS_DATA_ERROR			/* data send error */
    241  1.139     enami };
    242  1.139     enami 
    243   1.88     lukem static int	 bind_pasv_addr(void);
    244   1.88     lukem static int	 checkuser(const char *, const char *, int, int, char **);
    245   1.88     lukem static int	 checkaccess(const char *);
    246  1.116     lukem static int	 checkpassword(const struct passwd *, const char *);
    247  1.183     lukem static void	 do_pass(int, int, const char *);
    248   1.88     lukem static void	 end_login(void);
    249   1.88     lukem static FILE	*getdatasock(const char *);
    250   1.88     lukem static char	*gunique(const char *);
    251  1.160  christos static void	 login_utmp(const char *, const char *, const char *,
    252  1.160  christos 		     struct sockinet *);
    253  1.118     lukem static void	 logremotehost(struct sockinet *);
    254  1.195     joerg __dead static void	 lostconn(int);
    255  1.195     joerg __dead static void	 toolong(int);
    256  1.195     joerg __dead static void	 sigquit(int);
    257  1.158     lukem static void	 sigurg(int);
    258  1.158     lukem static int	 handleoobcmd(void);
    259   1.88     lukem static int	 receive_data(FILE *, FILE *);
    260  1.139     enami static int	 send_data(FILE *, FILE *, const struct stat *, int);
    261   1.88     lukem static struct passwd *sgetpwnam(const char *);
    262  1.139     enami static int	 write_data(int, char *, size_t, off_t *, struct timeval *,
    263  1.139     enami 		     int);
    264  1.139     enami static enum send_status
    265  1.139     enami 		 send_data_with_read(int, int, const struct stat *, int);
    266  1.139     enami static enum send_status
    267  1.139     enami 		 send_data_with_mmap(int, int, const struct stat *, int);
    268  1.139     enami static void	 logrusage(const struct rusage *, const struct rusage *);
    269  1.141  christos static void	 logout_utmp(void);
    270    1.8   deraadt 
    271   1.88     lukem int	main(int, char *[]);
    272   1.26    mellon 
    273   1.92  explorer #if defined(KERBEROS)
    274   1.88     lukem int	klogin(struct passwd *, char *, char *, char *);
    275   1.88     lukem void	kdestroy(void);
    276   1.26    mellon #endif
    277   1.92  explorer #if defined(KERBEROS5)
    278   1.92  explorer int	k5login(struct passwd *, char *, char *, char *);
    279   1.92  explorer void	k5destroy(void);
    280   1.92  explorer #endif
    281   1.63     lukem 
    282    1.8   deraadt int
    283   1.88     lukem main(int argc, char *argv[])
    284    1.1       cgd {
    285  1.176       mrg 	int		ch, on = 1, tos, keepalive;
    286  1.176       mrg 	socklen_t	addrlen;
    287   1.73     lukem #ifdef KERBEROS5
    288   1.76     lukem 	krb5_error_code	kerror;
    289   1.38   mycroft #endif
    290  1.111     lukem 	char		*p;
    291  1.154     lukem 	const char	*xferlogname = NULL;
    292  1.146    itojun 	long		l;
    293  1.158     lukem 	struct sigaction sa;
    294  1.167     peter 	sa_family_t	af = AF_UNSPEC;
    295    1.1       cgd 
    296   1.87     lukem 	connections = 1;
    297  1.171  christos 	ftpd_debug = 0;
    298   1.35     lukem 	logging = 0;
    299   1.87     lukem 	pdata = -1;
    300  1.167     peter 	Dflag = 0;
    301   1.51   msaitoh 	sflag = 0;
    302  1.111     lukem 	dataport = 0;
    303  1.111     lukem 	dopidfile = 1;		/* default: DO use a pid file to count users */
    304  1.118     lukem 	doutmp = 0;		/* default: Do NOT log to utmp */
    305  1.102     lukem 	dowtmp = 1;		/* default: DO log to wtmp */
    306  1.118     lukem 	doxferlog = 0;		/* default: Do NOT syslog xferlog */
    307  1.154     lukem 	xferlogfd = -1;		/* default: Do NOT write xferlog file */
    308  1.180  christos 	getnameopts = 0;	/* default: xlate addrs to name */
    309  1.101     lukem 	dropprivs = 0;
    310  1.101     lukem 	mapped = 0;
    311   1.87     lukem 	usedefault = 1;
    312  1.111     lukem 	emailaddr = NULL;
    313   1.80     lukem 	hostname[0] = '\0';
    314  1.100     lukem 	homedir[0] = '\0';
    315   1.95     lukem 	gidcount = 0;
    316  1.123     aidan 	is_oob = 0;
    317  1.111     lukem 	version = FTPD_VERSION;
    318  1.111     lukem 
    319  1.111     lukem 	/*
    320  1.111     lukem 	 * LOG_NDELAY sets up the logging connection immediately,
    321  1.111     lukem 	 * necessary for anonymous ftp's that chroot and can't do it later.
    322  1.111     lukem 	 */
    323  1.111     lukem 	openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
    324    1.1       cgd 
    325  1.167     peter 	while ((ch = getopt(argc, argv,
    326  1.180  christos 	    "46a:c:C:Dde:h:HlL:nP:qQrst:T:uUvV:wWX")) != -1) {
    327    1.8   deraadt 		switch (ch) {
    328  1.167     peter 		case '4':
    329  1.167     peter 			af = AF_INET;
    330  1.167     peter 			break;
    331  1.167     peter 
    332  1.167     peter 		case '6':
    333  1.167     peter 			af = AF_INET6;
    334  1.167     peter 			break;
    335  1.167     peter 
    336   1.22       cjs 		case 'a':
    337   1.22       cjs 			anondir = optarg;
    338   1.22       cjs 			break;
    339   1.22       cjs 
    340   1.34     lukem 		case 'c':
    341  1.111     lukem 			confdir = optarg;
    342   1.34     lukem 			break;
    343   1.73     lukem 
    344   1.35     lukem 		case 'C':
    345  1.188     lukem 			if ((p = strchr(optarg, '@')) != NULL) {
    346  1.188     lukem 				*p++ = '\0';
    347  1.188     lukem 				strlcpy(remotehost, p, MAXHOSTNAMELEN + 1);
    348  1.188     lukem 				if (inet_pton(AF_INET, p,
    349  1.188     lukem 				    &his_addr.su_addr) == 1) {
    350  1.188     lukem 					his_addr.su_family = AF_INET;
    351  1.188     lukem 					his_addr.su_len =
    352  1.188     lukem 					    sizeof(his_addr.si_su.su_sin);
    353  1.188     lukem #ifdef INET6
    354  1.188     lukem 				} else if (inet_pton(AF_INET6, p,
    355  1.188     lukem 				    &his_addr.su_6addr) == 1) {
    356  1.188     lukem 					his_addr.su_family = AF_INET6;
    357  1.188     lukem 					his_addr.su_len =
    358  1.188     lukem 					    sizeof(his_addr.si_su.su_sin6);
    359  1.188     lukem #endif
    360  1.188     lukem 				} else
    361  1.188     lukem 					his_addr.su_family = AF_UNSPEC;
    362  1.188     lukem 			}
    363   1.81     lukem 			pw = sgetpwnam(optarg);
    364   1.73     lukem 			exit(checkaccess(optarg) ? 0 : 1);
    365   1.35     lukem 			/* NOTREACHED */
    366   1.34     lukem 
    367  1.167     peter 		case 'D':
    368  1.167     peter 			Dflag = 1;
    369  1.167     peter 			break;
    370  1.167     peter 
    371    1.1       cgd 		case 'd':
    372   1.22       cjs 		case 'v':		/* deprecated */
    373  1.171  christos 			ftpd_debug = 1;
    374    1.1       cgd 			break;
    375    1.1       cgd 
    376  1.111     lukem 		case 'e':
    377  1.111     lukem 			emailaddr = optarg;
    378  1.111     lukem 			break;
    379  1.111     lukem 
    380   1.80     lukem 		case 'h':
    381   1.80     lukem 			strlcpy(hostname, optarg, sizeof(hostname));
    382   1.99     lukem 			break;
    383   1.99     lukem 
    384   1.99     lukem 		case 'H':
    385   1.99     lukem 			if (gethostname(hostname, sizeof(hostname)) == -1)
    386   1.99     lukem 				hostname[0] = '\0';
    387   1.99     lukem 			hostname[sizeof(hostname) - 1] = '\0';
    388   1.80     lukem 			break;
    389   1.80     lukem 
    390    1.1       cgd 		case 'l':
    391    1.8   deraadt 			logging++;	/* > 1 == extra logging */
    392    1.1       cgd 			break;
    393    1.1       cgd 
    394  1.154     lukem 		case 'L':
    395  1.154     lukem 			xferlogname = optarg;
    396  1.154     lukem 			break;
    397  1.154     lukem 
    398  1.180  christos 		case 'n':
    399  1.180  christos 			getnameopts = NI_NUMERICHOST;
    400  1.180  christos 			break;
    401  1.180  christos 
    402  1.111     lukem 		case 'P':
    403  1.146    itojun 			errno = 0;
    404  1.146    itojun 			p = NULL;
    405  1.146    itojun 			l = strtol(optarg, &p, 10);
    406  1.146    itojun 			if (errno || *optarg == '\0' || *p != '\0' ||
    407  1.146    itojun 			    l < IPPORT_RESERVED ||
    408  1.146    itojun 			    l > IPPORT_ANONMAX) {
    409  1.111     lukem 				syslog(LOG_WARNING, "Invalid dataport %s",
    410  1.111     lukem 				    optarg);
    411  1.111     lukem 				dataport = 0;
    412  1.111     lukem 			}
    413  1.146    itojun 			dataport = (int)l;
    414  1.111     lukem 			break;
    415  1.111     lukem 
    416  1.111     lukem 		case 'q':
    417  1.111     lukem 			dopidfile = 1;
    418  1.111     lukem 			break;
    419  1.111     lukem 
    420  1.111     lukem 		case 'Q':
    421  1.111     lukem 			dopidfile = 0;
    422  1.111     lukem 			break;
    423  1.111     lukem 
    424  1.101     lukem 		case 'r':
    425  1.101     lukem 			dropprivs = 1;
    426  1.101     lukem 			break;
    427  1.101     lukem 
    428   1.51   msaitoh 		case 's':
    429   1.51   msaitoh 			sflag = 1;
    430   1.51   msaitoh 			break;
    431   1.51   msaitoh 
    432    1.1       cgd 		case 't':
    433    1.1       cgd 		case 'T':
    434  1.119     lukem 			syslog(LOG_WARNING,
    435  1.111     lukem 			    "-%c has been deprecated in favour of ftpd.conf",
    436  1.111     lukem 			    ch);
    437  1.111     lukem 			break;
    438  1.111     lukem 
    439    1.1       cgd 		case 'u':
    440  1.111     lukem 			doutmp = 1;
    441    1.8   deraadt 			break;
    442    1.1       cgd 
    443   1.78     lukem 		case 'U':
    444  1.111     lukem 			doutmp = 0;
    445   1.78     lukem 			break;
    446   1.78     lukem 
    447  1.101     lukem 		case 'V':
    448  1.101     lukem 			if (EMPTYSTR(optarg) || strcmp(optarg, "-") == 0)
    449  1.101     lukem 				version = NULL;
    450  1.101     lukem 			else
    451  1.171  christos 				version = ftpd_strdup(optarg);
    452  1.101     lukem 			break;
    453  1.101     lukem 
    454  1.111     lukem 		case 'w':
    455  1.111     lukem 			dowtmp = 1;
    456  1.111     lukem 			break;
    457  1.111     lukem 
    458  1.102     lukem 		case 'W':
    459  1.102     lukem 			dowtmp = 0;
    460  1.102     lukem 			break;
    461  1.102     lukem 
    462  1.118     lukem 		case 'X':
    463  1.154     lukem 			doxferlog |= 1;
    464  1.118     lukem 			break;
    465  1.118     lukem 
    466    1.1       cgd 		default:
    467   1.35     lukem 			if (optopt == 'a' || optopt == 'C')
    468   1.35     lukem 				exit(1);
    469  1.119     lukem 			syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
    470    1.1       cgd 			break;
    471    1.1       cgd 		}
    472    1.1       cgd 	}
    473  1.111     lukem 	if (EMPTYSTR(confdir))
    474  1.111     lukem 		confdir = _DEFAULT_CONFDIR;
    475   1.35     lukem 
    476  1.201  christos 	pfilter_open();
    477  1.201  christos 
    478  1.166  christos 	if (dowtmp) {
    479  1.166  christos #ifdef SUPPORT_UTMPX
    480  1.166  christos 		ftpd_initwtmpx();
    481  1.166  christos #endif
    482  1.166  christos #ifdef SUPPORT_UTMP
    483  1.166  christos 		ftpd_initwtmp();
    484  1.166  christos #endif
    485  1.166  christos 	}
    486  1.157     lukem 	errno = 0;
    487  1.157     lukem 	l = sysconf(_SC_LOGIN_NAME_MAX);
    488  1.157     lukem 	if (l == -1 && errno != 0) {
    489  1.157     lukem 		syslog(LOG_ERR, "sysconf _SC_LOGIN_NAME_MAX: %m");
    490  1.157     lukem 		exit(1);
    491  1.157     lukem 	} else if (l <= 0) {
    492  1.157     lukem 		syslog(LOG_WARNING, "using conservative LOGIN_NAME_MAX value");
    493  1.157     lukem 		curname_len = _POSIX_LOGIN_NAME_MAX;
    494  1.157     lukem 	} else
    495  1.157     lukem 		curname_len = (size_t)l;
    496  1.157     lukem 	curname = malloc(curname_len);
    497  1.157     lukem 	if (curname == NULL) {
    498  1.157     lukem 		syslog(LOG_ERR, "malloc: %m");
    499  1.157     lukem 		exit(1);
    500  1.157     lukem 	}
    501  1.157     lukem 	curname[0] = '\0';
    502  1.157     lukem 
    503  1.167     peter 	if (Dflag) {
    504  1.167     peter 		int error, fd, i, n, *socks;
    505  1.167     peter 		struct pollfd *fds;
    506  1.167     peter 		struct addrinfo hints, *res, *res0;
    507  1.167     peter 
    508  1.167     peter 		if (daemon(1, 0) == -1) {
    509  1.167     peter 			syslog(LOG_ERR, "failed to daemonize: %m");
    510  1.167     peter 			exit(1);
    511  1.167     peter 		}
    512  1.167     peter 		(void)memset(&sa, 0, sizeof(sa));
    513  1.167     peter 		sa.sa_handler = SIG_IGN;
    514  1.167     peter 		sa.sa_flags = SA_NOCLDWAIT;
    515  1.167     peter 		sigemptyset(&sa.sa_mask);
    516  1.167     peter 		(void)sigaction(SIGCHLD, &sa, NULL);
    517  1.167     peter 
    518  1.167     peter 		(void)memset(&hints, 0, sizeof(hints));
    519  1.167     peter 		hints.ai_flags = AI_PASSIVE;
    520  1.167     peter 		hints.ai_family = af;
    521  1.167     peter 		hints.ai_socktype = SOCK_STREAM;
    522  1.167     peter 		error = getaddrinfo(NULL, "ftp", &hints, &res0);
    523  1.167     peter 		if (error) {
    524  1.167     peter 			syslog(LOG_ERR, "getaddrinfo: %s", gai_strerror(error));
    525  1.167     peter 			exit(1);
    526  1.167     peter 		}
    527  1.167     peter 
    528  1.167     peter 		for (n = 0, res = res0; res != NULL; res = res->ai_next)
    529  1.167     peter 			n++;
    530  1.167     peter 		if (n == 0) {
    531  1.167     peter 			syslog(LOG_ERR, "no addresses available");
    532  1.167     peter 			exit(1);
    533  1.167     peter 		}
    534  1.167     peter 		socks = malloc(n * sizeof(int));
    535  1.167     peter 		fds = malloc(n * sizeof(struct pollfd));
    536  1.167     peter 		if (socks == NULL || fds == NULL) {
    537  1.167     peter 			syslog(LOG_ERR, "malloc: %m");
    538  1.167     peter 			exit(1);
    539  1.167     peter 		}
    540  1.167     peter 
    541  1.167     peter 		for (n = 0, res = res0; res != NULL; res = res->ai_next) {
    542  1.167     peter 			socks[n] = socket(res->ai_family, res->ai_socktype,
    543  1.167     peter 			    res->ai_protocol);
    544  1.167     peter 			if (socks[n] == -1)
    545  1.167     peter 				continue;
    546  1.167     peter 			(void)setsockopt(socks[n], SOL_SOCKET, SO_REUSEADDR,
    547  1.167     peter 			    &on, sizeof(on));
    548  1.167     peter 			if (bind(socks[n], res->ai_addr, res->ai_addrlen)
    549  1.167     peter 			    == -1) {
    550  1.167     peter 				(void)close(socks[n]);
    551  1.167     peter 				continue;
    552  1.167     peter 			}
    553  1.167     peter 			if (listen(socks[n], 12) == -1) {
    554  1.167     peter 				(void)close(socks[n]);
    555  1.167     peter 				continue;
    556  1.167     peter 			}
    557  1.167     peter 
    558  1.167     peter 			fds[n].fd = socks[n];
    559  1.167     peter 			fds[n].events = POLLIN;
    560  1.167     peter 			n++;
    561  1.167     peter 		}
    562  1.167     peter 		if (n == 0) {
    563  1.167     peter 			syslog(LOG_ERR, "%m");
    564  1.167     peter 			exit(1);
    565  1.167     peter 		}
    566  1.167     peter 		freeaddrinfo(res0);
    567  1.167     peter 
    568  1.167     peter 		if (pidfile(NULL) == -1)
    569  1.167     peter 			syslog(LOG_ERR, "failed to write a pid file: %m");
    570  1.167     peter 
    571  1.167     peter 		for (;;) {
    572  1.167     peter 			if (poll(fds, n, INFTIM) == -1) {
    573  1.167     peter 				if (errno == EINTR)
    574  1.167     peter 					continue;
    575  1.167     peter 				syslog(LOG_ERR, "poll: %m");
    576  1.167     peter 				exit(1);
    577  1.167     peter 			}
    578  1.167     peter 			for (i = 0; i < n; i++) {
    579  1.167     peter 				if (fds[i].revents & POLLIN) {
    580  1.167     peter 					fd = accept(fds[i].fd, NULL, NULL);
    581  1.167     peter 					if (fd == -1) {
    582  1.167     peter 						syslog(LOG_ERR, "accept: %m");
    583  1.167     peter 						continue;
    584  1.167     peter 					}
    585  1.167     peter 					switch (fork()) {
    586  1.167     peter 					case -1:
    587  1.167     peter 						syslog(LOG_ERR, "fork: %m");
    588  1.167     peter 						break;
    589  1.167     peter 					case 0:
    590  1.167     peter 						goto child;
    591  1.167     peter 						/* NOTREACHED */
    592  1.167     peter 					}
    593  1.167     peter 					(void)close(fd);
    594  1.167     peter 				}
    595  1.167     peter 			}
    596  1.167     peter 		}
    597  1.167     peter  child:
    598  1.167     peter 		(void)dup2(fd, STDIN_FILENO);
    599  1.167     peter 		(void)dup2(fd, STDOUT_FILENO);
    600  1.167     peter 		(void)dup2(fd, STDERR_FILENO);
    601  1.167     peter 		for (i = 0; i < n; i++)
    602  1.167     peter 			(void)close(socks[i]);
    603  1.167     peter 	}
    604  1.167     peter 
    605  1.118     lukem 	memset((char *)&his_addr, 0, sizeof(his_addr));
    606  1.109     lukem 	addrlen = sizeof(his_addr.si_su);
    607  1.109     lukem 	if (getpeername(0, (struct sockaddr *)&his_addr.si_su, &addrlen) < 0) {
    608  1.196     lukem 		syslog((errno == ENOTCONN) ? LOG_NOTICE : LOG_ERR,
    609  1.196     lukem 		    "getpeername (%s): %m",argv[0]);
    610   1.35     lukem 		exit(1);
    611   1.35     lukem 	}
    612  1.109     lukem 	his_addr.su_len = addrlen;
    613  1.118     lukem 	memset((char *)&ctrl_addr, 0, sizeof(ctrl_addr));
    614  1.109     lukem 	addrlen = sizeof(ctrl_addr.si_su);
    615   1.68    itojun 	if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
    616   1.68    itojun 		syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
    617   1.68    itojun 		exit(1);
    618   1.68    itojun 	}
    619  1.109     lukem 	ctrl_addr.su_len = addrlen;
    620  1.104  christos #ifdef INET6
    621   1.67    itojun 	if (his_addr.su_family == AF_INET6
    622  1.109     lukem 	 && IN6_IS_ADDR_V4MAPPED(&his_addr.su_6addr)) {
    623   1.68    itojun #if 1
    624   1.68    itojun 		/*
    625   1.68    itojun 		 * IPv4 control connection arrived to AF_INET6 socket.
    626   1.68    itojun 		 * I hate to do this, but this is the easiest solution.
    627   1.90    itojun 		 *
    628   1.90    itojun 		 * The assumption is untrue on SIIT environment.
    629   1.68    itojun 		 */
    630  1.109     lukem 		struct sockinet tmp_addr;
    631   1.74    itojun 		const int off = sizeof(struct in6_addr) - sizeof(struct in_addr);
    632   1.68    itojun 
    633   1.68    itojun 		tmp_addr = his_addr;
    634   1.68    itojun 		memset(&his_addr, 0, sizeof(his_addr));
    635  1.109     lukem 		his_addr.su_family = AF_INET;
    636  1.109     lukem 		his_addr.su_len = sizeof(his_addr.si_su.su_sin);
    637  1.109     lukem 		memcpy(&his_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off],
    638  1.109     lukem 		    sizeof(his_addr.su_addr));
    639  1.109     lukem 		his_addr.su_port = tmp_addr.su_port;
    640   1.68    itojun 
    641   1.68    itojun 		tmp_addr = ctrl_addr;
    642   1.68    itojun 		memset(&ctrl_addr, 0, sizeof(ctrl_addr));
    643  1.109     lukem 		ctrl_addr.su_family = AF_INET;
    644  1.109     lukem 		ctrl_addr.su_len = sizeof(ctrl_addr.si_su.su_sin);
    645  1.109     lukem 		memcpy(&ctrl_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off],
    646  1.109     lukem 		    sizeof(ctrl_addr.su_addr));
    647  1.109     lukem 		ctrl_addr.su_port = tmp_addr.su_port;
    648   1.68    itojun #else
    649   1.67    itojun 		while (fgets(line, sizeof(line), fd) != NULL) {
    650   1.67    itojun 			if ((cp = strchr(line, '\n')) != NULL)
    651   1.67    itojun 				*cp = '\0';
    652   1.95     lukem 			reply(-530, "%s", line);
    653   1.67    itojun 		}
    654   1.67    itojun 		(void) fflush(stdout);
    655   1.67    itojun 		(void) fclose(fd);
    656   1.67    itojun 		reply(530,
    657  1.101     lukem 		    "Connection from IPv4 mapped address is not supported.");
    658   1.67    itojun 		exit(0);
    659   1.68    itojun #endif
    660   1.75    itojun 
    661   1.75    itojun 		mapped = 1;
    662   1.75    itojun 	} else
    663  1.109     lukem #endif /* INET6 */
    664   1.75    itojun 		mapped = 0;
    665   1.35     lukem #ifdef IP_TOS
    666   1.75    itojun 	if (!mapped && his_addr.su_family == AF_INET) {
    667   1.67    itojun 		tos = IPTOS_LOWDELAY;
    668   1.67    itojun 		if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos,
    669   1.67    itojun 			       sizeof(int)) < 0)
    670   1.67    itojun 			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
    671   1.67    itojun 	}
    672   1.35     lukem #endif
    673   1.80     lukem 	/* if the hostname hasn't been given, attempt to determine it */
    674   1.80     lukem 	if (hostname[0] == '\0') {
    675  1.109     lukem 		if (getnameinfo((struct sockaddr *)&ctrl_addr.si_su,
    676  1.180  christos 		    ctrl_addr.su_len, hostname, sizeof(hostname), NULL, 0,
    677  1.180  christos 			getnameopts) != 0)
    678   1.80     lukem 			(void)gethostname(hostname, sizeof(hostname));
    679   1.80     lukem 		hostname[sizeof(hostname) - 1] = '\0';
    680   1.80     lukem 	}
    681   1.79     lukem 
    682   1.35     lukem 	/* set this here so klogin can use it... */
    683   1.35     lukem 	(void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
    684   1.35     lukem 
    685    1.1       cgd 	(void) freopen(_PATH_DEVNULL, "w", stderr);
    686  1.158     lukem 
    687  1.158     lukem 	memset(&sa, 0, sizeof(sa));
    688  1.158     lukem 	sa.sa_handler = SIG_DFL;
    689  1.158     lukem 	sa.sa_flags = SA_RESTART;
    690  1.158     lukem 	sigemptyset(&sa.sa_mask);
    691  1.158     lukem 	(void) sigaction(SIGCHLD, &sa, NULL);
    692  1.158     lukem 
    693  1.158     lukem 	sa.sa_handler = sigquit;
    694  1.158     lukem 	sa.sa_flags = SA_RESTART;
    695  1.158     lukem 	sigfillset(&sa.sa_mask);	/* block all sigs in these handlers */
    696  1.158     lukem 	(void) sigaction(SIGHUP, &sa, NULL);
    697  1.158     lukem 	(void) sigaction(SIGINT, &sa, NULL);
    698  1.158     lukem 	(void) sigaction(SIGQUIT, &sa, NULL);
    699  1.158     lukem 	(void) sigaction(SIGTERM, &sa, NULL);
    700  1.158     lukem 	sa.sa_handler = lostconn;
    701  1.158     lukem 	(void) sigaction(SIGPIPE, &sa, NULL);
    702  1.158     lukem 	sa.sa_handler = toolong;
    703  1.158     lukem 	(void) sigaction(SIGALRM, &sa, NULL);
    704  1.158     lukem 	sa.sa_handler = sigurg;
    705  1.158     lukem 	(void) sigaction(SIGURG, &sa, NULL);
    706    1.1       cgd 
    707    1.1       cgd 	/* Try to handle urgent data inline */
    708    1.1       cgd #ifdef SO_OOBINLINE
    709    1.1       cgd 	if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
    710  1.119     lukem 		syslog(LOG_WARNING, "setsockopt: %m");
    711    1.1       cgd #endif
    712   1.66    briggs 	/* Set keepalives on the socket to detect dropped connections.  */
    713   1.66    briggs #ifdef SO_KEEPALIVE
    714   1.66    briggs 	keepalive = 1;
    715   1.66    briggs 	if (setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepalive,
    716   1.66    briggs 	    sizeof(int)) < 0)
    717   1.66    briggs 		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
    718   1.66    briggs #endif
    719    1.1       cgd 
    720    1.1       cgd #ifdef	F_SETOWN
    721    1.1       cgd 	if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
    722  1.119     lukem 		syslog(LOG_WARNING, "fcntl F_SETOWN: %m");
    723    1.1       cgd #endif
    724  1.118     lukem 	logremotehost(&his_addr);
    725    1.1       cgd 	/*
    726    1.1       cgd 	 * Set up default state
    727    1.1       cgd 	 */
    728    1.1       cgd 	data = -1;
    729    1.1       cgd 	type = TYPE_A;
    730    1.1       cgd 	form = FORM_N;
    731    1.1       cgd 	stru = STRU_F;
    732    1.1       cgd 	mode = MODE_S;
    733    1.1       cgd 	tmpline[0] = '\0';
    734   1.57     lukem 	hasyyerrored = 0;
    735    1.8   deraadt 
    736   1.38   mycroft #ifdef KERBEROS5
    737   1.38   mycroft 	kerror = krb5_init_context(&kcontext);
    738   1.38   mycroft 	if (kerror) {
    739  1.119     lukem 		syslog(LOG_ERR, "%s when initializing Kerberos context",
    740   1.38   mycroft 		    error_message(kerror));
    741   1.38   mycroft 		exit(0);
    742   1.38   mycroft 	}
    743   1.45  christos #endif /* KERBEROS5 */
    744   1.38   mycroft 
    745   1.82     lukem 	init_curclass();
    746   1.82     lukem 	curclass.timeout = 300;		/* 5 minutes, as per login(1) */
    747   1.82     lukem 	curclass.type = CLASS_REAL;
    748   1.82     lukem 
    749    1.8   deraadt 	/* If logins are disabled, print out the message. */
    750  1.100     lukem 	if (display_file(_PATH_NOLOGIN, 530)) {
    751    1.8   deraadt 		reply(530, "System not available.");
    752    1.8   deraadt 		exit(0);
    753    1.8   deraadt 	}
    754  1.163  christos 	(void)display_file(conffilename(_NAME_FTPWELCOME), 220);
    755    1.8   deraadt 		/* reply(220,) must follow */
    756  1.101     lukem 	if (EMPTYSTR(version))
    757  1.101     lukem 		reply(220, "%s FTP server ready.", hostname);
    758  1.101     lukem 	else
    759  1.101     lukem 		reply(220, "%s FTP server (%s) ready.", hostname, version);
    760   1.73     lukem 
    761  1.154     lukem 	if (xferlogname != NULL) {
    762  1.154     lukem 		xferlogfd = open(xferlogname, O_WRONLY | O_APPEND | O_CREAT,
    763  1.154     lukem 		    0660);
    764  1.154     lukem 		if (xferlogfd == -1)
    765  1.154     lukem 			syslog(LOG_WARNING, "open xferlog `%s': %m",
    766  1.154     lukem 			    xferlogname);
    767  1.154     lukem 		else
    768  1.154     lukem 			doxferlog |= 2;
    769  1.154     lukem 	}
    770  1.154     lukem 
    771  1.123     aidan 	ftp_loop();
    772    1.1       cgd 	/* NOTREACHED */
    773    1.1       cgd }
    774    1.1       cgd 
    775    1.8   deraadt static void
    776  1.178  christos lostconn(int signo __unused)
    777    1.1       cgd {
    778    1.8   deraadt 
    779  1.171  christos 	if (ftpd_debug)
    780    1.1       cgd 		syslog(LOG_DEBUG, "lost connection");
    781   1.35     lukem 	dologout(1);
    782    1.1       cgd }
    783    1.1       cgd 
    784  1.158     lukem static void
    785  1.178  christos toolong(int signo __unused)
    786  1.158     lukem {
    787  1.158     lukem 
    788  1.158     lukem 		/* XXXSIGRACE */
    789  1.158     lukem 	reply(421,
    790  1.158     lukem 	    "Timeout (" LLF " seconds): closing control connection.",
    791  1.158     lukem 	    (LLT)curclass.timeout);
    792  1.158     lukem 	if (logging)
    793  1.158     lukem 		syslog(LOG_INFO, "User %s timed out after " LLF " seconds",
    794  1.158     lukem 		    (pw ? pw->pw_name : "unknown"), (LLT)curclass.timeout);
    795  1.158     lukem 	dologout(1);
    796  1.158     lukem }
    797  1.158     lukem 
    798  1.158     lukem static void
    799  1.158     lukem sigquit(int signo)
    800  1.158     lukem {
    801  1.158     lukem 
    802  1.171  christos 	if (ftpd_debug)
    803  1.158     lukem 		syslog(LOG_DEBUG, "got signal %d", signo);
    804  1.158     lukem 	dologout(1);
    805  1.158     lukem }
    806  1.158     lukem 
    807  1.158     lukem static void
    808  1.178  christos sigurg(int signo __unused)
    809  1.158     lukem {
    810  1.158     lukem 
    811  1.158     lukem 	urgflag = 1;
    812  1.158     lukem }
    813  1.158     lukem 
    814  1.158     lukem 
    815    1.1       cgd /*
    816    1.1       cgd  * Save the result of a getpwnam.  Used for USER command, since
    817    1.1       cgd  * the data returned must not be clobbered by any other command
    818    1.1       cgd  * (e.g., globbing).
    819    1.1       cgd  */
    820    1.8   deraadt static struct passwd *
    821   1.88     lukem sgetpwnam(const char *name)
    822    1.1       cgd {
    823    1.1       cgd 	static struct passwd save;
    824    1.8   deraadt 	struct passwd *p;
    825    1.1       cgd 
    826    1.1       cgd 	if ((p = getpwnam(name)) == NULL)
    827    1.1       cgd 		return (p);
    828    1.1       cgd 	if (save.pw_name) {
    829   1.54   mycroft 		free((char *)save.pw_name);
    830   1.78     lukem 		memset(save.pw_passwd, 0, strlen(save.pw_passwd));
    831   1.54   mycroft 		free((char *)save.pw_passwd);
    832   1.54   mycroft 		free((char *)save.pw_gecos);
    833   1.54   mycroft 		free((char *)save.pw_dir);
    834   1.54   mycroft 		free((char *)save.pw_shell);
    835    1.1       cgd 	}
    836    1.1       cgd 	save = *p;
    837  1.171  christos 	save.pw_name = ftpd_strdup(p->pw_name);
    838  1.171  christos 	save.pw_passwd = ftpd_strdup(p->pw_passwd);
    839  1.171  christos 	save.pw_gecos = ftpd_strdup(p->pw_gecos);
    840  1.171  christos 	save.pw_dir = ftpd_strdup(p->pw_dir);
    841  1.171  christos 	save.pw_shell = ftpd_strdup(p->pw_shell);
    842    1.1       cgd 	return (&save);
    843    1.1       cgd }
    844    1.1       cgd 
    845   1.93     lukem static int	login_attempts;	/* number of failed login attempts */
    846  1.133     lukem static int	askpasswd;	/* had USER command, ask for PASSwd */
    847  1.133     lukem static int	permitted;	/* USER permitted */
    848    1.1       cgd 
    849    1.1       cgd /*
    850    1.1       cgd  * USER command.
    851    1.1       cgd  * Sets global passwd pointer pw if named account exists and is acceptable;
    852    1.1       cgd  * sets askpasswd if a PASS command is expected.  If logged in previously,
    853    1.1       cgd  * need to reset state.  If name is "ftp" or "anonymous", the name is not in
    854  1.163  christos  * _NAME_FTPUSERS, and ftp account exists, set guest and pw, then just return.
    855    1.1       cgd  * If account doesn't exist, ask for passwd anyway.  Otherwise, check user
    856    1.1       cgd  * requesting login privileges.  Disallow anyone who does not have a standard
    857    1.1       cgd  * shell as returned by getusershell().  Disallow anyone mentioned in the file
    858  1.163  christos  * _NAME_FTPUSERS to allow people such as root and uucp to be avoided.
    859    1.1       cgd  */
    860    1.8   deraadt void
    861   1.88     lukem user(const char *name)
    862    1.1       cgd {
    863  1.133     lukem 	char	*class;
    864  1.164  christos #ifdef	LOGIN_CAP
    865  1.164  christos 	login_cap_t *lc = NULL;
    866  1.164  christos #endif
    867  1.183     lukem #ifdef USE_PAM
    868  1.183     lukem 	int e;
    869  1.183     lukem #endif
    870  1.133     lukem 
    871  1.133     lukem 	class = NULL;
    872    1.1       cgd 	if (logged_in) {
    873   1.73     lukem 		switch (curclass.type) {
    874   1.73     lukem 		case CLASS_GUEST:
    875    1.1       cgd 			reply(530, "Can't change user from guest login.");
    876    1.1       cgd 			return;
    877   1.73     lukem 		case CLASS_CHROOT:
    878    1.5       cgd 			reply(530, "Can't change user from chroot user.");
    879    1.5       cgd 			return;
    880   1.73     lukem 		case CLASS_REAL:
    881  1.101     lukem 			if (dropprivs) {
    882  1.101     lukem 				reply(530, "Can't change user.");
    883  1.101     lukem 				return;
    884  1.101     lukem 			}
    885   1.73     lukem 			end_login();
    886   1.73     lukem 			break;
    887   1.73     lukem 		default:
    888   1.73     lukem 			abort();
    889    1.1       cgd 		}
    890    1.1       cgd 	}
    891    1.1       cgd 
    892   1.92  explorer #if defined(KERBEROS)
    893   1.38   mycroft 	kdestroy();
    894   1.38   mycroft #endif
    895   1.92  explorer #if defined(KERBEROS5)
    896   1.92  explorer 	k5destroy();
    897   1.92  explorer #endif
    898   1.38   mycroft 
    899   1.73     lukem 	curclass.type = CLASS_REAL;
    900  1.133     lukem 	askpasswd = 0;
    901  1.133     lukem 	permitted = 0;
    902  1.133     lukem 
    903    1.1       cgd 	if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
    904   1.81     lukem 			/* need `pw' setup for checkaccess() and checkuser () */
    905   1.81     lukem 		if ((pw = sgetpwnam("ftp")) == NULL)
    906   1.81     lukem 			reply(530, "User %s unknown.", name);
    907   1.82     lukem 		else if (! checkaccess("ftp") || ! checkaccess("anonymous"))
    908    1.1       cgd 			reply(530, "User %s access denied.", name);
    909   1.81     lukem 		else {
    910   1.73     lukem 			curclass.type = CLASS_GUEST;
    911    1.1       cgd 			askpasswd = 1;
    912    1.8   deraadt 			reply(331,
    913    1.8   deraadt 			    "Guest login ok, type your name as password.");
    914   1.81     lukem 		}
    915  1.133     lukem 		if (!askpasswd) {
    916  1.133     lukem 			if (logging)
    917  1.133     lukem 				syslog(LOG_NOTICE,
    918  1.133     lukem 				    "ANONYMOUS FTP LOGIN REFUSED FROM %s",
    919  1.191  christos 				    remoteloghost);
    920  1.133     lukem 			end_login();
    921  1.133     lukem 			goto cleanup_user;
    922  1.133     lukem 		}
    923  1.133     lukem 		name = "ftp";
    924  1.133     lukem 	} else
    925  1.133     lukem 		pw = sgetpwnam(name);
    926   1.34     lukem 
    927  1.157     lukem 	strlcpy(curname, name, curname_len);
    928   1.36   mycroft 
    929  1.133     lukem 			/* check user in /etc/ftpusers, and setup class */
    930  1.163  christos 	permitted = checkuser(_NAME_FTPUSERS, curname, 1, 0, &class);
    931  1.133     lukem 
    932  1.133     lukem 			/* check user in /etc/ftpchroot */
    933  1.177     lukem #ifdef	LOGIN_CAP
    934  1.164  christos 	lc = login_getpwclass(pw);
    935  1.177     lukem #endif
    936  1.164  christos 	if (checkuser(_NAME_FTPCHROOT, curname, 0, 0, NULL)
    937  1.164  christos #ifdef	LOGIN_CAP	/* Allow login.conf configuration as well */
    938  1.164  christos 	    || login_getcapbool(lc, "ftp-chroot", 0)
    939  1.164  christos #endif
    940  1.164  christos 	) {
    941  1.133     lukem 		if (curclass.type == CLASS_GUEST) {
    942  1.133     lukem 			syslog(LOG_NOTICE,
    943  1.133     lukem 	    "Can't change guest user to chroot class; remove entry in %s",
    944  1.163  christos 			    _NAME_FTPCHROOT);
    945  1.133     lukem 			exit(1);
    946  1.133     lukem 		}
    947  1.133     lukem 		curclass.type = CLASS_CHROOT;
    948  1.133     lukem 	}
    949  1.183     lukem 
    950  1.133     lukem 			/* determine default class */
    951  1.133     lukem 	if (class == NULL) {
    952  1.133     lukem 		switch (curclass.type) {
    953  1.133     lukem 		case CLASS_GUEST:
    954  1.171  christos 			class = ftpd_strdup("guest");
    955  1.133     lukem 			break;
    956  1.133     lukem 		case CLASS_CHROOT:
    957  1.171  christos 			class = ftpd_strdup("chroot");
    958  1.133     lukem 			break;
    959  1.133     lukem 		case CLASS_REAL:
    960  1.171  christos 			class = ftpd_strdup("real");
    961  1.133     lukem 			break;
    962  1.133     lukem 		default:
    963  1.133     lukem 			syslog(LOG_ERR, "unknown curclass.type %d; aborting",
    964  1.133     lukem 			    curclass.type);
    965  1.133     lukem 			abort();
    966  1.133     lukem 		}
    967  1.133     lukem 	}
    968  1.133     lukem 			/* parse ftpd.conf, setting up various parameters */
    969  1.133     lukem 	parse_conf(class);
    970  1.133     lukem 			/* if not guest user, check for valid shell */
    971  1.133     lukem 	if (pw == NULL)
    972  1.133     lukem 		permitted = 0;
    973  1.133     lukem 	else {
    974  1.133     lukem 		const char	*cp, *shell;
    975  1.133     lukem 
    976  1.133     lukem 		if ((shell = pw->pw_shell) == NULL || *shell == 0)
    977  1.133     lukem 			shell = _PATH_BSHELL;
    978  1.133     lukem 		while ((cp = getusershell()) != NULL)
    979  1.133     lukem 			if (strcmp(cp, shell) == 0)
    980  1.133     lukem 				break;
    981  1.133     lukem 		endusershell();
    982  1.133     lukem 		if (cp == NULL && curclass.type != CLASS_GUEST)
    983  1.133     lukem 			permitted = 0;
    984  1.133     lukem 	}
    985  1.133     lukem 
    986  1.133     lukem 			/* deny quickly (after USER not PASS) if requested */
    987  1.133     lukem 	if (CURCLASS_FLAGS_ISSET(denyquick) && !permitted) {
    988  1.133     lukem 		reply(530, "User %s may not use FTP.", curname);
    989  1.133     lukem 		if (logging)
    990  1.133     lukem 			syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
    991  1.191  christos 			    remoteloghost, curname);
    992  1.133     lukem 		end_login();
    993  1.133     lukem 		goto cleanup_user;
    994  1.133     lukem 	}
    995  1.133     lukem 
    996  1.133     lukem 			/* if haven't asked yet (i.e, not anon), ask now */
    997  1.133     lukem 	if (!askpasswd) {
    998  1.133     lukem 		askpasswd = 1;
    999  1.183     lukem #ifdef USE_PAM
   1000  1.183     lukem 		e = auth_pam();		/* this does reply(331, ...) */
   1001  1.183     lukem 		do_pass(1, e, "");
   1002  1.183     lukem 		goto cleanup_user;
   1003  1.183     lukem #else /* !USE_PAM */
   1004    1.7   deraadt #ifdef SKEY
   1005  1.133     lukem 		if (skey_haskey(curname) == 0) {
   1006  1.133     lukem 			const char *myskey;
   1007    1.7   deraadt 
   1008  1.133     lukem 			myskey = skey_keyinfo(curname);
   1009  1.134     lukem 			reply(331, "Password [ %s ] required for %s.",
   1010  1.133     lukem 			    myskey ? myskey : "error getting challenge",
   1011  1.133     lukem 			    curname);
   1012  1.133     lukem 		} else
   1013    1.7   deraadt #endif
   1014  1.133     lukem 			reply(331, "Password required for %s.", curname);
   1015  1.183     lukem #endif /* !USE_PAM */
   1016  1.133     lukem 	}
   1017    1.7   deraadt 
   1018  1.133     lukem  cleanup_user:
   1019  1.164  christos #ifdef LOGIN_CAP
   1020  1.164  christos 	login_close(lc);
   1021  1.164  christos #endif
   1022    1.1       cgd 	/*
   1023    1.1       cgd 	 * Delay before reading passwd after first failed
   1024    1.1       cgd 	 * attempt to slow down passwd-guessing programs.
   1025    1.1       cgd 	 */
   1026    1.1       cgd 	if (login_attempts)
   1027    1.1       cgd 		sleep((unsigned) login_attempts);
   1028  1.133     lukem 
   1029  1.133     lukem 	if (class)
   1030  1.133     lukem 		free(class);
   1031    1.1       cgd }
   1032    1.1       cgd 
   1033    1.1       cgd /*
   1034   1.58     lukem  * Determine whether something is to happen (allow access, chroot)
   1035   1.58     lukem  * for a user. Each line is a shell-style glob followed by
   1036   1.58     lukem  * `yes' or `no'.
   1037   1.58     lukem  *
   1038  1.126       wiz  * For backward compatibility, `allow' and `deny' are synonymns
   1039   1.58     lukem  * for `yes' and `no', respectively.
   1040   1.19       cjs  *
   1041   1.21       cjs  * Each glob is matched against the username in turn, and the first
   1042   1.58     lukem  * match found is used. If no match is found, the result is the
   1043   1.58     lukem  * argument `def'. If a match is found but without and explicit
   1044   1.58     lukem  * `yes'/`no', the result is the opposite of def.
   1045   1.58     lukem  *
   1046   1.58     lukem  * If the file doesn't exist at all, the result is the argument
   1047   1.58     lukem  * `nofile'
   1048   1.21       cjs  *
   1049   1.21       cjs  * Any line starting with `#' is considered a comment and ignored.
   1050   1.19       cjs  *
   1051   1.73     lukem  * Returns 0 if the user is denied, or 1 if they are allowed.
   1052   1.81     lukem  *
   1053   1.81     lukem  * NOTE: needs struct passwd *pw setup before use.
   1054   1.19       cjs  */
   1055  1.118     lukem static int
   1056   1.88     lukem checkuser(const char *fname, const char *name, int def, int nofile,
   1057   1.88     lukem 	    char **retclass)
   1058   1.58     lukem {
   1059   1.58     lukem 	FILE	*fd;
   1060   1.58     lukem 	int	 retval;
   1061  1.132     lukem 	char	*word, *perm, *class, *buf, *p;
   1062   1.76     lukem 	size_t	 len, line;
   1063   1.58     lukem 
   1064   1.58     lukem 	retval = def;
   1065   1.73     lukem 	if (retclass != NULL)
   1066   1.73     lukem 		*retclass = NULL;
   1067   1.58     lukem 	if ((fd = fopen(conffilename(fname), "r")) == NULL)
   1068   1.58     lukem 		return nofile;
   1069   1.19       cjs 
   1070   1.76     lukem 	line = 0;
   1071   1.73     lukem 	for (;
   1072   1.76     lukem 	    (buf = fparseln(fd, &len, &line, NULL, FPARSELN_UNESCCOMM |
   1073  1.147     lukem 			    FPARSELN_UNESCCONT | FPARSELN_UNESCESC)) != NULL;
   1074   1.73     lukem 	    free(buf), buf = NULL) {
   1075  1.132     lukem 		word = perm = class = NULL;
   1076   1.73     lukem 		p = buf;
   1077   1.73     lukem 		if (len < 1)
   1078   1.73     lukem 			continue;
   1079   1.73     lukem 		if (p[len - 1] == '\n')
   1080   1.73     lukem 			p[--len] = '\0';
   1081   1.73     lukem 		if (EMPTYSTR(p))
   1082   1.19       cjs 			continue;
   1083   1.73     lukem 
   1084  1.132     lukem 		NEXTWORD(p, word);
   1085   1.73     lukem 		NEXTWORD(p, perm);
   1086   1.73     lukem 		NEXTWORD(p, class);
   1087  1.132     lukem 		if (EMPTYSTR(word))
   1088   1.70      tron 			continue;
   1089   1.76     lukem 		if (!EMPTYSTR(class)) {
   1090   1.76     lukem 			if (strcasecmp(class, "all") == 0 ||
   1091   1.76     lukem 			    strcasecmp(class, "none") == 0) {
   1092   1.76     lukem 				syslog(LOG_WARNING,
   1093   1.76     lukem 		"%s line %d: illegal user-defined class `%s' - skipping entry",
   1094   1.76     lukem 					    fname, (int)line, class);
   1095   1.76     lukem 				continue;
   1096   1.76     lukem 			}
   1097   1.76     lukem 		}
   1098   1.73     lukem 
   1099   1.73     lukem 					/* have a host specifier */
   1100  1.132     lukem 		if ((p = strchr(word, '@')) != NULL) {
   1101  1.188     lukem 			unsigned char	net[16], mask[16], *addr;
   1102  1.188     lukem 			int		addrlen, bits, bytes, a;
   1103   1.73     lukem 
   1104   1.73     lukem 			*p++ = '\0';
   1105   1.73     lukem 					/* check against network or CIDR */
   1106  1.188     lukem 			memset(net, 0x00, sizeof(net));
   1107  1.188     lukem 			if ((bits = inet_net_pton(his_addr.su_family, p, net,
   1108  1.188     lukem 			    sizeof(net))) != -1) {
   1109  1.188     lukem #ifdef INET6
   1110  1.188     lukem 				if (his_addr.su_family == AF_INET) {
   1111  1.188     lukem #endif
   1112  1.188     lukem 					addrlen = 4;
   1113  1.188     lukem 					addr = (unsigned char *)&his_addr.su_addr;
   1114  1.188     lukem #ifdef INET6
   1115  1.188     lukem 				} else {
   1116  1.188     lukem 					addrlen = 16;
   1117  1.188     lukem 					addr = (unsigned char *)&his_addr.su_6addr;
   1118  1.188     lukem 				}
   1119  1.188     lukem #endif
   1120  1.188     lukem 				bytes = bits / 8;
   1121  1.188     lukem 				bits = bits % 8;
   1122  1.188     lukem 				if (bytes > 0)
   1123  1.188     lukem 					memset(mask, 0xFF, bytes);
   1124  1.188     lukem 				if (bytes < addrlen)
   1125  1.188     lukem 					mask[bytes] = 0xFF << (8 - bits);
   1126  1.188     lukem 				if (bytes + 1 < addrlen)
   1127  1.188     lukem 					memset(mask + bytes + 1, 0x00,
   1128  1.188     lukem 					    addrlen - bytes - 1);
   1129  1.188     lukem 				for (a = 0; a < addrlen; a++)
   1130  1.188     lukem 					if ((addr[a] & mask[a]) != net[a])
   1131  1.188     lukem 						break;
   1132  1.188     lukem 				if (a < addrlen)
   1133   1.73     lukem 					continue;
   1134   1.73     lukem 
   1135   1.73     lukem 					/* check against hostname glob */
   1136  1.132     lukem 			} else if (fnmatch(p, remotehost, FNM_CASEFOLD) != 0)
   1137   1.73     lukem 				continue;
   1138   1.19       cjs 		}
   1139   1.73     lukem 
   1140   1.81     lukem 					/* have a group specifier */
   1141  1.132     lukem 		if ((p = strchr(word, ':')) != NULL) {
   1142   1.81     lukem 			gid_t	*groups, *ng;
   1143   1.81     lukem 			int	 gsize, i, found;
   1144   1.81     lukem 
   1145  1.133     lukem 			if (pw == NULL)
   1146  1.133     lukem 				continue;	/* no match for unknown user */
   1147   1.81     lukem 			*p++ = '\0';
   1148   1.81     lukem 			groups = NULL;
   1149   1.81     lukem 			gsize = 16;
   1150   1.81     lukem 			do {
   1151   1.81     lukem 				ng = realloc(groups, gsize * sizeof(gid_t));
   1152   1.81     lukem 				if (ng == NULL)
   1153   1.81     lukem 					fatal(
   1154   1.81     lukem 					    "Local resource failure: realloc");
   1155   1.81     lukem 				groups = ng;
   1156   1.81     lukem 			} while (getgrouplist(pw->pw_name, pw->pw_gid,
   1157   1.81     lukem 						groups, &gsize) == -1);
   1158   1.81     lukem 			found = 0;
   1159   1.81     lukem 			for (i = 0; i < gsize; i++) {
   1160   1.81     lukem 				struct group *g;
   1161   1.81     lukem 
   1162   1.81     lukem 				if ((g = getgrgid(groups[i])) == NULL)
   1163   1.81     lukem 					continue;
   1164   1.81     lukem 				if (fnmatch(p, g->gr_name, 0) == 0) {
   1165   1.81     lukem 					found = 1;
   1166   1.81     lukem 					break;
   1167   1.81     lukem 				}
   1168   1.81     lukem 			}
   1169   1.81     lukem 			free(groups);
   1170   1.81     lukem 			if (!found)
   1171   1.81     lukem 				continue;
   1172   1.81     lukem 		}
   1173   1.81     lukem 
   1174   1.73     lukem 					/* check against username glob */
   1175  1.132     lukem 		if (fnmatch(word, name, 0) != 0)
   1176   1.73     lukem 			continue;
   1177   1.73     lukem 
   1178   1.73     lukem 		if (perm != NULL &&
   1179   1.73     lukem 		    ((strcasecmp(perm, "allow") == 0) ||
   1180   1.73     lukem 		     (strcasecmp(perm, "yes") == 0)))
   1181   1.73     lukem 			retval = 1;
   1182   1.73     lukem 		else if (perm != NULL &&
   1183   1.73     lukem 		    ((strcasecmp(perm, "deny") == 0) ||
   1184   1.73     lukem 		     (strcasecmp(perm, "no") == 0)))
   1185   1.73     lukem 			retval = 0;
   1186   1.73     lukem 		else
   1187   1.73     lukem 			retval = !def;
   1188   1.73     lukem 		if (!EMPTYSTR(class) && retclass != NULL)
   1189  1.171  christos 			*retclass = ftpd_strdup(class);
   1190   1.73     lukem 		free(buf);
   1191   1.73     lukem 		break;
   1192   1.19       cjs 	}
   1193   1.19       cjs 	(void) fclose(fd);
   1194   1.21       cjs 	return (retval);
   1195   1.19       cjs }
   1196   1.58     lukem 
   1197   1.58     lukem /*
   1198   1.58     lukem  * Check if user is allowed by /etc/ftpusers
   1199   1.73     lukem  * returns 1 for yes, 0 for no
   1200   1.81     lukem  *
   1201   1.81     lukem  * NOTE: needs struct passwd *pw setup (for checkuser())
   1202   1.58     lukem  */
   1203  1.118     lukem static int
   1204   1.88     lukem checkaccess(const char *name)
   1205   1.58     lukem {
   1206   1.58     lukem 
   1207  1.163  christos 	return (checkuser(_NAME_FTPUSERS, name, 1, 0, NULL));
   1208   1.58     lukem }
   1209   1.19       cjs 
   1210  1.140  christos static void
   1211  1.160  christos login_utmp(const char *line, const char *name, const char *host,
   1212  1.160  christos     struct sockinet *haddr)
   1213  1.140  christos {
   1214  1.140  christos #if defined(SUPPORT_UTMPX) || defined(SUPPORT_UTMP)
   1215  1.140  christos 	struct timeval tv;
   1216  1.140  christos 	(void)gettimeofday(&tv, NULL);
   1217  1.140  christos #endif
   1218  1.140  christos #ifdef SUPPORT_UTMPX
   1219  1.140  christos 	if (doutmp) {
   1220  1.140  christos 		(void)memset(&utmpx, 0, sizeof(utmpx));
   1221  1.140  christos 		utmpx.ut_tv = tv;
   1222  1.140  christos 		utmpx.ut_pid = getpid();
   1223  1.140  christos 		utmpx.ut_id[0] = 'f';
   1224  1.140  christos 		utmpx.ut_id[1] = 't';
   1225  1.140  christos 		utmpx.ut_id[2] = 'p';
   1226  1.140  christos 		utmpx.ut_id[3] = '*';
   1227  1.140  christos 		utmpx.ut_type = USER_PROCESS;
   1228  1.144    itojun 		(void)strncpy(utmpx.ut_name, name, sizeof(utmpx.ut_name));
   1229  1.144    itojun 		(void)strncpy(utmpx.ut_line, line, sizeof(utmpx.ut_line));
   1230  1.144    itojun 		(void)strncpy(utmpx.ut_host, host, sizeof(utmpx.ut_host));
   1231  1.160  christos 		(void)memcpy(&utmpx.ut_ss, &haddr->si_su, haddr->su_len);
   1232  1.155     tacha 		ftpd_loginx(&utmpx);
   1233  1.140  christos 	}
   1234  1.140  christos 	if (dowtmp)
   1235  1.160  christos 		ftpd_logwtmpx(line, name, host, haddr, 0, USER_PROCESS);
   1236  1.140  christos #endif
   1237  1.140  christos #ifdef SUPPORT_UTMP
   1238  1.140  christos 	if (doutmp) {
   1239  1.140  christos 		(void)memset(&utmp, 0, sizeof(utmp));
   1240  1.140  christos 		(void)time(&utmp.ut_time);
   1241  1.144    itojun 		(void)strncpy(utmp.ut_name, name, sizeof(utmp.ut_name));
   1242  1.144    itojun 		(void)strncpy(utmp.ut_line, line, sizeof(utmp.ut_line));
   1243  1.144    itojun 		(void)strncpy(utmp.ut_host, host, sizeof(utmp.ut_host));
   1244  1.152     lukem 		ftpd_login(&utmp);
   1245  1.140  christos 	}
   1246  1.140  christos 	if (dowtmp)
   1247  1.152     lukem 		ftpd_logwtmp(line, name, host);
   1248  1.140  christos #endif
   1249  1.140  christos }
   1250  1.140  christos 
   1251  1.140  christos static void
   1252  1.140  christos logout_utmp(void)
   1253  1.140  christos {
   1254  1.140  christos #ifdef SUPPORT_UTMPX
   1255  1.166  christos 	int okwtmpx = dowtmp;
   1256  1.140  christos #endif
   1257  1.140  christos #ifdef SUPPORT_UTMP
   1258  1.166  christos 	int okwtmp = dowtmp;
   1259  1.140  christos #endif
   1260  1.166  christos 	if (logged_in) {
   1261  1.140  christos #ifdef SUPPORT_UTMPX
   1262  1.166  christos 		if (doutmp)
   1263  1.166  christos 			okwtmpx &= ftpd_logoutx(ttyline, 0, DEAD_PROCESS);
   1264  1.166  christos 		if (okwtmpx)
   1265  1.166  christos 			ftpd_logwtmpx(ttyline, "", "", NULL, 0, DEAD_PROCESS);
   1266  1.140  christos #endif
   1267  1.140  christos #ifdef SUPPORT_UTMP
   1268  1.166  christos 		if (doutmp)
   1269  1.166  christos 			okwtmp &= ftpd_logout(ttyline);
   1270  1.166  christos 		if (okwtmp)
   1271  1.152     lukem 			ftpd_logwtmp(ttyline, "", "");
   1272  1.140  christos #endif
   1273  1.140  christos 	}
   1274  1.140  christos }
   1275  1.140  christos 
   1276   1.19       cjs /*
   1277  1.118     lukem  * Terminate login as previous user (if any), resetting state;
   1278    1.1       cgd  * used when USER command is given or login fails.
   1279    1.1       cgd  */
   1280    1.8   deraadt static void
   1281   1.88     lukem end_login(void)
   1282    1.1       cgd {
   1283  1.164  christos #ifdef USE_PAM
   1284  1.164  christos 	int e;
   1285  1.164  christos #endif
   1286  1.140  christos 	logout_utmp();
   1287  1.118     lukem 	show_chdir_messages(-1);		/* flush chdir cache */
   1288  1.118     lukem 	if (pw != NULL && pw->pw_passwd != NULL)
   1289  1.118     lukem 		memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
   1290    1.1       cgd 	pw = NULL;
   1291    1.1       cgd 	logged_in = 0;
   1292  1.133     lukem 	askpasswd = 0;
   1293  1.133     lukem 	permitted = 0;
   1294   1.85     lukem 	quietmessages = 0;
   1295   1.95     lukem 	gidcount = 0;
   1296   1.73     lukem 	curclass.type = CLASS_REAL;
   1297  1.118     lukem 	(void) seteuid((uid_t)0);
   1298  1.164  christos #ifdef	LOGIN_CAP
   1299  1.164  christos 	setusercontext(NULL, getpwuid(0), 0,
   1300  1.164  christos 		       LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
   1301  1.164  christos #endif
   1302  1.164  christos #ifdef USE_PAM
   1303  1.164  christos 	if (pamh) {
   1304  1.164  christos 		if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
   1305  1.164  christos 			syslog(LOG_ERR, "pam_setcred: %s",
   1306  1.164  christos 			    pam_strerror(pamh, e));
   1307  1.164  christos 		if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
   1308  1.164  christos 			syslog(LOG_ERR, "pam_close_session: %s",
   1309  1.164  christos 			    pam_strerror(pamh, e));
   1310  1.164  christos 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
   1311  1.164  christos 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
   1312  1.164  christos 		pamh = NULL;
   1313  1.164  christos 	}
   1314  1.164  christos #endif
   1315    1.1       cgd }
   1316    1.1       cgd 
   1317    1.8   deraadt void
   1318   1.88     lukem pass(const char *passwd)
   1319    1.1       cgd {
   1320  1.183     lukem 	do_pass(0, 0, passwd);
   1321  1.183     lukem }
   1322  1.183     lukem 
   1323  1.183     lukem /*
   1324  1.183     lukem  * Perform the passwd confirmation and login.
   1325  1.183     lukem  *
   1326  1.183     lukem  * If pass_checked is zero, confirm passwd is correct, & ignore pass_rval.
   1327  1.183     lukem  * This is the traditional PASS implementation.
   1328  1.183     lukem  *
   1329  1.183     lukem  * If pass_checked is non-zero, use pass_rval and ignore passwd.
   1330  1.183     lukem  * This is used by auth_pam() which has already parsed PASS.
   1331  1.183     lukem  * This only applies to curclass.type != CLASS_GUEST.
   1332  1.183     lukem  */
   1333  1.183     lukem static void
   1334  1.183     lukem do_pass(int pass_checked, int pass_rval, const char *passwd)
   1335  1.183     lukem {
   1336   1.78     lukem 	int		 rval;
   1337  1.133     lukem 	char		 root[MAXPATHLEN];
   1338  1.164  christos #ifdef	LOGIN_CAP
   1339  1.164  christos 	login_cap_t *lc = NULL;
   1340  1.164  christos #endif
   1341  1.164  christos #ifdef USE_PAM
   1342  1.164  christos 	int e;
   1343  1.164  christos #endif
   1344  1.183     lukem 
   1345  1.183     lukem 	rval = 1;
   1346  1.183     lukem 
   1347    1.1       cgd 	if (logged_in || askpasswd == 0) {
   1348    1.1       cgd 		reply(503, "Login with USER first.");
   1349    1.1       cgd 		return;
   1350    1.1       cgd 	}
   1351    1.1       cgd 	askpasswd = 0;
   1352   1.73     lukem 	if (curclass.type != CLASS_GUEST) {
   1353  1.101     lukem 			/* "ftp" is the only account allowed with no password */
   1354    1.8   deraadt 		if (pw == NULL) {
   1355    1.8   deraadt 			rval = 1;	/* failure below */
   1356    1.8   deraadt 			goto skip;
   1357    1.8   deraadt 		}
   1358  1.183     lukem 		if (pass_checked) {	/* password validated in user() */
   1359  1.183     lukem 			rval = pass_rval;
   1360  1.164  christos 			goto skip;
   1361  1.164  christos 		}
   1362  1.183     lukem #ifdef USE_PAM
   1363  1.183     lukem 		syslog(LOG_ERR, "do_pass: USE_PAM shouldn't get here");
   1364  1.183     lukem 		rval = 1;
   1365  1.164  christos 		goto skip;
   1366  1.164  christos #endif
   1367   1.92  explorer #if defined(KERBEROS)
   1368   1.64   thorpej 		if (klogin(pw, "", hostname, (char *)passwd) == 0) {
   1369   1.92  explorer 			rval = 0;
   1370   1.92  explorer 			goto skip;
   1371   1.92  explorer 		}
   1372   1.92  explorer #endif
   1373   1.92  explorer #if defined(KERBEROS5)
   1374   1.92  explorer 		if (k5login(pw, "", hostname, (char *)passwd) == 0) {
   1375   1.37   mycroft 			rval = 0;
   1376   1.37   mycroft 			goto skip;
   1377   1.37   mycroft 		}
   1378   1.37   mycroft #endif
   1379   1.36   mycroft #ifdef SKEY
   1380   1.62     lukem 		if (skey_haskey(pw->pw_name) == 0) {
   1381   1.62     lukem 			char *p;
   1382   1.62     lukem 			int r;
   1383   1.62     lukem 
   1384  1.171  christos 			p = ftpd_strdup(passwd);
   1385   1.62     lukem 			r = skey_passcheck(pw->pw_name, p);
   1386   1.62     lukem 			free(p);
   1387   1.62     lukem 			if (r != -1) {
   1388   1.62     lukem 				rval = 0;
   1389   1.62     lukem 				goto skip;
   1390   1.62     lukem 			}
   1391   1.36   mycroft 		}
   1392    1.4       cgd #endif
   1393  1.116     lukem 		if (!sflag)
   1394  1.116     lukem 			rval = checkpassword(pw, passwd);
   1395  1.116     lukem 		else
   1396  1.116     lukem 			rval = 1;
   1397    1.4       cgd 
   1398   1.89     lukem  skip:
   1399  1.101     lukem 
   1400  1.101     lukem 			/*
   1401  1.101     lukem 			 * If rval > 0, the user failed the authentication check
   1402  1.101     lukem 			 * above.  If rval == 0, either Kerberos or local
   1403  1.101     lukem 			 * authentication succeeded.
   1404  1.101     lukem 			 */
   1405    1.4       cgd 		if (rval) {
   1406   1.98  sommerfe 			reply(530, "%s", rval == 2 ? "Password expired." :
   1407   1.45  christos 			    "Login incorrect.");
   1408  1.201  christos 			pfilter_notify(1, rval == 2 ? "exppass" : "badpass");
   1409   1.23     lukem 			if (logging) {
   1410    1.8   deraadt 				syslog(LOG_NOTICE,
   1411  1.191  christos 				    "FTP LOGIN FAILED FROM %s", remoteloghost);
   1412   1.23     lukem 				syslog(LOG_AUTHPRIV | LOG_NOTICE,
   1413    1.8   deraadt 				    "FTP LOGIN FAILED FROM %s, %s",
   1414  1.191  christos 				    remoteloghost, curname);
   1415   1.23     lukem 			}
   1416    1.1       cgd 			pw = NULL;
   1417    1.1       cgd 			if (login_attempts++ >= 5) {
   1418    1.1       cgd 				syslog(LOG_NOTICE,
   1419    1.1       cgd 				    "repeated login failures from %s",
   1420  1.191  christos 				    remoteloghost);
   1421    1.1       cgd 				exit(0);
   1422    1.1       cgd 			}
   1423    1.1       cgd 			return;
   1424    1.1       cgd 		}
   1425    1.1       cgd 	}
   1426   1.19       cjs 
   1427  1.133     lukem 			/* password ok; check if anything else prevents login */
   1428  1.133     lukem 	if (! permitted) {
   1429   1.19       cjs 		reply(530, "User %s may not use FTP.", pw->pw_name);
   1430   1.19       cjs 		if (logging)
   1431   1.62     lukem 			syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
   1432  1.191  christos 			    remoteloghost, pw->pw_name);
   1433   1.82     lukem 		goto bad;
   1434   1.19       cjs 	}
   1435   1.19       cjs 
   1436    1.1       cgd 	login_attempts = 0;		/* this time successful */
   1437    1.8   deraadt 	if (setegid((gid_t)pw->pw_gid) < 0) {
   1438    1.8   deraadt 		reply(550, "Can't set gid.");
   1439   1.82     lukem 		goto bad;
   1440    1.8   deraadt 	}
   1441  1.164  christos #ifdef	LOGIN_CAP
   1442  1.164  christos 	if ((lc = login_getpwclass(pw)) != NULL) {
   1443  1.164  christos #ifdef notyet
   1444  1.164  christos 		char	remote_ip[NI_MAXHOST];
   1445  1.164  christos 
   1446  1.164  christos 		if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
   1447  1.164  christos 			remote_ip, sizeof(remote_ip) - 1, NULL, 0,
   1448  1.164  christos 			NI_NUMERICHOST))
   1449  1.164  christos 				*remote_ip = 0;
   1450  1.164  christos 		remote_ip[sizeof(remote_ip) - 1] = 0;
   1451  1.164  christos 		if (!auth_hostok(lc, remotehost, remote_ip)) {
   1452  1.201  christos 			pfilter_notify(1, "bannedhost");
   1453  1.164  christos 			syslog(LOG_INFO|LOG_AUTH,
   1454  1.164  christos 			    "FTP LOGIN FAILED (HOST) as %s: permission denied.",
   1455  1.164  christos 			    pw->pw_name);
   1456  1.164  christos 			reply(530, "Permission denied.");
   1457  1.164  christos 			pw = NULL;
   1458  1.164  christos 			return;
   1459  1.164  christos 		}
   1460  1.164  christos 		if (!auth_timeok(lc, time(NULL))) {
   1461  1.164  christos 			reply(530, "Login not available right now.");
   1462  1.164  christos 			pw = NULL;
   1463  1.164  christos 			return;
   1464  1.164  christos 		}
   1465  1.164  christos #endif
   1466  1.164  christos 	}
   1467  1.164  christos 	setsid();
   1468  1.164  christos 	setusercontext(lc, pw, 0,
   1469  1.164  christos 		LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
   1470  1.164  christos 		LOGIN_SETRESOURCES|LOGIN_SETUMASK);
   1471  1.164  christos #else
   1472    1.1       cgd 	(void) initgroups(pw->pw_name, pw->pw_gid);
   1473  1.101     lukem 			/* cache groups for cmds.c::matchgroup() */
   1474  1.164  christos #endif
   1475  1.164  christos #ifdef USE_PAM
   1476  1.164  christos 	if (pamh) {
   1477  1.164  christos 		if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
   1478  1.164  christos 			syslog(LOG_ERR, "pam_open_session: %s",
   1479  1.164  christos 			    pam_strerror(pamh, e));
   1480  1.164  christos 		} else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED))
   1481  1.164  christos 		    != PAM_SUCCESS) {
   1482  1.164  christos 			syslog(LOG_ERR, "pam_setcred: %s",
   1483  1.164  christos 			    pam_strerror(pamh, e));
   1484  1.164  christos 		}
   1485  1.164  christos 	}
   1486  1.164  christos #endif
   1487  1.151       dsl 	gidcount = getgroups(0, NULL);
   1488  1.151       dsl 	if (gidlist)
   1489  1.151       dsl 		free(gidlist);
   1490  1.151       dsl 	gidlist = malloc(gidcount * sizeof *gidlist);
   1491  1.151       dsl 	gidcount = getgroups(gidcount, gidlist);
   1492    1.1       cgd 
   1493  1.140  christos 	/* open utmp/wtmp before chroot */
   1494  1.160  christos 	login_utmp(ttyline, pw->pw_name, remotehost, &his_addr);
   1495   1.78     lukem 
   1496    1.1       cgd 	logged_in = 1;
   1497    1.1       cgd 
   1498  1.111     lukem 	connections = 1;
   1499  1.111     lukem 	if (dopidfile)
   1500  1.111     lukem 		count_users();
   1501   1.82     lukem 	if (curclass.limit != -1 && connections > curclass.limit) {
   1502   1.82     lukem 		if (! EMPTYSTR(curclass.limitfile))
   1503  1.100     lukem 			(void)display_file(conffilename(curclass.limitfile),
   1504  1.100     lukem 			    530);
   1505   1.82     lukem 		reply(530,
   1506  1.147     lukem 		    "User %s access denied, connection limit of " LLF
   1507  1.147     lukem 		    " reached.",
   1508  1.147     lukem 		    pw->pw_name, (LLT)curclass.limit);
   1509   1.82     lukem 		syslog(LOG_NOTICE,
   1510  1.147     lukem 		    "Maximum connection limit of " LLF
   1511  1.147     lukem 		    " for class %s reached, login refused for %s",
   1512  1.147     lukem 		    (LLT)curclass.limit, curclass.classname, pw->pw_name);
   1513   1.82     lukem 		goto bad;
   1514   1.82     lukem 	}
   1515   1.24     lukem 
   1516  1.100     lukem 	homedir[0] = '/';
   1517   1.73     lukem 	switch (curclass.type) {
   1518   1.73     lukem 	case CLASS_GUEST:
   1519  1.101     lukem 			/*
   1520  1.101     lukem 			 * We MUST do a chdir() after the chroot. Otherwise
   1521  1.101     lukem 			 * the old current directory will be accessible as "."
   1522  1.101     lukem 			 * outside the new root!
   1523  1.101     lukem 			 */
   1524  1.100     lukem 		format_path(root,
   1525  1.100     lukem 		    curclass.chroot ? curclass.chroot :
   1526  1.100     lukem 		    anondir ? anondir :
   1527  1.100     lukem 		    pw->pw_dir);
   1528  1.100     lukem 		format_path(homedir,
   1529  1.100     lukem 		    curclass.homedir ? curclass.homedir :
   1530  1.100     lukem 		    "/");
   1531  1.100     lukem 		if (EMPTYSTR(homedir))
   1532  1.100     lukem 			homedir[0] = '/';
   1533  1.100     lukem 		if (EMPTYSTR(root) || chroot(root) < 0) {
   1534  1.100     lukem 			syslog(LOG_NOTICE,
   1535  1.100     lukem 			    "GUEST user %s: can't chroot to %s: %m",
   1536  1.100     lukem 			    pw->pw_name, root);
   1537  1.100     lukem 			goto bad_guest;
   1538  1.100     lukem 		}
   1539  1.100     lukem 		if (chdir(homedir) < 0) {
   1540  1.100     lukem 			syslog(LOG_NOTICE,
   1541  1.100     lukem 			    "GUEST user %s: can't chdir to %s: %m",
   1542  1.100     lukem 			    pw->pw_name, homedir);
   1543  1.100     lukem  bad_guest:
   1544    1.1       cgd 			reply(550, "Can't set guest privileges.");
   1545    1.5       cgd 			goto bad;
   1546    1.5       cgd 		}
   1547   1.73     lukem 		break;
   1548   1.73     lukem 	case CLASS_CHROOT:
   1549  1.100     lukem 		format_path(root,
   1550  1.100     lukem 		    curclass.chroot ? curclass.chroot :
   1551  1.100     lukem 		    pw->pw_dir);
   1552  1.100     lukem 		format_path(homedir,
   1553  1.100     lukem 		    curclass.homedir ? curclass.homedir :
   1554  1.100     lukem 		    "/");
   1555  1.100     lukem 		if (EMPTYSTR(homedir))
   1556  1.100     lukem 			homedir[0] = '/';
   1557  1.100     lukem 		if (EMPTYSTR(root) || chroot(root) < 0) {
   1558  1.100     lukem 			syslog(LOG_NOTICE,
   1559  1.100     lukem 			    "CHROOT user %s: can't chroot to %s: %m",
   1560  1.100     lukem 			    pw->pw_name, root);
   1561  1.100     lukem 			goto bad_chroot;
   1562  1.100     lukem 		}
   1563  1.100     lukem 		if (chdir(homedir) < 0) {
   1564  1.100     lukem 			syslog(LOG_NOTICE,
   1565  1.100     lukem 			    "CHROOT user %s: can't chdir to %s: %m",
   1566  1.100     lukem 			    pw->pw_name, homedir);
   1567  1.100     lukem  bad_chroot:
   1568    1.5       cgd 			reply(550, "Can't change root.");
   1569    1.1       cgd 			goto bad;
   1570    1.1       cgd 		}
   1571   1.73     lukem 		break;
   1572   1.73     lukem 	case CLASS_REAL:
   1573  1.172       wiz 			/* only chroot REAL if explicitly requested */
   1574  1.118     lukem 		if (! EMPTYSTR(curclass.chroot)) {
   1575  1.118     lukem 			format_path(root, curclass.chroot);
   1576  1.118     lukem 			if (EMPTYSTR(root) || chroot(root) < 0) {
   1577  1.118     lukem 				syslog(LOG_NOTICE,
   1578  1.118     lukem 				    "REAL user %s: can't chroot to %s: %m",
   1579  1.118     lukem 				    pw->pw_name, root);
   1580  1.118     lukem 				goto bad_chroot;
   1581  1.118     lukem 			}
   1582  1.118     lukem 		}
   1583  1.100     lukem 		format_path(homedir,
   1584  1.100     lukem 		    curclass.homedir ? curclass.homedir :
   1585  1.100     lukem 		    pw->pw_dir);
   1586  1.100     lukem 		if (EMPTYSTR(homedir) || chdir(homedir) < 0) {
   1587   1.73     lukem 			if (chdir("/") < 0) {
   1588  1.100     lukem 				syslog(LOG_NOTICE,
   1589  1.100     lukem 				    "REAL user %s: can't chdir to %s: %m",
   1590  1.100     lukem 				    pw->pw_name,
   1591  1.100     lukem 				    !EMPTYSTR(homedir) ?  homedir : "/");
   1592   1.73     lukem 				reply(530,
   1593   1.73     lukem 				    "User %s: can't change directory to %s.",
   1594  1.100     lukem 				    pw->pw_name,
   1595  1.100     lukem 				    !EMPTYSTR(homedir) ? homedir : "/");
   1596   1.73     lukem 				goto bad;
   1597  1.100     lukem 			} else {
   1598   1.95     lukem 				reply(-230,
   1599   1.73     lukem 				    "No directory! Logging in with home=/");
   1600  1.100     lukem 				homedir[0] = '/';
   1601  1.100     lukem 			}
   1602  1.100     lukem 		}
   1603   1.73     lukem 		break;
   1604   1.73     lukem 	}
   1605  1.164  christos #ifndef LOGIN_CAP
   1606  1.151       dsl 	setsid();
   1607  1.105  jdolecek 	setlogin(pw->pw_name);
   1608  1.164  christos #endif
   1609  1.101     lukem 	if (dropprivs ||
   1610  1.101     lukem 	    (curclass.type != CLASS_REAL &&
   1611  1.101     lukem 	    ntohs(ctrl_addr.su_port) > IPPORT_RESERVED + 1)) {
   1612  1.101     lukem 		dropprivs++;
   1613  1.101     lukem 		if (setgid((gid_t)pw->pw_gid) < 0) {
   1614  1.101     lukem 			reply(550, "Can't set gid.");
   1615  1.101     lukem 			goto bad;
   1616  1.101     lukem 		}
   1617  1.101     lukem 		if (setuid((uid_t)pw->pw_uid) < 0) {
   1618  1.101     lukem 			reply(550, "Can't set uid.");
   1619  1.101     lukem 			goto bad;
   1620  1.101     lukem 		}
   1621  1.101     lukem 	} else {
   1622  1.101     lukem 		if (seteuid((uid_t)pw->pw_uid) < 0) {
   1623  1.101     lukem 			reply(550, "Can't set uid.");
   1624  1.101     lukem 			goto bad;
   1625  1.101     lukem 		}
   1626    1.1       cgd 	}
   1627  1.100     lukem 	setenv("HOME", homedir, 1);
   1628   1.44     lukem 
   1629   1.85     lukem 	if (curclass.type == CLASS_GUEST && passwd[0] == '-')
   1630   1.85     lukem 		quietmessages = 1;
   1631   1.85     lukem 
   1632  1.101     lukem 			/*
   1633  1.101     lukem 			 * Display a login message, if it exists.
   1634  1.101     lukem 			 * N.B. reply(230,) must follow the message.
   1635  1.101     lukem 			 */
   1636  1.131     lukem 	if (! EMPTYSTR(curclass.motd))
   1637  1.131     lukem 		(void)display_file(conffilename(curclass.motd), 230);
   1638   1.24     lukem 	show_chdir_messages(230);
   1639   1.73     lukem 	if (curclass.type == CLASS_GUEST) {
   1640  1.118     lukem 		char *p;
   1641  1.118     lukem 
   1642    1.1       cgd 		reply(230, "Guest login ok, access restrictions apply.");
   1643  1.181     lukem #if defined(HAVE_SETPROCTITLE)
   1644    1.8   deraadt 		snprintf(proctitle, sizeof(proctitle),
   1645  1.129     lukem 		    "%s: anonymous/%s", remotehost, passwd);
   1646   1.97    itojun 		setproctitle("%s", proctitle);
   1647  1.181     lukem #endif /* defined(HAVE_SETPROCTITLE) */
   1648    1.1       cgd 		if (logging)
   1649   1.81     lukem 			syslog(LOG_INFO,
   1650   1.81     lukem 			"ANONYMOUS FTP LOGIN FROM %s, %s (class: %s, type: %s)",
   1651  1.191  christos 			    remoteloghost, passwd,
   1652   1.81     lukem 			    curclass.classname, CURCLASSTYPE);
   1653  1.118     lukem 			/* store guest password reply into pw_passwd */
   1654  1.171  christos 		REASSIGN(pw->pw_passwd, ftpd_strdup(passwd));
   1655  1.118     lukem 		for (p = pw->pw_passwd; *p; p++)
   1656  1.159       dsl 			if (!isgraph((unsigned char)*p))
   1657  1.118     lukem 				*p = '_';
   1658    1.1       cgd 	} else {
   1659    1.1       cgd 		reply(230, "User %s logged in.", pw->pw_name);
   1660  1.181     lukem #if defined(HAVE_SETPROCTITLE)
   1661    1.8   deraadt 		snprintf(proctitle, sizeof(proctitle),
   1662    1.8   deraadt 		    "%s: %s", remotehost, pw->pw_name);
   1663   1.97    itojun 		setproctitle("%s", proctitle);
   1664  1.181     lukem #endif /* defined(HAVE_SETPROCTITLE) */
   1665    1.1       cgd 		if (logging)
   1666   1.81     lukem 			syslog(LOG_INFO,
   1667   1.81     lukem 			    "FTP LOGIN FROM %s as %s (class: %s, type: %s)",
   1668  1.191  christos 			    remoteloghost, pw->pw_name,
   1669   1.81     lukem 			    curclass.classname, CURCLASSTYPE);
   1670    1.1       cgd 	}
   1671   1.24     lukem 	(void) umask(curclass.umask);
   1672  1.164  christos #ifdef	LOGIN_CAP
   1673  1.164  christos 	login_close(lc);
   1674  1.164  christos #endif
   1675  1.133     lukem 	return;
   1676  1.111     lukem 
   1677   1.73     lukem  bad:
   1678  1.164  christos #ifdef	LOGIN_CAP
   1679  1.164  christos 	login_close(lc);
   1680  1.164  christos #endif
   1681  1.101     lukem 			/* Forget all about it... */
   1682    1.1       cgd 	end_login();
   1683    1.1       cgd }
   1684    1.1       cgd 
   1685    1.8   deraadt void
   1686  1.193     lukem retrieve(const char *argv[], const char *name)
   1687    1.1       cgd {
   1688   1.95     lukem 	FILE *fin, *dout;
   1689    1.1       cgd 	struct stat st;
   1690   1.88     lukem 	int (*closefunc)(FILE *) = NULL;
   1691  1.148   thorpej 	int dolog, sendrv, closerv, stderrfd, isconversion, isdata, isls;
   1692   1.62     lukem 	struct timeval start, finish, td, *tdp;
   1693  1.139     enami 	struct rusage rusage_before, rusage_after;
   1694   1.62     lukem 	const char *dispname;
   1695  1.193     lukem 	const char *error;
   1696    1.1       cgd 
   1697   1.49     lukem 	sendrv = closerv = stderrfd = -1;
   1698  1.148   thorpej 	isconversion = isdata = isls = dolog = 0;
   1699   1.62     lukem 	tdp = NULL;
   1700   1.62     lukem 	dispname = name;
   1701   1.95     lukem 	fin = dout = NULL;
   1702  1.138     lukem 	error = NULL;
   1703  1.118     lukem 	if (argv == NULL) {		/* if not running a command ... */
   1704  1.148   thorpej 		dolog = 1;
   1705   1.62     lukem 		isdata = 1;
   1706   1.62     lukem 		fin = fopen(name, "r");
   1707   1.62     lukem 		closefunc = fclose;
   1708  1.118     lukem 		if (fin == NULL)	/* doesn't exist?; try a conversion */
   1709   1.71     lukem 			argv = do_conversion(name);
   1710   1.71     lukem 		if (argv != NULL) {
   1711   1.49     lukem 			isconversion++;
   1712  1.118     lukem 			syslog(LOG_DEBUG, "get command: '%s' on '%s'",
   1713   1.71     lukem 			    argv[0], name);
   1714   1.49     lukem 		}
   1715   1.24     lukem 	}
   1716   1.71     lukem 	if (argv != NULL) {
   1717   1.82     lukem 		char temp[MAXPATHLEN];
   1718    1.1       cgd 
   1719   1.71     lukem 		if (strcmp(argv[0], INTERNAL_LS) == 0) {
   1720   1.63     lukem 			isls = 1;
   1721   1.63     lukem 			stderrfd = -1;
   1722   1.63     lukem 		} else {
   1723   1.63     lukem 			(void)snprintf(temp, sizeof(temp), "%s", TMPFILE);
   1724   1.63     lukem 			stderrfd = mkstemp(temp);
   1725   1.63     lukem 			if (stderrfd != -1)
   1726   1.63     lukem 				(void)unlink(temp);
   1727   1.63     lukem 		}
   1728   1.71     lukem 		dispname = argv[0];
   1729   1.71     lukem 		fin = ftpd_popen(argv, "r", stderrfd);
   1730   1.62     lukem 		closefunc = ftpd_pclose;
   1731    1.1       cgd 		st.st_size = -1;
   1732    1.1       cgd 		st.st_blksize = BUFSIZ;
   1733    1.1       cgd 	}
   1734    1.1       cgd 	if (fin == NULL) {
   1735    1.8   deraadt 		if (errno != 0) {
   1736   1.62     lukem 			perror_reply(550, dispname);
   1737  1.148   thorpej 			if (dolog)
   1738  1.118     lukem 				logxfer("get", -1, name, NULL, NULL,
   1739   1.62     lukem 				    strerror(errno));
   1740    1.8   deraadt 		}
   1741   1.71     lukem 		goto cleanupretrieve;
   1742    1.1       cgd 	}
   1743    1.8   deraadt 	byte_count = -1;
   1744   1.71     lukem 	if (argv == NULL
   1745   1.49     lukem 	    && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
   1746  1.138     lukem 		error = "Not a plain file";
   1747  1.138     lukem 		reply(550, "%s: %s.", dispname, error);
   1748    1.1       cgd 		goto done;
   1749    1.1       cgd 	}
   1750    1.1       cgd 	if (restart_point) {
   1751    1.1       cgd 		if (type == TYPE_A) {
   1752   1.49     lukem 			off_t i;
   1753    1.8   deraadt 			int c;
   1754    1.1       cgd 
   1755   1.49     lukem 			for (i = 0; i < restart_point; i++) {
   1756    1.1       cgd 				if ((c=getc(fin)) == EOF) {
   1757  1.138     lukem 					error = strerror(errno);
   1758   1.62     lukem 					perror_reply(550, dispname);
   1759    1.1       cgd 					goto done;
   1760    1.1       cgd 				}
   1761    1.1       cgd 				if (c == '\n')
   1762    1.1       cgd 					i++;
   1763    1.8   deraadt 			}
   1764   1.31    kleink 		} else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
   1765  1.138     lukem 			error = strerror(errno);
   1766   1.62     lukem 			perror_reply(550, dispname);
   1767    1.1       cgd 			goto done;
   1768    1.1       cgd 		}
   1769    1.1       cgd 	}
   1770   1.62     lukem 	dout = dataconn(dispname, st.st_size, "w");
   1771    1.1       cgd 	if (dout == NULL)
   1772    1.1       cgd 		goto done;
   1773   1.62     lukem 
   1774  1.139     enami 	(void)getrusage(RUSAGE_SELF, &rusage_before);
   1775   1.62     lukem 	(void)gettimeofday(&start, NULL);
   1776  1.139     enami 	sendrv = send_data(fin, dout, &st, isdata);
   1777   1.62     lukem 	(void)gettimeofday(&finish, NULL);
   1778  1.139     enami 	(void)getrusage(RUSAGE_SELF, &rusage_after);
   1779  1.137     lukem 	closedataconn(dout);		/* close now to affect timing stats */
   1780   1.62     lukem 	timersub(&finish, &start, &td);
   1781   1.62     lukem 	tdp = &td;
   1782   1.89     lukem  done:
   1783  1.148   thorpej 	if (dolog) {
   1784  1.138     lukem 		logxfer("get", byte_count, name, NULL, tdp, error);
   1785  1.139     enami 		if (tdp != NULL)
   1786  1.139     enami 			logrusage(&rusage_before, &rusage_after);
   1787  1.139     enami 	}
   1788   1.49     lukem 	closerv = (*closefunc)(fin);
   1789   1.49     lukem 	if (sendrv == 0) {
   1790  1.132     lukem 		FILE *errf;
   1791   1.49     lukem 		struct stat sb;
   1792   1.49     lukem 
   1793   1.71     lukem 		if (!isls && argv != NULL && closerv != 0) {
   1794   1.95     lukem 			reply(-226,
   1795   1.49     lukem 			    "Command returned an exit status of %d",
   1796   1.49     lukem 			    closerv);
   1797   1.49     lukem 			if (isconversion)
   1798  1.119     lukem 				syslog(LOG_WARNING,
   1799   1.71     lukem 				    "retrieve command: '%s' returned %d",
   1800   1.71     lukem 				    argv[0], closerv);
   1801   1.49     lukem 		}
   1802   1.71     lukem 		if (!isls && argv != NULL && stderrfd != -1 &&
   1803   1.49     lukem 		    (fstat(stderrfd, &sb) == 0) && sb.st_size > 0 &&
   1804  1.132     lukem 		    ((errf = fdopen(stderrfd, "r")) != NULL)) {
   1805   1.49     lukem 			char *cp, line[LINE_MAX];
   1806   1.49     lukem 
   1807   1.95     lukem 			reply(-226, "Command error messages:");
   1808  1.132     lukem 			rewind(errf);
   1809  1.132     lukem 			while (fgets(line, sizeof(line), errf) != NULL) {
   1810   1.49     lukem 				if ((cp = strchr(line, '\n')) != NULL)
   1811   1.49     lukem 					*cp = '\0';
   1812   1.95     lukem 				reply(0, "  %s", line);
   1813   1.49     lukem 			}
   1814   1.49     lukem 			(void) fflush(stdout);
   1815  1.132     lukem 			(void) fclose(errf);
   1816   1.49     lukem 				/* a reply(226,) must follow */
   1817   1.49     lukem 		}
   1818   1.49     lukem 		reply(226, "Transfer complete.");
   1819   1.49     lukem 	}
   1820   1.71     lukem  cleanupretrieve:
   1821   1.49     lukem 	if (stderrfd != -1)
   1822   1.49     lukem 		(void)close(stderrfd);
   1823   1.71     lukem 	if (isconversion)
   1824   1.71     lukem 		free(argv);
   1825    1.1       cgd }
   1826    1.1       cgd 
   1827    1.8   deraadt void
   1828  1.132     lukem store(const char *name, const char *fmode, int unique)
   1829    1.1       cgd {
   1830    1.1       cgd 	FILE *fout, *din;
   1831    1.1       cgd 	struct stat st;
   1832   1.88     lukem 	int (*closefunc)(FILE *);
   1833   1.62     lukem 	struct timeval start, finish, td, *tdp;
   1834  1.193     lukem 	const char *desc, *error;
   1835    1.1       cgd 
   1836   1.95     lukem 	din = NULL;
   1837  1.132     lukem 	desc = (*fmode == 'w') ? "put" : "append";
   1838  1.138     lukem 	error = NULL;
   1839    1.1       cgd 	if (unique && stat(name, &st) == 0 &&
   1840    1.8   deraadt 	    (name = gunique(name)) == NULL) {
   1841  1.118     lukem 		logxfer(desc, -1, name, NULL, NULL,
   1842  1.118     lukem 		    "cannot create unique file");
   1843   1.89     lukem 		goto cleanupstore;
   1844    1.8   deraadt 	}
   1845    1.1       cgd 
   1846    1.1       cgd 	if (restart_point)
   1847  1.132     lukem 		fmode = "r+";
   1848  1.132     lukem 	fout = fopen(name, fmode);
   1849    1.1       cgd 	closefunc = fclose;
   1850   1.62     lukem 	tdp = NULL;
   1851    1.1       cgd 	if (fout == NULL) {
   1852    1.1       cgd 		perror_reply(553, name);
   1853  1.118     lukem 		logxfer(desc, -1, name, NULL, NULL, strerror(errno));
   1854   1.89     lukem 		goto cleanupstore;
   1855    1.1       cgd 	}
   1856    1.8   deraadt 	byte_count = -1;
   1857    1.1       cgd 	if (restart_point) {
   1858    1.1       cgd 		if (type == TYPE_A) {
   1859   1.49     lukem 			off_t i;
   1860    1.8   deraadt 			int c;
   1861    1.1       cgd 
   1862   1.49     lukem 			for (i = 0; i < restart_point; i++) {
   1863    1.1       cgd 				if ((c=getc(fout)) == EOF) {
   1864  1.138     lukem 					error = strerror(errno);
   1865    1.1       cgd 					perror_reply(550, name);
   1866    1.1       cgd 					goto done;
   1867    1.1       cgd 				}
   1868    1.1       cgd 				if (c == '\n')
   1869    1.1       cgd 					i++;
   1870    1.8   deraadt 			}
   1871    1.1       cgd 			/*
   1872    1.1       cgd 			 * We must do this seek to "current" position
   1873    1.1       cgd 			 * because we are changing from reading to
   1874    1.1       cgd 			 * writing.
   1875    1.1       cgd 			 */
   1876   1.20     lukem 			if (fseek(fout, 0L, SEEK_CUR) < 0) {
   1877  1.138     lukem 				error = strerror(errno);
   1878    1.1       cgd 				perror_reply(550, name);
   1879    1.1       cgd 				goto done;
   1880    1.1       cgd 			}
   1881   1.31    kleink 		} else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
   1882  1.138     lukem 			error = strerror(errno);
   1883    1.1       cgd 			perror_reply(550, name);
   1884    1.1       cgd 			goto done;
   1885    1.1       cgd 		}
   1886    1.1       cgd 	}
   1887    1.1       cgd 	din = dataconn(name, (off_t)-1, "r");
   1888    1.1       cgd 	if (din == NULL)
   1889    1.1       cgd 		goto done;
   1890   1.62     lukem 	(void)gettimeofday(&start, NULL);
   1891    1.1       cgd 	if (receive_data(din, fout) == 0) {
   1892    1.1       cgd 		if (unique)
   1893    1.1       cgd 			reply(226, "Transfer complete (unique file name:%s).",
   1894    1.1       cgd 			    name);
   1895    1.1       cgd 		else
   1896    1.1       cgd 			reply(226, "Transfer complete.");
   1897    1.1       cgd 	}
   1898   1.62     lukem 	(void)gettimeofday(&finish, NULL);
   1899  1.137     lukem 	closedataconn(din);		/* close now to affect timing stats */
   1900   1.62     lukem 	timersub(&finish, &start, &td);
   1901   1.62     lukem 	tdp = &td;
   1902   1.89     lukem  done:
   1903  1.138     lukem 	logxfer(desc, byte_count, name, NULL, tdp, error);
   1904    1.1       cgd 	(*closefunc)(fout);
   1905   1.89     lukem  cleanupstore:
   1906  1.137     lukem 	;
   1907    1.1       cgd }
   1908    1.1       cgd 
   1909    1.8   deraadt static FILE *
   1910  1.132     lukem getdatasock(const char *fmode)
   1911    1.1       cgd {
   1912  1.101     lukem 	int		on, s, t, tries;
   1913  1.101     lukem 	in_port_t	port;
   1914    1.1       cgd 
   1915  1.101     lukem 	on = 1;
   1916    1.1       cgd 	if (data >= 0)
   1917  1.132     lukem 		return (fdopen(data, fmode));
   1918  1.101     lukem 	if (! dropprivs)
   1919  1.101     lukem 		(void) seteuid((uid_t)0);
   1920   1.67    itojun 	s = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
   1921    1.1       cgd 	if (s < 0)
   1922    1.1       cgd 		goto bad;
   1923    1.1       cgd 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
   1924    1.8   deraadt 	    (char *) &on, sizeof(on)) < 0)
   1925    1.1       cgd 		goto bad;
   1926   1.66    briggs 	if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
   1927   1.66    briggs 	    (char *) &on, sizeof(on)) < 0)
   1928   1.66    briggs 		goto bad;
   1929  1.101     lukem 			/* anchor socket to avoid multi-homing problems */
   1930   1.67    itojun 	data_source = ctrl_addr;
   1931  1.101     lukem 			/*
   1932  1.101     lukem 			 * By default source port for PORT connctions is
   1933  1.101     lukem 			 * ctrlport-1 (see RFC959 section 5.2).
   1934  1.101     lukem 			 * However, if privs have been dropped and that
   1935  1.101     lukem 			 * would be < IPPORT_RESERVED, use a random port
   1936  1.101     lukem 			 * instead.
   1937  1.101     lukem 			 */
   1938  1.111     lukem 	if (dataport)
   1939  1.111     lukem 		port = dataport;
   1940  1.111     lukem 	else
   1941  1.111     lukem 		port = ntohs(ctrl_addr.su_port) - 1;
   1942  1.101     lukem 	if (dropprivs && port < IPPORT_RESERVED)
   1943  1.101     lukem 		port = 0;		/* use random port */
   1944  1.101     lukem 	data_source.su_port = htons(port);
   1945  1.101     lukem 
   1946    1.1       cgd 	for (tries = 1; ; tries++) {
   1947  1.109     lukem 		if (bind(s, (struct sockaddr *)&data_source.si_su,
   1948   1.67    itojun 		    data_source.su_len) >= 0)
   1949    1.1       cgd 			break;
   1950    1.1       cgd 		if (errno != EADDRINUSE || tries > 10)
   1951    1.1       cgd 			goto bad;
   1952    1.1       cgd 		sleep(tries);
   1953    1.1       cgd 	}
   1954  1.101     lukem 	if (! dropprivs)
   1955  1.101     lukem 		(void) seteuid((uid_t)pw->pw_uid);
   1956    1.1       cgd #ifdef IP_TOS
   1957   1.75    itojun 	if (!mapped && ctrl_addr.su_family == AF_INET) {
   1958   1.67    itojun 		on = IPTOS_THROUGHPUT;
   1959   1.67    itojun 		if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on,
   1960   1.67    itojun 			       sizeof(int)) < 0)
   1961   1.67    itojun 			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
   1962   1.67    itojun 	}
   1963    1.1       cgd #endif
   1964  1.132     lukem 	return (fdopen(s, fmode));
   1965   1.89     lukem  bad:
   1966  1.101     lukem 		/* Return the real value of errno (close may change it) */
   1967    1.8   deraadt 	t = errno;
   1968  1.101     lukem 	if (! dropprivs)
   1969  1.101     lukem 		(void) seteuid((uid_t)pw->pw_uid);
   1970  1.203       shm 	if (s >= 0)
   1971  1.203       shm 		(void) close(s);
   1972    1.8   deraadt 	errno = t;
   1973    1.1       cgd 	return (NULL);
   1974    1.1       cgd }
   1975    1.1       cgd 
   1976   1.93     lukem FILE *
   1977  1.132     lukem dataconn(const char *name, off_t size, const char *fmode)
   1978    1.1       cgd {
   1979    1.1       cgd 	char sizebuf[32];
   1980    1.1       cgd 	FILE *file;
   1981  1.150     lukem 	int retry, tos, keepalive, conerrno;
   1982    1.1       cgd 
   1983    1.1       cgd 	file_size = size;
   1984    1.1       cgd 	byte_count = 0;
   1985    1.1       cgd 	if (size != (off_t) -1)
   1986  1.109     lukem 		(void)snprintf(sizebuf, sizeof(sizebuf), " (" LLF " byte%s)",
   1987  1.109     lukem 		    (LLT)size, PLURAL(size));
   1988    1.1       cgd 	else
   1989   1.29       mrg 		sizebuf[0] = '\0';
   1990    1.1       cgd 	if (pdata >= 0) {
   1991  1.109     lukem 		struct sockinet from;
   1992  1.176       mrg 		int s;
   1993  1.176       mrg 		socklen_t fromlen = sizeof(from.su_len);
   1994    1.1       cgd 
   1995   1.42     lukem 		(void) alarm(curclass.timeout);
   1996  1.109     lukem 		s = accept(pdata, (struct sockaddr *)&from.si_su, &fromlen);
   1997   1.42     lukem 		(void) alarm(0);
   1998    1.1       cgd 		if (s < 0) {
   1999    1.1       cgd 			reply(425, "Can't open data connection.");
   2000    1.1       cgd 			(void) close(pdata);
   2001    1.1       cgd 			pdata = -1;
   2002    1.8   deraadt 			return (NULL);
   2003    1.1       cgd 		}
   2004    1.1       cgd 		(void) close(pdata);
   2005    1.1       cgd 		pdata = s;
   2006   1.67    itojun 		switch (from.su_family) {
   2007   1.67    itojun 		case AF_INET:
   2008    1.1       cgd #ifdef IP_TOS
   2009   1.75    itojun 			if (!mapped) {
   2010   1.75    itojun 				tos = IPTOS_THROUGHPUT;
   2011   1.75    itojun 				(void) setsockopt(s, IPPROTO_IP, IP_TOS,
   2012   1.75    itojun 				    (char *)&tos, sizeof(int));
   2013   1.75    itojun 			}
   2014   1.67    itojun 			break;
   2015   1.66    briggs #endif
   2016   1.67    itojun 		}
   2017   1.66    briggs 		/* Set keepalives on the socket to detect dropped conns. */
   2018   1.66    briggs #ifdef SO_KEEPALIVE
   2019   1.66    briggs 		keepalive = 1;
   2020   1.66    briggs 		(void) setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
   2021   1.66    briggs 		    (char *)&keepalive, sizeof(int));
   2022    1.1       cgd #endif
   2023    1.8   deraadt 		reply(150, "Opening %s mode data connection for '%s'%s.",
   2024    1.1       cgd 		     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
   2025  1.132     lukem 		return (fdopen(pdata, fmode));
   2026    1.1       cgd 	}
   2027    1.1       cgd 	if (data >= 0) {
   2028    1.8   deraadt 		reply(125, "Using existing data connection for '%s'%s.",
   2029    1.1       cgd 		    name, sizebuf);
   2030    1.1       cgd 		usedefault = 1;
   2031  1.132     lukem 		return (fdopen(data, fmode));
   2032    1.1       cgd 	}
   2033    1.1       cgd 	if (usedefault)
   2034    1.1       cgd 		data_dest = his_addr;
   2035    1.1       cgd 	usedefault = 1;
   2036  1.150     lukem 	retry = conerrno = 0;
   2037  1.150     lukem 	do {
   2038  1.150     lukem 		file = getdatasock(fmode);
   2039  1.150     lukem 		if (file == NULL) {
   2040  1.150     lukem 			char hbuf[NI_MAXHOST];
   2041  1.150     lukem 			char pbuf[NI_MAXSERV];
   2042  1.150     lukem 
   2043  1.150     lukem 			if (getnameinfo((struct sockaddr *)&data_source.si_su,
   2044  1.150     lukem 			    data_source.su_len, hbuf, sizeof(hbuf), pbuf,
   2045  1.150     lukem 			    sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV))
   2046  1.150     lukem 				strlcpy(hbuf, "?", sizeof(hbuf));
   2047  1.150     lukem 			reply(425, "Can't create data socket (%s,%s): %s.",
   2048  1.150     lukem 			      hbuf, pbuf, strerror(errno));
   2049  1.150     lukem 			return (NULL);
   2050  1.150     lukem 		}
   2051  1.150     lukem 		data = fileno(file);
   2052  1.150     lukem 		conerrno = 0;
   2053  1.150     lukem 		if (connect(data, (struct sockaddr *)&data_dest.si_su,
   2054  1.150     lukem 		    data_dest.su_len) == 0)
   2055  1.150     lukem 			break;
   2056  1.150     lukem 		conerrno = errno;
   2057  1.150     lukem 		(void) fclose(file);
   2058  1.174     peter 		file = NULL;
   2059  1.150     lukem 		data = -1;
   2060  1.150     lukem 		if (conerrno == EADDRINUSE) {
   2061    1.1       cgd 			sleep((unsigned) swaitint);
   2062    1.1       cgd 			retry += swaitint;
   2063  1.150     lukem 		} else {
   2064  1.150     lukem 			break;
   2065    1.1       cgd 		}
   2066  1.150     lukem 	} while (retry <= swaitmax);
   2067  1.150     lukem 	if (conerrno != 0) {
   2068    1.1       cgd 		perror_reply(425, "Can't build data connection");
   2069    1.1       cgd 		return (NULL);
   2070    1.1       cgd 	}
   2071    1.8   deraadt 	reply(150, "Opening %s mode data connection for '%s'%s.",
   2072    1.1       cgd 	     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
   2073    1.1       cgd 	return (file);
   2074    1.1       cgd }
   2075    1.1       cgd 
   2076   1.95     lukem void
   2077   1.95     lukem closedataconn(FILE *fd)
   2078   1.95     lukem {
   2079   1.95     lukem 
   2080  1.136     lukem 	if (fd == NULL)
   2081  1.136     lukem 		return;
   2082  1.136     lukem 	(void)fclose(fd);
   2083   1.95     lukem 	data = -1;
   2084   1.95     lukem 	if (pdata >= 0)
   2085   1.95     lukem 		(void)close(pdata);
   2086   1.95     lukem 	pdata = -1;
   2087   1.95     lukem }
   2088   1.95     lukem 
   2089  1.139     enami int
   2090  1.139     enami write_data(int fd, char *buf, size_t size, off_t *bufrem,
   2091  1.139     enami     struct timeval *then, int isdata)
   2092  1.139     enami {
   2093  1.139     enami 	struct timeval now, td;
   2094  1.139     enami 	ssize_t c;
   2095  1.139     enami 
   2096  1.139     enami 	while (size > 0) {
   2097  1.139     enami 		c = size;
   2098  1.139     enami 		if (curclass.writesize) {
   2099  1.139     enami 			if (curclass.writesize < c)
   2100  1.139     enami 				c = curclass.writesize;
   2101  1.139     enami 		}
   2102  1.139     enami 		if (curclass.rateget) {
   2103  1.139     enami 			if (*bufrem < c)
   2104  1.139     enami 				c = *bufrem;
   2105  1.139     enami 		}
   2106  1.139     enami 		(void) alarm(curclass.timeout);
   2107  1.139     enami 		c = write(fd, buf, c);
   2108  1.139     enami 		if (c <= 0)
   2109  1.139     enami 			return (1);
   2110  1.139     enami 		buf += c;
   2111  1.139     enami 		size -= c;
   2112  1.139     enami 		byte_count += c;
   2113  1.139     enami 		if (isdata) {
   2114  1.139     enami 			total_data_out += c;
   2115  1.139     enami 			total_data += c;
   2116  1.139     enami 		}
   2117  1.139     enami 		total_bytes_out += c;
   2118  1.139     enami 		total_bytes += c;
   2119  1.139     enami 		if (curclass.rateget) {
   2120  1.139     enami 			*bufrem -= c;
   2121  1.139     enami 			if (*bufrem == 0) {
   2122  1.139     enami 				(void)gettimeofday(&now, NULL);
   2123  1.139     enami 				timersub(&now, then, &td);
   2124  1.139     enami 				if (td.tv_sec == 0) {
   2125  1.139     enami 					usleep(1000000 - td.tv_usec);
   2126  1.139     enami 					(void)gettimeofday(then, NULL);
   2127  1.139     enami 				} else
   2128  1.139     enami 					*then = now;
   2129  1.139     enami 				*bufrem = curclass.rateget;
   2130  1.139     enami 			}
   2131  1.139     enami 		}
   2132  1.139     enami 	}
   2133  1.139     enami 	return (0);
   2134  1.139     enami }
   2135  1.139     enami 
   2136  1.139     enami static enum send_status
   2137  1.139     enami send_data_with_read(int filefd, int netfd, const struct stat *st, int isdata)
   2138  1.139     enami {
   2139  1.139     enami 	struct timeval then;
   2140  1.139     enami 	off_t bufrem;
   2141  1.193     lukem 	ssize_t readsize;
   2142  1.139     enami 	char *buf;
   2143  1.139     enami 	int c, error;
   2144  1.139     enami 
   2145  1.193     lukem 	if (curclass.readsize > 0)
   2146  1.139     enami 		readsize = curclass.readsize;
   2147  1.139     enami 	else
   2148  1.193     lukem 		readsize = st->st_blksize;
   2149  1.139     enami 	if ((buf = malloc(readsize)) == NULL) {
   2150  1.139     enami 		perror_reply(451, "Local resource failure: malloc");
   2151  1.139     enami 		return (SS_NO_TRANSFER);
   2152  1.139     enami 	}
   2153  1.139     enami 
   2154  1.139     enami 	if (curclass.rateget) {
   2155  1.139     enami 		bufrem = curclass.rateget;
   2156  1.139     enami 		(void)gettimeofday(&then, NULL);
   2157  1.193     lukem 	} else
   2158  1.193     lukem 		bufrem = readsize;
   2159  1.200  christos 	for (;;) {
   2160  1.139     enami 		(void) alarm(curclass.timeout);
   2161  1.139     enami 		c = read(filefd, buf, readsize);
   2162  1.139     enami 		if (c == 0)
   2163  1.139     enami 			error = SS_SUCCESS;
   2164  1.139     enami 		else if (c < 0)
   2165  1.139     enami 			error = SS_FILE_ERROR;
   2166  1.139     enami 		else if (write_data(netfd, buf, c, &bufrem, &then, isdata))
   2167  1.139     enami 			error = SS_DATA_ERROR;
   2168  1.158     lukem 		else if (urgflag && handleoobcmd())
   2169  1.158     lukem 			error = SS_ABORTED;
   2170  1.139     enami 		else
   2171  1.139     enami 			continue;
   2172  1.139     enami 
   2173  1.139     enami 		free(buf);
   2174  1.139     enami 		return (error);
   2175  1.139     enami 	}
   2176  1.139     enami }
   2177  1.139     enami 
   2178  1.139     enami static enum send_status
   2179  1.139     enami send_data_with_mmap(int filefd, int netfd, const struct stat *st, int isdata)
   2180  1.139     enami {
   2181  1.139     enami 	struct timeval then;
   2182  1.139     enami 	off_t bufrem, filesize, off, origoff;
   2183  1.193     lukem 	ssize_t mapsize, winsize;
   2184  1.139     enami 	int error, sendbufsize, sendlowat;
   2185  1.139     enami 	void *win;
   2186  1.139     enami 
   2187  1.193     lukem 	bufrem = 0;
   2188  1.139     enami 	if (curclass.sendbufsize) {
   2189  1.139     enami 		sendbufsize = curclass.sendbufsize;
   2190  1.139     enami 		if (setsockopt(netfd, SOL_SOCKET, SO_SNDBUF,
   2191  1.139     enami 		    &sendbufsize, sizeof(int)) == -1)
   2192  1.139     enami 			syslog(LOG_WARNING, "setsockopt(SO_SNDBUF, %d): %m",
   2193  1.139     enami 			    sendbufsize);
   2194  1.139     enami 	}
   2195  1.139     enami 
   2196  1.139     enami 	if (curclass.sendlowat) {
   2197  1.139     enami 		sendlowat = curclass.sendlowat;
   2198  1.139     enami 		if (setsockopt(netfd, SOL_SOCKET, SO_SNDLOWAT,
   2199  1.139     enami 		    &sendlowat, sizeof(int)) == -1)
   2200  1.139     enami 			syslog(LOG_WARNING, "setsockopt(SO_SNDLOWAT, %d): %m",
   2201  1.139     enami 			    sendlowat);
   2202  1.139     enami 	}
   2203  1.139     enami 
   2204  1.139     enami 	winsize = curclass.mmapsize;
   2205  1.139     enami 	filesize = st->st_size;
   2206  1.171  christos 	if (ftpd_debug)
   2207  1.193     lukem 		syslog(LOG_INFO, "mmapsize = " LLF ", writesize = " LLF,
   2208  1.193     lukem 		    (LLT)winsize, (LLT)curclass.writesize);
   2209  1.193     lukem 	if (winsize <= 0)
   2210  1.139     enami 		goto try_read;
   2211  1.139     enami 
   2212  1.139     enami 	off = lseek(filefd, (off_t)0, SEEK_CUR);
   2213  1.139     enami 	if (off == -1)
   2214  1.139     enami 		goto try_read;
   2215  1.139     enami 
   2216  1.139     enami 	origoff = off;
   2217  1.139     enami 	if (curclass.rateget) {
   2218  1.139     enami 		bufrem = curclass.rateget;
   2219  1.139     enami 		(void)gettimeofday(&then, NULL);
   2220  1.193     lukem 	} else
   2221  1.193     lukem 		bufrem = winsize;
   2222  1.139     enami 	while (1) {
   2223  1.139     enami 		mapsize = MIN(filesize - off, winsize);
   2224  1.139     enami 		if (mapsize == 0)
   2225  1.139     enami 			break;
   2226  1.139     enami 		win = mmap(NULL, mapsize, PROT_READ,
   2227  1.139     enami 		    MAP_FILE|MAP_SHARED, filefd, off);
   2228  1.139     enami 		if (win == MAP_FAILED) {
   2229  1.139     enami 			if (off == origoff)
   2230  1.139     enami 				goto try_read;
   2231  1.139     enami 			return (SS_FILE_ERROR);
   2232  1.139     enami 		}
   2233  1.139     enami 		(void) madvise(win, mapsize, MADV_SEQUENTIAL);
   2234  1.139     enami 		error = write_data(netfd, win, mapsize, &bufrem, &then,
   2235  1.139     enami 		    isdata);
   2236  1.139     enami 		(void) madvise(win, mapsize, MADV_DONTNEED);
   2237  1.139     enami 		munmap(win, mapsize);
   2238  1.158     lukem 		if (urgflag && handleoobcmd())
   2239  1.158     lukem 			return (SS_ABORTED);
   2240  1.139     enami 		if (error)
   2241  1.139     enami 			return (SS_DATA_ERROR);
   2242  1.139     enami 		off += mapsize;
   2243  1.139     enami 	}
   2244  1.139     enami 	return (SS_SUCCESS);
   2245  1.139     enami 
   2246  1.139     enami  try_read:
   2247  1.139     enami 	return (send_data_with_read(filefd, netfd, st, isdata));
   2248  1.139     enami }
   2249  1.139     enami 
   2250    1.1       cgd /*
   2251  1.183     lukem  * Transfer the contents of "instr" to "outstr" peer using the appropriate
   2252  1.139     enami  * encapsulation of the data subject to Mode, Structure, and Type.
   2253    1.1       cgd  *
   2254    1.1       cgd  * NB: Form isn't handled.
   2255    1.1       cgd  */
   2256   1.49     lukem static int
   2257  1.139     enami send_data(FILE *instr, FILE *outstr, const struct stat *st, int isdata)
   2258    1.1       cgd {
   2259   1.73     lukem 	int	 c, filefd, netfd, rval;
   2260    1.1       cgd 
   2261  1.158     lukem 	urgflag = 0;
   2262   1.62     lukem 	transflag = 1;
   2263   1.62     lukem 	rval = -1;
   2264   1.24     lukem 
   2265    1.1       cgd 	switch (type) {
   2266    1.1       cgd 
   2267    1.1       cgd 	case TYPE_A:
   2268  1.109     lukem  /* XXXLUKEM: rate limit ascii send (get) */
   2269   1.62     lukem 		(void) alarm(curclass.timeout);
   2270    1.1       cgd 		while ((c = getc(instr)) != EOF) {
   2271  1.158     lukem 			if (urgflag && handleoobcmd())
   2272  1.158     lukem 				goto cleanup_send_data;
   2273    1.1       cgd 			byte_count++;
   2274   1.63     lukem 			if (c == '\n') {
   2275   1.63     lukem 				if (ferror(outstr))
   2276   1.63     lukem 					goto data_err;
   2277   1.63     lukem 				(void) putc('\r', outstr);
   2278   1.63     lukem 				if (isdata) {
   2279   1.63     lukem 					total_data_out++;
   2280   1.63     lukem 					total_data++;
   2281   1.63     lukem 				}
   2282   1.63     lukem 				total_bytes_out++;
   2283   1.63     lukem 				total_bytes++;
   2284   1.63     lukem 			}
   2285   1.63     lukem 			(void) putc(c, outstr);
   2286   1.62     lukem 			if (isdata) {
   2287   1.62     lukem 				total_data_out++;
   2288   1.62     lukem 				total_data++;
   2289   1.62     lukem 			}
   2290   1.62     lukem 			total_bytes_out++;
   2291   1.62     lukem 			total_bytes++;
   2292   1.62     lukem 			if ((byte_count % 4096) == 0)
   2293   1.62     lukem 				(void) alarm(curclass.timeout);
   2294    1.1       cgd 		}
   2295   1.62     lukem 		(void) alarm(0);
   2296    1.1       cgd 		fflush(outstr);
   2297    1.1       cgd 		if (ferror(instr))
   2298    1.1       cgd 			goto file_err;
   2299    1.1       cgd 		if (ferror(outstr))
   2300    1.1       cgd 			goto data_err;
   2301   1.62     lukem 		rval = 0;
   2302   1.62     lukem 		goto cleanup_send_data;
   2303    1.1       cgd 
   2304    1.1       cgd 	case TYPE_I:
   2305    1.1       cgd 	case TYPE_L:
   2306   1.63     lukem 		filefd = fileno(instr);
   2307    1.1       cgd 		netfd = fileno(outstr);
   2308  1.139     enami 		switch (send_data_with_mmap(filefd, netfd, st, isdata)) {
   2309  1.139     enami 
   2310  1.139     enami 		case SS_SUCCESS:
   2311  1.139     enami 			break;
   2312  1.139     enami 
   2313  1.158     lukem 		case SS_ABORTED:
   2314  1.139     enami 		case SS_NO_TRANSFER:
   2315  1.139     enami 			goto cleanup_send_data;
   2316  1.139     enami 
   2317  1.139     enami 		case SS_FILE_ERROR:
   2318  1.139     enami 			goto file_err;
   2319   1.73     lukem 
   2320  1.139     enami 		case SS_DATA_ERROR:
   2321  1.139     enami 			goto data_err;
   2322    1.1       cgd 		}
   2323   1.62     lukem 		rval = 0;
   2324   1.62     lukem 		goto cleanup_send_data;
   2325   1.62     lukem 
   2326    1.1       cgd 	default:
   2327    1.1       cgd 		reply(550, "Unimplemented TYPE %d in send_data", type);
   2328   1.62     lukem 		goto cleanup_send_data;
   2329    1.1       cgd 	}
   2330    1.1       cgd 
   2331   1.89     lukem  data_err:
   2332   1.62     lukem 	(void) alarm(0);
   2333    1.1       cgd 	perror_reply(426, "Data connection");
   2334   1.62     lukem 	goto cleanup_send_data;
   2335    1.1       cgd 
   2336   1.89     lukem  file_err:
   2337   1.62     lukem 	(void) alarm(0);
   2338   1.62     lukem 	perror_reply(551, "Error on input file");
   2339  1.158     lukem 	goto cleanup_send_data;
   2340   1.73     lukem 
   2341   1.89     lukem  cleanup_send_data:
   2342   1.62     lukem 	(void) alarm(0);
   2343    1.1       cgd 	transflag = 0;
   2344  1.158     lukem 	urgflag = 0;
   2345   1.62     lukem 	if (isdata) {
   2346   1.62     lukem 		total_files_out++;
   2347   1.62     lukem 		total_files++;
   2348   1.62     lukem 	}
   2349   1.62     lukem 	total_xfers_out++;
   2350   1.62     lukem 	total_xfers++;
   2351   1.62     lukem 	return (rval);
   2352    1.1       cgd }
   2353    1.1       cgd 
   2354    1.1       cgd /*
   2355    1.8   deraadt  * Transfer data from peer to "outstr" using the appropriate encapulation of
   2356    1.8   deraadt  * the data subject to Mode, Structure, and Type.
   2357    1.1       cgd  *
   2358    1.1       cgd  * N.B.: Form isn't handled.
   2359    1.1       cgd  */
   2360    1.8   deraadt static int
   2361   1.88     lukem receive_data(FILE *instr, FILE *outstr)
   2362    1.1       cgd {
   2363  1.178  christos 	int	c, netfd, filefd, rval;
   2364  1.178  christos 	int	volatile bare_lfs;
   2365  1.111     lukem 	off_t	byteswritten;
   2366  1.168  ginsbach 	char	*buf;
   2367  1.193     lukem 	ssize_t	readsize;
   2368  1.158     lukem 	struct sigaction sa, sa_saved;
   2369  1.168  ginsbach 	struct stat st;
   2370    1.1       cgd 
   2371  1.158     lukem 	memset(&sa, 0, sizeof(sa));
   2372  1.158     lukem 	sigfillset(&sa.sa_mask);
   2373  1.158     lukem 	sa.sa_flags = SA_RESTART;
   2374  1.158     lukem 	sa.sa_handler = lostconn;
   2375  1.158     lukem 	(void) sigaction(SIGALRM, &sa, &sa_saved);
   2376  1.158     lukem 
   2377   1.24     lukem 	bare_lfs = 0;
   2378  1.158     lukem 	urgflag = 0;
   2379   1.62     lukem 	transflag = 1;
   2380   1.62     lukem 	rval = -1;
   2381  1.111     lukem 	byteswritten = 0;
   2382  1.168  ginsbach 	buf = NULL;
   2383   1.24     lukem 
   2384  1.111     lukem #define FILESIZECHECK(x) \
   2385  1.111     lukem 			do { \
   2386  1.111     lukem 				if (curclass.maxfilesize != -1 && \
   2387  1.111     lukem 				    (x) > curclass.maxfilesize) { \
   2388  1.111     lukem 					errno = EFBIG; \
   2389  1.111     lukem 					goto file_err; \
   2390  1.111     lukem 				} \
   2391  1.111     lukem 			} while (0)
   2392  1.111     lukem 
   2393    1.1       cgd 	switch (type) {
   2394    1.1       cgd 
   2395    1.1       cgd 	case TYPE_I:
   2396    1.1       cgd 	case TYPE_L:
   2397   1.62     lukem 		netfd = fileno(instr);
   2398   1.62     lukem 		filefd = fileno(outstr);
   2399   1.62     lukem 		(void) alarm(curclass.timeout);
   2400  1.168  ginsbach 		if (curclass.readsize)
   2401  1.168  ginsbach 			readsize = curclass.readsize;
   2402  1.200  christos 		else if (fstat(filefd, &st) != -1)
   2403  1.193     lukem 			readsize = (ssize_t)st.st_blksize;
   2404  1.168  ginsbach 		else
   2405  1.168  ginsbach 			readsize = BUFSIZ;
   2406  1.168  ginsbach 		if ((buf = malloc(readsize)) == NULL) {
   2407  1.168  ginsbach 			perror_reply(451, "Local resource failure: malloc");
   2408  1.168  ginsbach 			goto cleanup_recv_data;
   2409  1.168  ginsbach 		}
   2410   1.73     lukem 		if (curclass.rateput) {
   2411   1.73     lukem 			while (1) {
   2412   1.73     lukem 				int d;
   2413   1.73     lukem 				struct timeval then, now, td;
   2414   1.73     lukem 				off_t bufrem;
   2415   1.73     lukem 
   2416   1.73     lukem 				(void)gettimeofday(&then, NULL);
   2417   1.73     lukem 				errno = c = d = 0;
   2418   1.73     lukem 				for (bufrem = curclass.rateput; bufrem > 0; ) {
   2419   1.73     lukem 					if ((c = read(netfd, buf,
   2420  1.168  ginsbach 					    MIN(readsize, bufrem))) <= 0)
   2421   1.73     lukem 						goto recvdone;
   2422  1.158     lukem 					if (urgflag && handleoobcmd())
   2423  1.158     lukem 						goto cleanup_recv_data;
   2424  1.111     lukem 					FILESIZECHECK(byte_count + c);
   2425   1.73     lukem 					if ((d = write(filefd, buf, c)) != c)
   2426  1.111     lukem 						goto file_err;
   2427   1.73     lukem 					(void) alarm(curclass.timeout);
   2428   1.73     lukem 					bufrem -= c;
   2429   1.73     lukem 					byte_count += c;
   2430   1.73     lukem 					total_data_in += c;
   2431   1.73     lukem 					total_data += c;
   2432   1.73     lukem 					total_bytes_in += c;
   2433   1.73     lukem 					total_bytes += c;
   2434   1.73     lukem 				}
   2435   1.73     lukem 				(void)gettimeofday(&now, NULL);
   2436   1.73     lukem 				timersub(&now, &then, &td);
   2437   1.96     lukem 				if (td.tv_sec == 0)
   2438   1.96     lukem 					usleep(1000000 - td.tv_usec);
   2439   1.73     lukem 			}
   2440   1.73     lukem 		} else {
   2441  1.168  ginsbach 			while ((c = read(netfd, buf, readsize)) > 0) {
   2442  1.158     lukem 				if (urgflag && handleoobcmd())
   2443  1.158     lukem 					goto cleanup_recv_data;
   2444  1.111     lukem 				FILESIZECHECK(byte_count + c);
   2445   1.73     lukem 				if (write(filefd, buf, c) != c)
   2446   1.73     lukem 					goto file_err;
   2447   1.73     lukem 				(void) alarm(curclass.timeout);
   2448   1.73     lukem 				byte_count += c;
   2449   1.73     lukem 				total_data_in += c;
   2450   1.73     lukem 				total_data += c;
   2451   1.73     lukem 				total_bytes_in += c;
   2452   1.73     lukem 				total_bytes += c;
   2453   1.73     lukem 			}
   2454    1.1       cgd 		}
   2455   1.73     lukem  recvdone:
   2456   1.73     lukem 		if (c < 0)
   2457    1.1       cgd 			goto data_err;
   2458   1.62     lukem 		rval = 0;
   2459   1.62     lukem 		goto cleanup_recv_data;
   2460    1.1       cgd 
   2461    1.1       cgd 	case TYPE_E:
   2462    1.1       cgd 		reply(553, "TYPE E not implemented.");
   2463   1.62     lukem 		goto cleanup_recv_data;
   2464    1.1       cgd 
   2465    1.1       cgd 	case TYPE_A:
   2466   1.62     lukem 		(void) alarm(curclass.timeout);
   2467  1.109     lukem  /* XXXLUKEM: rate limit ascii receive (put) */
   2468    1.1       cgd 		while ((c = getc(instr)) != EOF) {
   2469  1.158     lukem 			if (urgflag && handleoobcmd())
   2470  1.158     lukem 				goto cleanup_recv_data;
   2471    1.1       cgd 			byte_count++;
   2472   1.62     lukem 			total_data_in++;
   2473   1.62     lukem 			total_data++;
   2474   1.62     lukem 			total_bytes_in++;
   2475   1.62     lukem 			total_bytes++;
   2476   1.62     lukem 			if ((byte_count % 4096) == 0)
   2477   1.62     lukem 				(void) alarm(curclass.timeout);
   2478    1.1       cgd 			if (c == '\n')
   2479    1.1       cgd 				bare_lfs++;
   2480    1.1       cgd 			while (c == '\r') {
   2481    1.1       cgd 				if (ferror(outstr))
   2482    1.1       cgd 					goto data_err;
   2483    1.1       cgd 				if ((c = getc(instr)) != '\n') {
   2484   1.62     lukem 					byte_count++;
   2485   1.62     lukem 					total_data_in++;
   2486   1.62     lukem 					total_data++;
   2487   1.62     lukem 					total_bytes_in++;
   2488   1.62     lukem 					total_bytes++;
   2489   1.62     lukem 					if ((byte_count % 4096) == 0)
   2490   1.62     lukem 						(void) alarm(curclass.timeout);
   2491  1.111     lukem 					byteswritten++;
   2492  1.111     lukem 					FILESIZECHECK(byteswritten);
   2493    1.1       cgd 					(void) putc ('\r', outstr);
   2494    1.1       cgd 					if (c == '\0' || c == EOF)
   2495    1.1       cgd 						goto contin2;
   2496    1.1       cgd 				}
   2497    1.1       cgd 			}
   2498  1.111     lukem 			byteswritten++;
   2499  1.111     lukem 			FILESIZECHECK(byteswritten);
   2500    1.1       cgd 			(void) putc(c, outstr);
   2501  1.111     lukem  contin2:	;
   2502    1.1       cgd 		}
   2503   1.62     lukem 		(void) alarm(0);
   2504    1.1       cgd 		fflush(outstr);
   2505    1.1       cgd 		if (ferror(instr))
   2506    1.1       cgd 			goto data_err;
   2507    1.1       cgd 		if (ferror(outstr))
   2508    1.1       cgd 			goto file_err;
   2509    1.1       cgd 		if (bare_lfs) {
   2510   1.95     lukem 			reply(-226,
   2511   1.62     lukem 			    "WARNING! %d bare linefeeds received in ASCII mode",
   2512    1.8   deraadt 			    bare_lfs);
   2513   1.95     lukem 			reply(0, "File may not have transferred correctly.");
   2514    1.1       cgd 		}
   2515   1.62     lukem 		rval = 0;
   2516   1.62     lukem 		goto cleanup_recv_data;
   2517   1.62     lukem 
   2518    1.1       cgd 	default:
   2519    1.1       cgd 		reply(550, "Unimplemented TYPE %d in receive_data", type);
   2520   1.62     lukem 		goto cleanup_recv_data;
   2521    1.1       cgd 	}
   2522  1.120       cgd #undef FILESIZECHECK
   2523    1.1       cgd 
   2524   1.89     lukem  data_err:
   2525   1.62     lukem 	(void) alarm(0);
   2526    1.1       cgd 	perror_reply(426, "Data Connection");
   2527   1.62     lukem 	goto cleanup_recv_data;
   2528    1.1       cgd 
   2529   1.89     lukem  file_err:
   2530   1.62     lukem 	(void) alarm(0);
   2531   1.62     lukem 	perror_reply(452, "Error writing file");
   2532   1.62     lukem 	goto cleanup_recv_data;
   2533   1.62     lukem 
   2534   1.89     lukem  cleanup_recv_data:
   2535   1.62     lukem 	(void) alarm(0);
   2536  1.158     lukem 	(void) sigaction(SIGALRM, &sa_saved, NULL);
   2537  1.168  ginsbach 	if (buf)
   2538  1.168  ginsbach 		free(buf);
   2539    1.1       cgd 	transflag = 0;
   2540  1.158     lukem 	urgflag = 0;
   2541   1.62     lukem 	total_files_in++;
   2542   1.62     lukem 	total_files++;
   2543   1.62     lukem 	total_xfers_in++;
   2544   1.62     lukem 	total_xfers++;
   2545   1.62     lukem 	return (rval);
   2546    1.1       cgd }
   2547    1.1       cgd 
   2548    1.8   deraadt void
   2549   1.88     lukem statcmd(void)
   2550    1.1       cgd {
   2551  1.109     lukem 	struct sockinet *su = NULL;
   2552  1.112    itojun 	static char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
   2553  1.185     lukem 	unsigned char *a, *p;
   2554   1.89     lukem 	int ispassive, af;
   2555   1.93     lukem 	off_t otbi, otbo, otb;
   2556    1.1       cgd 
   2557  1.197    plunky 	a = p = NULL;
   2558   1.67    itojun 
   2559   1.95     lukem 	reply(-211, "%s FTP server status:", hostname);
   2560  1.101     lukem 	reply(0, "Version: %s", EMPTYSTR(version) ? "<suppressed>" : version);
   2561  1.112    itojun 	hbuf[0] = '\0';
   2562  1.109     lukem 	if (!getnameinfo((struct sockaddr *)&his_addr.si_su, his_addr.su_len,
   2563  1.112    itojun 			hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST)
   2564  1.112    itojun 	    && strcmp(remotehost, hbuf) != 0)
   2565  1.112    itojun 		reply(0, "Connected to %s (%s)", remotehost, hbuf);
   2566  1.104  christos 	else
   2567   1.95     lukem 		reply(0, "Connected to %s", remotehost);
   2568  1.104  christos 
   2569    1.1       cgd 	if (logged_in) {
   2570   1.73     lukem 		if (curclass.type == CLASS_GUEST)
   2571   1.95     lukem 			reply(0, "Logged in anonymously");
   2572    1.1       cgd 		else
   2573   1.95     lukem 			reply(0, "Logged in as %s%s", pw->pw_name,
   2574   1.73     lukem 			    curclass.type == CLASS_CHROOT ? " (chroot)" : "");
   2575    1.1       cgd 	} else if (askpasswd)
   2576   1.95     lukem 		reply(0, "Waiting for password");
   2577    1.1       cgd 	else
   2578   1.95     lukem 		reply(0, "Waiting for user name");
   2579   1.95     lukem 	cprintf(stdout, "    TYPE: %s", typenames[type]);
   2580   1.93     lukem 	if (type == TYPE_A || type == TYPE_E)
   2581   1.95     lukem 		cprintf(stdout, ", FORM: %s", formnames[form]);
   2582   1.62     lukem 	if (type == TYPE_L) {
   2583    1.1       cgd #if NBBY == 8
   2584   1.95     lukem 		cprintf(stdout, " %d", NBBY);
   2585    1.1       cgd #else
   2586   1.62     lukem 			/* XXX: `bytesize' needs to be defined in this case */
   2587   1.95     lukem 		cprintf(stdout, " %d", bytesize);
   2588    1.1       cgd #endif
   2589   1.62     lukem 	}
   2590   1.95     lukem 	cprintf(stdout, "; STRUcture: %s; transfer MODE: %s\r\n",
   2591    1.1       cgd 	    strunames[stru], modenames[mode]);
   2592   1.67    itojun 	ispassive = 0;
   2593   1.67    itojun 	if (data != -1) {
   2594  1.147     lukem 		reply(0, "Data connection open");
   2595   1.67    itojun 		su = NULL;
   2596   1.67    itojun 	} else if (pdata != -1) {
   2597   1.95     lukem 		reply(0, "in Passive mode");
   2598  1.118     lukem 		if (curclass.advertise.su_len != 0)
   2599  1.118     lukem 			su = &curclass.advertise;
   2600  1.118     lukem 		else
   2601  1.118     lukem 			su = &pasv_addr;
   2602   1.67    itojun 		ispassive = 1;
   2603    1.1       cgd 		goto printaddr;
   2604    1.1       cgd 	} else if (usedefault == 0) {
   2605  1.173     peter 		su = (struct sockinet *)&data_dest;
   2606  1.173     peter 
   2607   1.67    itojun 		if (epsvall) {
   2608   1.95     lukem 			reply(0, "EPSV only mode (EPSV ALL)");
   2609   1.67    itojun 			goto epsvonly;
   2610   1.67    itojun 		}
   2611   1.89     lukem  printaddr:
   2612   1.93     lukem 							/* PASV/PORT */
   2613   1.67    itojun 		if (su->su_family == AF_INET) {
   2614  1.185     lukem 			a = (unsigned char *) &su->su_addr;
   2615  1.185     lukem 			p = (unsigned char *) &su->su_port;
   2616    1.1       cgd #define UC(b) (((int) b) & 0xff)
   2617   1.95     lukem 			reply(0, "%s (%d,%d,%d,%d,%d,%d)",
   2618   1.93     lukem 				ispassive ? "PASV" : "PORT" ,
   2619   1.67    itojun 				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
   2620   1.67    itojun 				UC(p[0]), UC(p[1]));
   2621   1.67    itojun 		}
   2622   1.67    itojun 
   2623   1.93     lukem 							/* LPSV/LPRT */
   2624   1.67    itojun 	    {
   2625  1.132     lukem 		int alen, i;
   2626   1.67    itojun 
   2627   1.67    itojun 		alen = 0;
   2628   1.67    itojun 		switch (su->su_family) {
   2629   1.67    itojun 		case AF_INET:
   2630  1.185     lukem 			a = (unsigned char *) &su->su_addr;
   2631  1.185     lukem 			p = (unsigned char *) &su->su_port;
   2632  1.109     lukem 			alen = sizeof(su->su_addr);
   2633   1.67    itojun 			af = 4;
   2634   1.67    itojun 			break;
   2635  1.104  christos #ifdef INET6
   2636   1.67    itojun 		case AF_INET6:
   2637  1.185     lukem 			a = (unsigned char *) &su->su_6addr;
   2638  1.185     lukem 			p = (unsigned char *) &su->su_port;
   2639  1.109     lukem 			alen = sizeof(su->su_6addr);
   2640   1.67    itojun 			af = 6;
   2641   1.67    itojun 			break;
   2642  1.104  christos #endif
   2643   1.67    itojun 		default:
   2644   1.67    itojun 			af = 0;
   2645   1.67    itojun 			break;
   2646   1.67    itojun 		}
   2647   1.67    itojun 		if (af) {
   2648   1.95     lukem 			cprintf(stdout, "    %s (%d,%d",
   2649   1.93     lukem 			    ispassive ? "LPSV" : "LPRT", af, alen);
   2650   1.67    itojun 			for (i = 0; i < alen; i++)
   2651   1.95     lukem 				cprintf(stdout, ",%d", UC(a[i]));
   2652  1.112    itojun 			cprintf(stdout, ",%d,%d,%d)\r\n",
   2653  1.112    itojun 			    2, UC(p[0]), UC(p[1]));
   2654    1.1       cgd #undef UC
   2655   1.67    itojun 		}
   2656   1.67    itojun 	    }
   2657   1.67    itojun 
   2658   1.67    itojun 		/* EPRT/EPSV */
   2659   1.89     lukem  epsvonly:
   2660  1.109     lukem 		af = af2epsvproto(su->su_family);
   2661  1.112    itojun 		hbuf[0] = '\0';
   2662  1.109     lukem 		if (af > 0) {
   2663  1.112    itojun 			struct sockinet tmp;
   2664  1.112    itojun 
   2665  1.112    itojun 			tmp = *su;
   2666  1.113     lukem #ifdef INET6
   2667  1.112    itojun 			if (tmp.su_family == AF_INET6)
   2668  1.112    itojun 				tmp.su_scope_id = 0;
   2669  1.113     lukem #endif
   2670  1.112    itojun 			if (getnameinfo((struct sockaddr *)&tmp.si_su,
   2671  1.112    itojun 			    tmp.su_len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
   2672  1.112    itojun 			    NI_NUMERICHOST | NI_NUMERICSERV) == 0)
   2673  1.112    itojun 				reply(0, "%s (|%d|%s|%s|)",
   2674   1.93     lukem 				    ispassive ? "EPSV" : "EPRT",
   2675  1.112    itojun 				    af, hbuf, sbuf);
   2676   1.67    itojun 		}
   2677    1.1       cgd 	} else
   2678   1.95     lukem 		reply(0, "No data connection");
   2679   1.62     lukem 
   2680   1.62     lukem 	if (logged_in) {
   2681  1.109     lukem 		reply(0,
   2682  1.109     lukem 		    "Data sent:        " LLF " byte%s in " LLF " file%s",
   2683  1.109     lukem 		    (LLT)total_data_out, PLURAL(total_data_out),
   2684  1.109     lukem 		    (LLT)total_files_out, PLURAL(total_files_out));
   2685  1.109     lukem 		reply(0,
   2686  1.109     lukem 		    "Data received:    " LLF " byte%s in " LLF " file%s",
   2687  1.109     lukem 		    (LLT)total_data_in, PLURAL(total_data_in),
   2688  1.109     lukem 		    (LLT)total_files_in, PLURAL(total_files_in));
   2689  1.109     lukem 		reply(0,
   2690  1.109     lukem 		    "Total data:       " LLF " byte%s in " LLF " file%s",
   2691  1.109     lukem 		    (LLT)total_data, PLURAL(total_data),
   2692  1.109     lukem 		    (LLT)total_files, PLURAL(total_files));
   2693   1.62     lukem 	}
   2694   1.62     lukem 	otbi = total_bytes_in;
   2695   1.62     lukem 	otbo = total_bytes_out;
   2696   1.62     lukem 	otb = total_bytes;
   2697  1.109     lukem 	reply(0, "Traffic sent:     " LLF " byte%s in " LLF " transfer%s",
   2698  1.109     lukem 	    (LLT)otbo, PLURAL(otbo),
   2699  1.109     lukem 	    (LLT)total_xfers_out, PLURAL(total_xfers_out));
   2700  1.109     lukem 	reply(0, "Traffic received: " LLF " byte%s in " LLF " transfer%s",
   2701  1.109     lukem 	    (LLT)otbi, PLURAL(otbi),
   2702  1.109     lukem 	    (LLT)total_xfers_in, PLURAL(total_xfers_in));
   2703  1.109     lukem 	reply(0, "Total traffic:    " LLF " byte%s in " LLF " transfer%s",
   2704  1.109     lukem 	    (LLT)otb, PLURAL(otb),
   2705  1.109     lukem 	    (LLT)total_xfers, PLURAL(total_xfers));
   2706   1.24     lukem 
   2707  1.133     lukem 	if (logged_in && !CURCLASS_FLAGS_ISSET(private)) {
   2708   1.24     lukem 		struct ftpconv *cp;
   2709   1.24     lukem 
   2710   1.98  sommerfe 		reply(0, "%s", "");
   2711   1.95     lukem 		reply(0, "Class: %s, type: %s",
   2712   1.81     lukem 		    curclass.classname, CURCLASSTYPE);
   2713   1.95     lukem 		reply(0, "Check PORT/LPRT commands: %sabled",
   2714  1.111     lukem 		    CURCLASS_FLAGS_ISSET(checkportcmd) ? "en" : "dis");
   2715  1.100     lukem 		if (! EMPTYSTR(curclass.display))
   2716   1.95     lukem 			reply(0, "Display file: %s", curclass.display);
   2717  1.100     lukem 		if (! EMPTYSTR(curclass.notify))
   2718   1.95     lukem 			reply(0, "Notify fileglob: %s", curclass.notify);
   2719  1.147     lukem 		reply(0, "Idle timeout: " LLF ", maximum timeout: " LLF,
   2720  1.147     lukem 		    (LLT)curclass.timeout, (LLT)curclass.maxtimeout);
   2721   1.95     lukem 		reply(0, "Current connections: %d", connections);
   2722   1.82     lukem 		if (curclass.limit == -1)
   2723   1.95     lukem 			reply(0, "Maximum connections: unlimited");
   2724   1.82     lukem 		else
   2725  1.147     lukem 			reply(0, "Maximum connections: " LLF,
   2726  1.147     lukem 			    (LLT)curclass.limit);
   2727   1.82     lukem 		if (curclass.limitfile)
   2728  1.111     lukem 			reply(0, "Connection limit exceeded message file: %s",
   2729  1.131     lukem 			    conffilename(curclass.limitfile));
   2730  1.100     lukem 		if (! EMPTYSTR(curclass.chroot))
   2731  1.100     lukem 			reply(0, "Chroot format: %s", curclass.chroot);
   2732  1.135     lukem 		reply(0, "Deny bad ftpusers(5) quickly: %sabled",
   2733  1.133     lukem 		    CURCLASS_FLAGS_ISSET(denyquick) ? "en" : "dis");
   2734  1.100     lukem 		if (! EMPTYSTR(curclass.homedir))
   2735  1.100     lukem 			reply(0, "Homedir format: %s", curclass.homedir);
   2736  1.111     lukem 		if (curclass.maxfilesize == -1)
   2737  1.111     lukem 			reply(0, "Maximum file size: unlimited");
   2738  1.111     lukem 		else
   2739  1.111     lukem 			reply(0, "Maximum file size: " LLF,
   2740  1.111     lukem 			    (LLT)curclass.maxfilesize);
   2741  1.100     lukem 		if (! EMPTYSTR(curclass.motd))
   2742  1.131     lukem 			reply(0, "MotD file: %s", conffilename(curclass.motd));
   2743   1.95     lukem 		reply(0,
   2744   1.73     lukem 	    "Modify commands (CHMOD, DELE, MKD, RMD, RNFR, UMASK): %sabled",
   2745  1.111     lukem 		    CURCLASS_FLAGS_ISSET(modify) ? "en" : "dis");
   2746   1.95     lukem 		reply(0, "Upload commands (APPE, STOR, STOU): %sabled",
   2747  1.111     lukem 		    CURCLASS_FLAGS_ISSET(upload) ? "en" : "dis");
   2748  1.111     lukem 		reply(0, "Sanitize file names: %sabled",
   2749  1.111     lukem 		    CURCLASS_FLAGS_ISSET(sanenames) ? "en" : "dis");
   2750  1.111     lukem 		reply(0, "PASV/LPSV/EPSV connections: %sabled",
   2751  1.111     lukem 		    CURCLASS_FLAGS_ISSET(passive) ? "en" : "dis");
   2752  1.118     lukem 		if (curclass.advertise.su_len != 0) {
   2753  1.118     lukem 			char buf[50];	/* big enough for IPv6 address */
   2754  1.118     lukem 			const char *bp;
   2755  1.118     lukem 
   2756  1.118     lukem 			bp = inet_ntop(curclass.advertise.su_family,
   2757  1.118     lukem 			    (void *)&curclass.advertise.su_addr,
   2758  1.118     lukem 			    buf, sizeof(buf));
   2759  1.118     lukem 			if (bp != NULL)
   2760  1.128     lukem 				reply(0, "PASV advertise address: %s", bp);
   2761  1.118     lukem 		}
   2762   1.85     lukem 		if (curclass.portmin && curclass.portmax)
   2763  1.147     lukem 			reply(0, "PASV port range: " LLF " - " LLF,
   2764  1.147     lukem 			    (LLT)curclass.portmin, (LLT)curclass.portmax);
   2765   1.73     lukem 		if (curclass.rateget)
   2766  1.111     lukem 			reply(0, "Rate get limit: " LLF " bytes/sec",
   2767  1.111     lukem 			    (LLT)curclass.rateget);
   2768   1.73     lukem 		else
   2769   1.95     lukem 			reply(0, "Rate get limit: disabled");
   2770   1.73     lukem 		if (curclass.rateput)
   2771  1.111     lukem 			reply(0, "Rate put limit: " LLF " bytes/sec",
   2772  1.111     lukem 			    (LLT)curclass.rateput);
   2773   1.73     lukem 		else
   2774   1.95     lukem 			reply(0, "Rate put limit: disabled");
   2775  1.147     lukem 		if (curclass.mmapsize)
   2776  1.147     lukem 			reply(0, "Mmap size: " LLF, (LLT)curclass.mmapsize);
   2777  1.147     lukem 		else
   2778  1.147     lukem 			reply(0, "Mmap size: disabled");
   2779  1.147     lukem 		if (curclass.readsize)
   2780  1.147     lukem 			reply(0, "Read size: " LLF, (LLT)curclass.readsize);
   2781  1.147     lukem 		else
   2782  1.147     lukem 			reply(0, "Read size: default");
   2783  1.147     lukem 		if (curclass.writesize)
   2784  1.147     lukem 			reply(0, "Write size: " LLF, (LLT)curclass.writesize);
   2785  1.147     lukem 		else
   2786  1.147     lukem 			reply(0, "Write size: default");
   2787  1.168  ginsbach 		if (curclass.recvbufsize)
   2788  1.168  ginsbach 			reply(0, "Receive buffer size: " LLF,
   2789  1.168  ginsbach 			    (LLT)curclass.recvbufsize);
   2790  1.168  ginsbach 		else
   2791  1.168  ginsbach 			reply(0, "Receive buffer size: default");
   2792  1.147     lukem 		if (curclass.sendbufsize)
   2793  1.147     lukem 			reply(0, "Send buffer size: " LLF,
   2794  1.147     lukem 			    (LLT)curclass.sendbufsize);
   2795  1.147     lukem 		else
   2796  1.147     lukem 			reply(0, "Send buffer size: default");
   2797  1.147     lukem 		if (curclass.sendlowat)
   2798  1.147     lukem 			reply(0, "Send low water mark: " LLF,
   2799  1.147     lukem 			    (LLT)curclass.sendlowat);
   2800  1.147     lukem 		else
   2801  1.147     lukem 			reply(0, "Send low water mark: default");
   2802   1.95     lukem 		reply(0, "Umask: %.04o", curclass.umask);
   2803   1.24     lukem 		for (cp = curclass.conversions; cp != NULL; cp=cp->next) {
   2804   1.24     lukem 			if (cp->suffix == NULL || cp->types == NULL ||
   2805   1.24     lukem 			    cp->command == NULL)
   2806   1.24     lukem 				continue;
   2807   1.95     lukem 			reply(0, "Conversion: %s [%s] disable: %s, command: %s",
   2808   1.24     lukem 			    cp->suffix, cp->types, cp->disable, cp->command);
   2809   1.24     lukem 		}
   2810   1.24     lukem 	}
   2811   1.24     lukem 
   2812    1.1       cgd 	reply(211, "End of status");
   2813    1.1       cgd }
   2814    1.1       cgd 
   2815    1.8   deraadt void
   2816   1.88     lukem fatal(const char *s)
   2817    1.1       cgd {
   2818    1.8   deraadt 
   2819    1.1       cgd 	reply(451, "Error in server: %s\n", s);
   2820    1.1       cgd 	reply(221, "Closing connection due to server error.");
   2821    1.1       cgd 	dologout(0);
   2822    1.1       cgd 	/* NOTREACHED */
   2823    1.1       cgd }
   2824    1.1       cgd 
   2825   1.93     lukem /*
   2826   1.93     lukem  * reply() --
   2827   1.95     lukem  *	depending on the value of n, display fmt with a trailing CRLF and
   2828   1.95     lukem  *	prefix of:
   2829   1.95     lukem  *	n < -1		prefix the message with abs(n) + "-"	(initial line)
   2830   1.95     lukem  *	n == 0		prefix the message with 4 spaces	(middle lines)
   2831   1.95     lukem  *	n >  0		prefix the message with n + " "		(final line)
   2832   1.93     lukem  */
   2833    1.8   deraadt void
   2834    1.8   deraadt reply(int n, const char *fmt, ...)
   2835    1.1       cgd {
   2836  1.158     lukem 	char	msg[MAXPATHLEN * 2 + 100];
   2837  1.158     lukem 	size_t	b;
   2838  1.158     lukem 	va_list	ap;
   2839   1.88     lukem 
   2840   1.95     lukem 	if (n == 0)
   2841  1.158     lukem 		b = snprintf(msg, sizeof(msg), "    ");
   2842   1.95     lukem 	else if (n < 0)
   2843  1.158     lukem 		b = snprintf(msg, sizeof(msg), "%d-", -n);
   2844   1.95     lukem 	else
   2845  1.158     lukem 		b = snprintf(msg, sizeof(msg), "%d ", n);
   2846  1.158     lukem 	va_start(ap, fmt);
   2847  1.158     lukem 	vsnprintf(msg + b, sizeof(msg) - b, fmt, ap);
   2848  1.130       wiz 	va_end(ap);
   2849  1.158     lukem 	cprintf(stdout, "%s\r\n", msg);
   2850    1.1       cgd 	(void)fflush(stdout);
   2851  1.171  christos 	if (ftpd_debug)
   2852  1.158     lukem 		syslog(LOG_DEBUG, "<--- %s", msg);
   2853    1.1       cgd }
   2854    1.1       cgd 
   2855    1.8   deraadt static void
   2856  1.118     lukem logremotehost(struct sockinet *who)
   2857    1.1       cgd {
   2858  1.109     lukem 
   2859  1.191  christos #if defined(HAVE_SOCKADDR_SNPRINTF)
   2860  1.191  christos 	char abuf[BUFSIZ];
   2861  1.191  christos #endif
   2862  1.191  christos 
   2863  1.191  christos 	struct sockaddr *sa = (struct sockaddr *)&who->si_su;
   2864  1.191  christos 	if (getnameinfo(sa, who->su_len, remotehost, sizeof(remotehost), NULL,
   2865  1.191  christos 	    0, getnameopts))
   2866  1.112    itojun 		strlcpy(remotehost, "?", sizeof(remotehost));
   2867  1.191  christos #if defined(HAVE_SOCKADDR_SNPRINTF)
   2868  1.191  christos 	sockaddr_snprintf(abuf, sizeof(abuf), "%a", sa);
   2869  1.191  christos 	snprintf(remoteloghost, sizeof(remoteloghost), "%s(%s)", remotehost,
   2870  1.191  christos 	    abuf);
   2871  1.191  christos #else
   2872  1.191  christos 	strlcpy(remoteloghost, remotehost, sizeof(remoteloghost));
   2873  1.191  christos #endif
   2874  1.191  christos 
   2875  1.181     lukem #if defined(HAVE_SETPROCTITLE)
   2876    1.8   deraadt 	snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
   2877   1.97    itojun 	setproctitle("%s", proctitle);
   2878  1.181     lukem #endif /* defined(HAVE_SETPROCTITLE) */
   2879    1.8   deraadt 	if (logging)
   2880   1.79     lukem 		syslog(LOG_INFO, "connection from %s to %s",
   2881  1.191  christos 		    remoteloghost, hostname);
   2882    1.1       cgd }
   2883    1.1       cgd 
   2884    1.1       cgd /*
   2885  1.118     lukem  * Record logout in wtmp file and exit with supplied status.
   2886  1.158     lukem  * NOTE: because this is called from signal handlers it cannot
   2887  1.158     lukem  *       use stdio (or call other functions that use stdio).
   2888    1.1       cgd  */
   2889    1.8   deraadt void
   2890   1.88     lukem dologout(int status)
   2891    1.1       cgd {
   2892   1.16       mrg 	/*
   2893   1.16       mrg 	* Prevent reception of SIGURG from resulting in a resumption
   2894   1.16       mrg 	* back to the main program loop.
   2895   1.16       mrg 	*/
   2896   1.16       mrg 	transflag = 0;
   2897  1.141  christos 	logout_utmp();
   2898    1.1       cgd 	if (logged_in) {
   2899   1.36   mycroft #ifdef KERBEROS
   2900    1.4       cgd 		if (!notickets && krbtkfile_env)
   2901    1.4       cgd 			unlink(krbtkfile_env);
   2902    1.4       cgd #endif
   2903    1.1       cgd 	}
   2904    1.1       cgd 	/* beware of flushing buffers after a SIGPIPE */
   2905  1.154     lukem 	if (xferlogfd != -1)
   2906  1.154     lukem 		close(xferlogfd);
   2907    1.1       cgd 	_exit(status);
   2908    1.1       cgd }
   2909    1.1       cgd 
   2910  1.124     lukem void
   2911  1.124     lukem abor(void)
   2912  1.123     aidan {
   2913  1.124     lukem 
   2914  1.158     lukem 	if (!transflag)
   2915  1.158     lukem 		return;
   2916  1.123     aidan 	tmpline[0] = '\0';
   2917  1.123     aidan 	is_oob = 0;
   2918  1.123     aidan 	reply(426, "Transfer aborted. Data connection closed.");
   2919  1.123     aidan 	reply(226, "Abort successful");
   2920  1.158     lukem 	transflag = 0;		/* flag that the transfer has aborted */
   2921  1.123     aidan }
   2922  1.123     aidan 
   2923  1.124     lukem void
   2924  1.124     lukem statxfer(void)
   2925  1.123     aidan {
   2926  1.124     lukem 
   2927  1.158     lukem 	if (!transflag)
   2928  1.158     lukem 		return;
   2929  1.123     aidan 	tmpline[0] = '\0';
   2930  1.123     aidan 	is_oob = 0;
   2931  1.123     aidan 	if (file_size != (off_t) -1)
   2932  1.123     aidan 		reply(213,
   2933  1.123     aidan 		    "Status: " LLF " of " LLF " byte%s transferred",
   2934  1.123     aidan 		    (LLT)byte_count, (LLT)file_size,
   2935  1.123     aidan 		    PLURAL(byte_count));
   2936  1.123     aidan 	else
   2937  1.123     aidan 		reply(213, "Status: " LLF " byte%s transferred",
   2938  1.123     aidan 		    (LLT)byte_count, PLURAL(byte_count));
   2939  1.123     aidan }
   2940  1.123     aidan 
   2941  1.158     lukem /*
   2942  1.158     lukem  * Call when urgflag != 0 to handle Out Of Band commands.
   2943  1.158     lukem  * Returns non zero if the OOB command aborted the transfer
   2944  1.158     lukem  * by setting transflag to 0. (c.f., "ABOR").
   2945  1.158     lukem  */
   2946  1.158     lukem static int
   2947  1.198  dholland handleoobcmd(void)
   2948    1.1       cgd {
   2949    1.1       cgd 	char *cp;
   2950  1.187     lukem 	int ret;
   2951    1.1       cgd 
   2952  1.158     lukem 	if (!urgflag)
   2953  1.158     lukem 		return (0);
   2954  1.158     lukem 	urgflag = 0;
   2955    1.1       cgd 	/* only process if transfer occurring */
   2956    1.1       cgd 	if (!transflag)
   2957  1.158     lukem 		return (0);
   2958    1.1       cgd 	cp = tmpline;
   2959  1.194       roy 	ret = get_line(cp, sizeof(tmpline)-1, stdin);
   2960  1.187     lukem 	if (ret == -1) {
   2961    1.1       cgd 		reply(221, "You could at least say goodbye.");
   2962    1.1       cgd 		dologout(0);
   2963  1.187     lukem 	} else if (ret == -2) {
   2964  1.187     lukem 		/* Ignore truncated command */
   2965  1.187     lukem 		/* XXX: abort xfer with "500 command too long", & return 1 ? */
   2966  1.187     lukem 		return 0;
   2967    1.1       cgd 	}
   2968  1.158     lukem 		/*
   2969  1.158     lukem 		 * Manually parse OOB commands, because we can't
   2970  1.158     lukem 		 * recursively call the yacc parser...
   2971  1.158     lukem 		 */
   2972  1.158     lukem 	if (strcasecmp(cp, "ABOR\r\n") == 0) {
   2973  1.158     lukem 		abor();
   2974  1.158     lukem 	} else if (strcasecmp(cp, "STAT\r\n") == 0) {
   2975  1.158     lukem 		statxfer();
   2976  1.158     lukem 	} else {
   2977  1.158     lukem 		/* XXX: error with "500 unknown command" ? */
   2978  1.158     lukem 	}
   2979  1.158     lukem 	return (transflag == 0);
   2980    1.1       cgd }
   2981    1.1       cgd 
   2982   1.84     lukem static int
   2983   1.88     lukem bind_pasv_addr(void)
   2984   1.84     lukem {
   2985   1.84     lukem 	static int passiveport;
   2986   1.84     lukem 	int port, len;
   2987   1.84     lukem 
   2988   1.84     lukem 	len = pasv_addr.su_len;
   2989   1.84     lukem 	if (curclass.portmin == 0 && curclass.portmax == 0) {
   2990   1.84     lukem 		pasv_addr.su_port = 0;
   2991  1.109     lukem 		return (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len));
   2992   1.84     lukem 	}
   2993   1.84     lukem 
   2994   1.84     lukem 	if (passiveport == 0) {
   2995   1.84     lukem 		srand(getpid());
   2996   1.84     lukem 		passiveport = rand() % (curclass.portmax - curclass.portmin)
   2997   1.84     lukem 		    + curclass.portmin;
   2998   1.84     lukem 	}
   2999   1.84     lukem 
   3000   1.84     lukem 	port = passiveport;
   3001   1.84     lukem 	while (1) {
   3002   1.84     lukem 		port++;
   3003   1.84     lukem 		if (port > curclass.portmax)
   3004   1.84     lukem 			port = curclass.portmin;
   3005   1.84     lukem 		else if (port == passiveport) {
   3006   1.84     lukem 			errno = EAGAIN;
   3007   1.84     lukem 			return (-1);
   3008   1.84     lukem 		}
   3009   1.84     lukem 		pasv_addr.su_port = htons(port);
   3010  1.109     lukem 		if (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len) == 0)
   3011   1.84     lukem 			break;
   3012   1.84     lukem 		if (errno != EADDRINUSE)
   3013   1.84     lukem 			return (-1);
   3014   1.84     lukem 	}
   3015   1.84     lukem 	passiveport = port;
   3016   1.84     lukem 	return (0);
   3017   1.84     lukem }
   3018   1.84     lukem 
   3019    1.1       cgd /*
   3020    1.1       cgd  * Note: a response of 425 is not mentioned as a possible response to
   3021    1.8   deraadt  *	the PASV command in RFC959. However, it has been blessed as
   3022    1.8   deraadt  *	a legitimate response by Jon Postel in a telephone conversation
   3023    1.1       cgd  *	with Rick Adams on 25 Jan 89.
   3024    1.1       cgd  */
   3025    1.8   deraadt void
   3026   1.88     lukem passive(void)
   3027    1.1       cgd {
   3028  1.193     lukem 	socklen_t len;
   3029  1.193     lukem 	int recvbufsize;
   3030    1.8   deraadt 	char *p, *a;
   3031    1.1       cgd 
   3032   1.72    itojun 	if (pdata >= 0)
   3033   1.72    itojun 		close(pdata);
   3034    1.1       cgd 	pdata = socket(AF_INET, SOCK_STREAM, 0);
   3035   1.23     lukem 	if (pdata < 0 || !logged_in) {
   3036    1.1       cgd 		perror_reply(425, "Can't open passive connection");
   3037    1.1       cgd 		return;
   3038    1.1       cgd 	}
   3039    1.1       cgd 	pasv_addr = ctrl_addr;
   3040   1.84     lukem 
   3041   1.84     lukem 	if (bind_pasv_addr() < 0)
   3042   1.84     lukem 		goto pasv_error;
   3043   1.67    itojun 	len = pasv_addr.su_len;
   3044  1.109     lukem 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
   3045    1.1       cgd 		goto pasv_error;
   3046  1.109     lukem 	pasv_addr.su_len = len;
   3047  1.168  ginsbach 	if (curclass.recvbufsize) {
   3048  1.168  ginsbach 		recvbufsize = curclass.recvbufsize;
   3049  1.168  ginsbach 		if (setsockopt(pdata, SOL_SOCKET, SO_RCVBUF, &recvbufsize,
   3050  1.168  ginsbach 			       sizeof(int)) == -1)
   3051  1.168  ginsbach 			syslog(LOG_WARNING, "setsockopt(SO_RCVBUF, %d): %m",
   3052  1.168  ginsbach 			       recvbufsize);
   3053  1.168  ginsbach 	}
   3054    1.1       cgd 	if (listen(pdata, 1) < 0)
   3055    1.1       cgd 		goto pasv_error;
   3056  1.118     lukem 	if (curclass.advertise.su_len != 0)
   3057  1.118     lukem 		a = (char *) &curclass.advertise.su_addr;
   3058  1.118     lukem 	else
   3059  1.118     lukem 		a = (char *) &pasv_addr.su_addr;
   3060   1.67    itojun 	p = (char *) &pasv_addr.su_port;
   3061    1.1       cgd 
   3062    1.1       cgd #define UC(b) (((int) b) & 0xff)
   3063    1.1       cgd 
   3064    1.1       cgd 	reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
   3065    1.1       cgd 		UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
   3066    1.1       cgd 	return;
   3067    1.1       cgd 
   3068   1.89     lukem  pasv_error:
   3069   1.67    itojun 	(void) close(pdata);
   3070   1.67    itojun 	pdata = -1;
   3071   1.67    itojun 	perror_reply(425, "Can't open passive connection");
   3072   1.67    itojun 	return;
   3073   1.67    itojun }
   3074   1.67    itojun 
   3075   1.67    itojun /*
   3076  1.106    itojun  * convert protocol identifier to/from AF
   3077  1.106    itojun  */
   3078  1.106    itojun int
   3079  1.106    itojun lpsvproto2af(int proto)
   3080  1.106    itojun {
   3081  1.106    itojun 
   3082  1.106    itojun 	switch (proto) {
   3083  1.109     lukem 	case 4:
   3084  1.109     lukem 		return AF_INET;
   3085  1.106    itojun #ifdef INET6
   3086  1.109     lukem 	case 6:
   3087  1.109     lukem 		return AF_INET6;
   3088  1.106    itojun #endif
   3089  1.109     lukem 	default:
   3090  1.109     lukem 		return -1;
   3091  1.106    itojun 	}
   3092  1.106    itojun }
   3093  1.106    itojun 
   3094  1.106    itojun int
   3095  1.106    itojun af2lpsvproto(int af)
   3096  1.106    itojun {
   3097  1.106    itojun 
   3098  1.106    itojun 	switch (af) {
   3099  1.109     lukem 	case AF_INET:
   3100  1.109     lukem 		return 4;
   3101  1.106    itojun #ifdef INET6
   3102  1.109     lukem 	case AF_INET6:
   3103  1.109     lukem 		return 6;
   3104  1.106    itojun #endif
   3105  1.109     lukem 	default:
   3106  1.109     lukem 		return -1;
   3107  1.106    itojun 	}
   3108  1.106    itojun }
   3109  1.106    itojun 
   3110  1.106    itojun int
   3111  1.106    itojun epsvproto2af(int proto)
   3112  1.106    itojun {
   3113  1.106    itojun 
   3114  1.106    itojun 	switch (proto) {
   3115  1.109     lukem 	case 1:
   3116  1.109     lukem 		return AF_INET;
   3117  1.106    itojun #ifdef INET6
   3118  1.109     lukem 	case 2:
   3119  1.109     lukem 		return AF_INET6;
   3120  1.106    itojun #endif
   3121  1.109     lukem 	default:
   3122  1.109     lukem 		return -1;
   3123  1.106    itojun 	}
   3124  1.106    itojun }
   3125  1.106    itojun 
   3126  1.106    itojun int
   3127  1.106    itojun af2epsvproto(int af)
   3128  1.106    itojun {
   3129  1.106    itojun 
   3130  1.106    itojun 	switch (af) {
   3131  1.109     lukem 	case AF_INET:
   3132  1.109     lukem 		return 1;
   3133  1.106    itojun #ifdef INET6
   3134  1.109     lukem 	case AF_INET6:
   3135  1.109     lukem 		return 2;
   3136  1.106    itojun #endif
   3137  1.109     lukem 	default:
   3138  1.109     lukem 		return -1;
   3139  1.106    itojun 	}
   3140  1.106    itojun }
   3141  1.106    itojun 
   3142  1.106    itojun /*
   3143   1.67    itojun  * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)
   3144   1.67    itojun  * 229 Entering Extended Passive Mode (|||port|)
   3145   1.67    itojun  */
   3146   1.67    itojun void
   3147  1.193     lukem long_passive(const char *cmd, int pf)
   3148   1.67    itojun {
   3149  1.176       mrg 	socklen_t len;
   3150   1.84     lukem 	char *p, *a;
   3151   1.67    itojun 
   3152   1.67    itojun 	if (!logged_in) {
   3153   1.67    itojun 		syslog(LOG_NOTICE, "long passive but not logged in");
   3154   1.67    itojun 		reply(503, "Login with USER first.");
   3155   1.67    itojun 		return;
   3156   1.67    itojun 	}
   3157   1.67    itojun 
   3158  1.106    itojun 	if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) {
   3159  1.106    itojun 		/*
   3160  1.111     lukem 		 * XXX: only EPRT/EPSV ready clients will understand this
   3161  1.106    itojun 		 */
   3162  1.106    itojun 		if (strcmp(cmd, "EPSV") != 0)
   3163  1.106    itojun 			reply(501, "Network protocol mismatch"); /*XXX*/
   3164  1.106    itojun 		else
   3165  1.106    itojun 			epsv_protounsupp("Network protocol mismatch");
   3166   1.67    itojun 
   3167  1.106    itojun 		return;
   3168   1.67    itojun 	}
   3169   1.73     lukem 
   3170   1.72    itojun 	if (pdata >= 0)
   3171   1.72    itojun 		close(pdata);
   3172   1.67    itojun 	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
   3173   1.67    itojun 	if (pdata < 0) {
   3174   1.67    itojun 		perror_reply(425, "Can't open passive connection");
   3175   1.67    itojun 		return;
   3176   1.67    itojun 	}
   3177   1.67    itojun 	pasv_addr = ctrl_addr;
   3178   1.84     lukem 	if (bind_pasv_addr() < 0)
   3179   1.67    itojun 		goto pasv_error;
   3180   1.67    itojun 	len = pasv_addr.su_len;
   3181  1.109     lukem 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
   3182   1.67    itojun 		goto pasv_error;
   3183  1.109     lukem 	pasv_addr.su_len = len;
   3184   1.67    itojun 	if (listen(pdata, 1) < 0)
   3185   1.67    itojun 		goto pasv_error;
   3186   1.67    itojun 	p = (char *) &pasv_addr.su_port;
   3187   1.67    itojun 
   3188   1.67    itojun #define UC(b) (((int) b) & 0xff)
   3189   1.67    itojun 
   3190   1.67    itojun 	if (strcmp(cmd, "LPSV") == 0) {
   3191  1.118     lukem 		struct sockinet *advert;
   3192  1.118     lukem 
   3193  1.118     lukem 		if (curclass.advertise.su_len != 0)
   3194  1.118     lukem 			advert = &curclass.advertise;
   3195  1.118     lukem 		else
   3196  1.118     lukem 			advert = &pasv_addr;
   3197  1.118     lukem 		switch (advert->su_family) {
   3198   1.67    itojun 		case AF_INET:
   3199  1.118     lukem 			a = (char *) &advert->su_addr;
   3200  1.109     lukem 			reply(228,
   3201  1.109     lukem     "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
   3202   1.67    itojun 				4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
   3203   1.67    itojun 				2, UC(p[0]), UC(p[1]));
   3204   1.67    itojun 			return;
   3205  1.104  christos #ifdef INET6
   3206   1.67    itojun 		case AF_INET6:
   3207  1.118     lukem 			a = (char *) &advert->su_6addr;
   3208  1.109     lukem 			reply(228,
   3209  1.109     lukem     "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
   3210   1.67    itojun 				6, 16,
   3211   1.67    itojun 				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
   3212   1.67    itojun 				UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
   3213   1.67    itojun 				UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
   3214   1.67    itojun 				UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
   3215   1.67    itojun 				2, UC(p[0]), UC(p[1]));
   3216   1.67    itojun 			return;
   3217  1.104  christos #endif
   3218   1.67    itojun 		}
   3219   1.67    itojun #undef UC
   3220   1.67    itojun 	} else if (strcmp(cmd, "EPSV") == 0) {
   3221   1.67    itojun 		switch (pasv_addr.su_family) {
   3222   1.67    itojun 		case AF_INET:
   3223  1.109     lukem #ifdef INET6
   3224   1.67    itojun 		case AF_INET6:
   3225  1.109     lukem #endif
   3226   1.67    itojun 			reply(229, "Entering Extended Passive Mode (|||%d|)",
   3227  1.109     lukem 			    ntohs(pasv_addr.su_port));
   3228   1.67    itojun 			return;
   3229   1.67    itojun 		}
   3230   1.67    itojun 	} else {
   3231   1.67    itojun 		/* more proper error code? */
   3232   1.67    itojun 	}
   3233   1.67    itojun 
   3234   1.89     lukem  pasv_error:
   3235    1.1       cgd 	(void) close(pdata);
   3236    1.1       cgd 	pdata = -1;
   3237    1.1       cgd 	perror_reply(425, "Can't open passive connection");
   3238    1.1       cgd 	return;
   3239  1.106    itojun }
   3240  1.106    itojun 
   3241  1.106    itojun int
   3242  1.106    itojun extended_port(const char *arg)
   3243  1.106    itojun {
   3244  1.106    itojun 	char *tmp = NULL;
   3245  1.106    itojun 	char *result[3];
   3246  1.106    itojun 	char *p, *q;
   3247  1.106    itojun 	char delim;
   3248  1.106    itojun 	struct addrinfo hints;
   3249  1.106    itojun 	struct addrinfo *res = NULL;
   3250  1.106    itojun 	int i;
   3251  1.106    itojun 	unsigned long proto;
   3252  1.106    itojun 
   3253  1.171  christos 	tmp = ftpd_strdup(arg);
   3254  1.106    itojun 	p = tmp;
   3255  1.106    itojun 	delim = p[0];
   3256  1.106    itojun 	p++;
   3257  1.106    itojun 	memset(result, 0, sizeof(result));
   3258  1.106    itojun 	for (i = 0; i < 3; i++) {
   3259  1.106    itojun 		q = strchr(p, delim);
   3260  1.106    itojun 		if (!q || *q != delim)
   3261  1.106    itojun 			goto parsefail;
   3262  1.106    itojun 		*q++ = '\0';
   3263  1.106    itojun 		result[i] = p;
   3264  1.106    itojun 		p = q;
   3265  1.106    itojun 	}
   3266  1.106    itojun 
   3267  1.111     lukem 			/* some more sanity checks */
   3268  1.146    itojun 	errno = 0;
   3269  1.106    itojun 	p = NULL;
   3270  1.106    itojun 	(void)strtoul(result[2], &p, 10);
   3271  1.146    itojun 	if (errno || !*result[2] || *p)
   3272  1.108    itojun 		goto parsefail;
   3273  1.146    itojun 	errno = 0;
   3274  1.106    itojun 	p = NULL;
   3275  1.106    itojun 	proto = strtoul(result[0], &p, 10);
   3276  1.146    itojun 	if (errno || !*result[0] || *p)
   3277  1.106    itojun 		goto protounsupp;
   3278  1.106    itojun 
   3279  1.106    itojun 	memset(&hints, 0, sizeof(hints));
   3280  1.106    itojun 	hints.ai_family = epsvproto2af((int)proto);
   3281  1.106    itojun 	if (hints.ai_family < 0)
   3282  1.106    itojun 		goto protounsupp;
   3283  1.106    itojun 	hints.ai_socktype = SOCK_STREAM;
   3284  1.106    itojun 	hints.ai_flags = AI_NUMERICHOST;
   3285  1.106    itojun 	if (getaddrinfo(result[1], result[2], &hints, &res))
   3286  1.106    itojun 		goto parsefail;
   3287  1.106    itojun 	if (res->ai_next)
   3288  1.106    itojun 		goto parsefail;
   3289  1.106    itojun 	if (sizeof(data_dest) < res->ai_addrlen)
   3290  1.106    itojun 		goto parsefail;
   3291  1.118     lukem 	memcpy(&data_dest.si_su, res->ai_addr, res->ai_addrlen);
   3292  1.118     lukem 	data_dest.su_len = res->ai_addrlen;
   3293  1.113     lukem #ifdef INET6
   3294  1.106    itojun 	if (his_addr.su_family == AF_INET6 &&
   3295  1.106    itojun 	    data_dest.su_family == AF_INET6) {
   3296  1.111     lukem 			/* XXX: more sanity checks! */
   3297  1.109     lukem 		data_dest.su_scope_id = his_addr.su_scope_id;
   3298  1.106    itojun 	}
   3299  1.113     lukem #endif
   3300  1.106    itojun 
   3301  1.106    itojun 	if (tmp != NULL)
   3302  1.106    itojun 		free(tmp);
   3303  1.106    itojun 	if (res)
   3304  1.106    itojun 		freeaddrinfo(res);
   3305  1.106    itojun 	return 0;
   3306  1.106    itojun 
   3307  1.109     lukem  parsefail:
   3308  1.106    itojun 	reply(500, "Invalid argument, rejected.");
   3309  1.106    itojun 	usedefault = 1;
   3310  1.107    itojun 	if (tmp != NULL)
   3311  1.107    itojun 		free(tmp);
   3312  1.107    itojun 	if (res)
   3313  1.107    itojun 		freeaddrinfo(res);
   3314  1.106    itojun 	return -1;
   3315  1.106    itojun 
   3316  1.109     lukem  protounsupp:
   3317  1.106    itojun 	epsv_protounsupp("Protocol not supported");
   3318  1.106    itojun 	usedefault = 1;
   3319  1.107    itojun 	if (tmp != NULL)
   3320  1.107    itojun 		free(tmp);
   3321  1.106    itojun 	return -1;
   3322  1.106    itojun }
   3323  1.106    itojun 
   3324  1.106    itojun /*
   3325  1.106    itojun  * 522 Protocol not supported (proto,...)
   3326  1.106    itojun  * as we assume address family for control and data connections are the same,
   3327  1.106    itojun  * we do not return the list of address families we support - instead, we
   3328  1.106    itojun  * return the address family of the control connection.
   3329  1.106    itojun  */
   3330  1.106    itojun void
   3331  1.106    itojun epsv_protounsupp(const char *message)
   3332  1.106    itojun {
   3333  1.106    itojun 	int proto;
   3334  1.106    itojun 
   3335  1.106    itojun 	proto = af2epsvproto(ctrl_addr.su_family);
   3336  1.106    itojun 	if (proto < 0)
   3337  1.111     lukem 		reply(501, "%s", message);	/* XXX */
   3338  1.106    itojun 	else
   3339  1.106    itojun 		reply(522, "%s, use (%d)", message, proto);
   3340    1.1       cgd }
   3341    1.1       cgd 
   3342    1.1       cgd /*
   3343    1.1       cgd  * Generate unique name for file with basename "local".
   3344    1.1       cgd  * The file named "local" is already known to exist.
   3345    1.1       cgd  * Generates failure reply on error.
   3346   1.29       mrg  *
   3347  1.109     lukem  * XXX:	this function should under go changes similar to
   3348  1.109     lukem  *	the mktemp(3)/mkstemp(3) changes.
   3349    1.1       cgd  */
   3350    1.8   deraadt static char *
   3351   1.88     lukem gunique(const char *local)
   3352    1.1       cgd {
   3353   1.82     lukem 	static char new[MAXPATHLEN];
   3354    1.1       cgd 	struct stat st;
   3355    1.8   deraadt 	char *cp;
   3356   1.73     lukem 	int count;
   3357    1.1       cgd 
   3358    1.8   deraadt 	cp = strrchr(local, '/');
   3359    1.1       cgd 	if (cp)
   3360    1.1       cgd 		*cp = '\0';
   3361    1.1       cgd 	if (stat(cp ? local : ".", &st) < 0) {
   3362    1.1       cgd 		perror_reply(553, cp ? local : ".");
   3363   1.57     lukem 		return (NULL);
   3364    1.1       cgd 	}
   3365    1.1       cgd 	if (cp)
   3366    1.1       cgd 		*cp = '/';
   3367    1.1       cgd 	for (count = 1; count < 100; count++) {
   3368   1.73     lukem 		(void)snprintf(new, sizeof(new) - 1, "%s.%d", local, count);
   3369    1.1       cgd 		if (stat(new, &st) < 0)
   3370    1.8   deraadt 			return (new);
   3371    1.1       cgd 	}
   3372    1.1       cgd 	reply(452, "Unique file name cannot be created.");
   3373    1.8   deraadt 	return (NULL);
   3374    1.1       cgd }
   3375    1.1       cgd 
   3376    1.1       cgd /*
   3377    1.1       cgd  * Format and send reply containing system error number.
   3378    1.1       cgd  */
   3379    1.8   deraadt void
   3380   1.88     lukem perror_reply(int code, const char *string)
   3381    1.1       cgd {
   3382   1.62     lukem 	int save_errno;
   3383    1.8   deraadt 
   3384   1.62     lukem 	save_errno = errno;
   3385    1.1       cgd 	reply(code, "%s: %s.", string, strerror(errno));
   3386   1.62     lukem 	errno = save_errno;
   3387    1.1       cgd }
   3388    1.1       cgd 
   3389    1.1       cgd static char *onefile[] = {
   3390  1.193     lukem 	NULL,
   3391    1.1       cgd 	0
   3392    1.1       cgd };
   3393    1.1       cgd 
   3394    1.8   deraadt void
   3395   1.88     lukem send_file_list(const char *whichf)
   3396    1.1       cgd {
   3397    1.1       cgd 	struct stat st;
   3398  1.178  christos 	DIR *dirp;
   3399    1.1       cgd 	struct dirent *dir;
   3400  1.178  christos 	FILE *volatile dout;
   3401  1.178  christos 	char **volatile dirlist;
   3402  1.178  christos 	char *dirname, *p;
   3403  1.178  christos 	char *notglob;
   3404  1.178  christos 	int volatile simple;
   3405  1.178  christos 	int volatile freeglob;
   3406    1.8   deraadt 	glob_t gl;
   3407   1.62     lukem 
   3408  1.178  christos 	dirp = NULL;
   3409  1.178  christos 	dout = NULL;
   3410  1.178  christos 	notglob = NULL;
   3411  1.178  christos 	simple = 0;
   3412  1.178  christos 	freeglob = 0;
   3413  1.158     lukem 	urgflag = 0;
   3414    1.1       cgd 
   3415   1.62     lukem 	p = NULL;
   3416    1.8   deraadt 	if (strpbrk(whichf, "~{[*?") != NULL) {
   3417  1.122  christos 		int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE|GLOB_LIMIT;
   3418    1.1       cgd 
   3419    1.8   deraadt 		memset(&gl, 0, sizeof(gl));
   3420    1.8   deraadt 		freeglob = 1;
   3421    1.8   deraadt 		if (glob(whichf, flags, 0, &gl)) {
   3422  1.170     lukem 			reply(450, "Not found");
   3423  1.158     lukem 			goto cleanup_send_file_list;
   3424    1.8   deraadt 		} else if (gl.gl_pathc == 0) {
   3425    1.1       cgd 			errno = ENOENT;
   3426  1.170     lukem 			perror_reply(450, whichf);
   3427  1.158     lukem 			goto cleanup_send_file_list;
   3428    1.1       cgd 		}
   3429    1.8   deraadt 		dirlist = gl.gl_pathv;
   3430    1.1       cgd 	} else {
   3431  1.171  christos 		notglob = ftpd_strdup(whichf);
   3432  1.132     lukem 		onefile[0] = notglob;
   3433    1.1       cgd 		dirlist = onefile;
   3434    1.1       cgd 		simple = 1;
   3435    1.1       cgd 	}
   3436   1.62     lukem 					/* XXX: } for vi sm */
   3437    1.1       cgd 
   3438   1.20     lukem 	while ((dirname = *dirlist++) != NULL) {
   3439   1.33     lukem 		int trailingslash = 0;
   3440   1.33     lukem 
   3441    1.1       cgd 		if (stat(dirname, &st) < 0) {
   3442    1.1       cgd 			/*
   3443    1.1       cgd 			 * If user typed "ls -l", etc, and the client
   3444    1.1       cgd 			 * used NLST, do what the user meant.
   3445    1.1       cgd 			 */
   3446   1.71     lukem 			/* XXX: nuke this support? */
   3447    1.1       cgd 			if (dirname[0] == '-' && *dirlist == NULL &&
   3448    1.1       cgd 			    transflag == 0) {
   3449  1.193     lukem 				const char *argv[] = { INTERNAL_LS, "", NULL };
   3450   1.71     lukem 
   3451   1.71     lukem 				argv[1] = dirname;
   3452   1.71     lukem 				retrieve(argv, dirname);
   3453  1.158     lukem 				goto cleanup_send_file_list;
   3454    1.1       cgd 			}
   3455  1.170     lukem 			perror_reply(450, whichf);
   3456   1.95     lukem 			goto cleanup_send_file_list;
   3457    1.1       cgd 		}
   3458    1.1       cgd 
   3459    1.8   deraadt 		if (S_ISREG(st.st_mode)) {
   3460  1.118     lukem 			/*
   3461  1.118     lukem 			 * XXXRFC:
   3462  1.118     lukem 			 *	should we follow RFC959 and not work
   3463  1.118     lukem 			 *	for non directories?
   3464  1.118     lukem 			 */
   3465    1.1       cgd 			if (dout == NULL) {
   3466    1.1       cgd 				dout = dataconn("file list", (off_t)-1, "w");
   3467    1.1       cgd 				if (dout == NULL)
   3468  1.158     lukem 					goto cleanup_send_file_list;
   3469  1.158     lukem 				transflag = 1;
   3470    1.1       cgd 			}
   3471  1.118     lukem 			cprintf(dout, "%s%s\n", dirname,
   3472   1.62     lukem 			    type == TYPE_A ? "\r" : "");
   3473    1.1       cgd 			continue;
   3474    1.8   deraadt 		} else if (!S_ISDIR(st.st_mode))
   3475    1.1       cgd 			continue;
   3476    1.1       cgd 
   3477   1.33     lukem 		if (dirname[strlen(dirname) - 1] == '/')
   3478   1.33     lukem 			trailingslash++;
   3479   1.33     lukem 
   3480    1.1       cgd 		if ((dirp = opendir(dirname)) == NULL)
   3481    1.1       cgd 			continue;
   3482    1.1       cgd 
   3483    1.1       cgd 		while ((dir = readdir(dirp)) != NULL) {
   3484   1.82     lukem 			char nbuf[MAXPATHLEN];
   3485    1.1       cgd 
   3486  1.202       shm 			if (urgflag && handleoobcmd()) {
   3487  1.202       shm 				(void) closedir(dirp);
   3488  1.158     lukem 				goto cleanup_send_file_list;
   3489  1.202       shm 			}
   3490  1.158     lukem 
   3491   1.93     lukem 			if (ISDOTDIR(dir->d_name) || ISDOTDOTDIR(dir->d_name))
   3492    1.1       cgd 				continue;
   3493    1.1       cgd 
   3494   1.33     lukem 			(void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
   3495   1.33     lukem 			    trailingslash ? "" : "/", dir->d_name);
   3496    1.1       cgd 
   3497    1.1       cgd 			/*
   3498   1.30     lukem 			 * We have to do a stat to ensure it's
   3499    1.1       cgd 			 * not a directory or special file.
   3500    1.1       cgd 			 */
   3501  1.118     lukem 			/*
   3502  1.118     lukem 			 * XXXRFC:
   3503  1.118     lukem 			 *	should we follow RFC959 and filter out
   3504  1.118     lukem 			 *	non files ?   lukem - NO!, or not until
   3505  1.118     lukem 			 *	our ftp client uses MLS{T,D} for completion.
   3506  1.118     lukem 			 */
   3507    1.1       cgd 			if (simple || (stat(nbuf, &st) == 0 &&
   3508    1.8   deraadt 			    S_ISREG(st.st_mode))) {
   3509    1.1       cgd 				if (dout == NULL) {
   3510    1.1       cgd 					dout = dataconn("file list", (off_t)-1,
   3511    1.1       cgd 						"w");
   3512  1.202       shm 					if (dout == NULL) {
   3513  1.202       shm 						(void) closedir(dirp);
   3514  1.158     lukem 						goto cleanup_send_file_list;
   3515  1.202       shm 					}
   3516  1.158     lukem 					transflag = 1;
   3517    1.1       cgd 				}
   3518   1.62     lukem 				p = nbuf;
   3519    1.1       cgd 				if (nbuf[0] == '.' && nbuf[1] == '/')
   3520   1.62     lukem 					p = &nbuf[2];
   3521  1.118     lukem 				cprintf(dout, "%s%s\n", p,
   3522   1.62     lukem 				    type == TYPE_A ? "\r" : "");
   3523    1.1       cgd 			}
   3524    1.1       cgd 		}
   3525    1.1       cgd 		(void) closedir(dirp);
   3526    1.1       cgd 	}
   3527    1.1       cgd 
   3528    1.1       cgd 	if (dout == NULL)
   3529  1.170     lukem 		reply(450, "No files found.");
   3530    1.1       cgd 	else if (ferror(dout) != 0)
   3531  1.170     lukem 		perror_reply(451, "Data connection");
   3532    1.1       cgd 	else
   3533    1.1       cgd 		reply(226, "Transfer complete.");
   3534    1.1       cgd 
   3535   1.95     lukem  cleanup_send_file_list:
   3536  1.158     lukem 	closedataconn(dout);
   3537    1.1       cgd 	transflag = 0;
   3538  1.158     lukem 	urgflag = 0;
   3539   1.62     lukem 	total_xfers++;
   3540   1.62     lukem 	total_xfers_out++;
   3541  1.132     lukem 	if (notglob)
   3542  1.132     lukem 		free(notglob);
   3543   1.62     lukem 	if (freeglob)
   3544    1.8   deraadt 		globfree(&gl);
   3545   1.34     lukem }
   3546   1.34     lukem 
   3547   1.34     lukem char *
   3548   1.88     lukem conffilename(const char *s)
   3549   1.34     lukem {
   3550   1.82     lukem 	static char filename[MAXPATHLEN];
   3551   1.34     lukem 
   3552   1.73     lukem 	if (*s == '/')
   3553   1.73     lukem 		strlcpy(filename, s, sizeof(filename));
   3554   1.73     lukem 	else
   3555   1.73     lukem 		(void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
   3556   1.73     lukem 	return (filename);
   3557   1.62     lukem }
   3558   1.62     lukem 
   3559   1.62     lukem /*
   3560  1.118     lukem  * logxfer --
   3561  1.118     lukem  *	if logging > 1, then based on the arguments, syslog a message:
   3562   1.62     lukem  *	 if bytes != -1		"<command> <file1> = <bytes> bytes"
   3563   1.62     lukem  *	 else if file2 != NULL	"<command> <file1> <file2>"
   3564   1.62     lukem  *	 else			"<command> <file1>"
   3565   1.62     lukem  *	if elapsed != NULL, append "in xxx.yyy seconds"
   3566   1.62     lukem  *	if error != NULL, append ": " + error
   3567  1.118     lukem  *
   3568  1.147     lukem  *	if doxferlog != 0, bytes != -1, and command is "get", "put",
   3569  1.154     lukem  *	or "append", syslog and/or write a wu-ftpd style xferlog entry
   3570   1.62     lukem  */
   3571   1.62     lukem void
   3572  1.118     lukem logxfer(const char *command, off_t bytes, const char *file1, const char *file2,
   3573  1.139     enami     const struct timeval *elapsed, const char *error)
   3574   1.62     lukem {
   3575  1.169     lukem 	char		 buf[MAXPATHLEN * 2 + 100];
   3576  1.169     lukem 	char		 realfile1[MAXPATHLEN], realfile2[MAXPATHLEN];
   3577  1.118     lukem 	const char	*r1, *r2;
   3578  1.118     lukem 	char		 direction;
   3579  1.118     lukem 	size_t		 len;
   3580  1.118     lukem 	time_t		 now;
   3581   1.62     lukem 
   3582  1.118     lukem 	if (logging <=1 && !doxferlog)
   3583   1.62     lukem 		return;
   3584   1.62     lukem 
   3585  1.118     lukem 	r1 = r2 = NULL;
   3586  1.169     lukem 	if ((r1 = realpath(file1, realfile1)) == NULL)
   3587  1.118     lukem 		r1 = file1;
   3588  1.118     lukem 	if (file2 != NULL)
   3589  1.169     lukem 		if ((r2 = realpath(file2, realfile2)) == NULL)
   3590  1.118     lukem 			r2 = file2;
   3591   1.62     lukem 
   3592  1.118     lukem 		/*
   3593  1.118     lukem 		 * syslog command
   3594  1.118     lukem 		 */
   3595  1.118     lukem 	if (logging > 1) {
   3596  1.118     lukem 		len = snprintf(buf, sizeof(buf), "%s %s", command, r1);
   3597  1.118     lukem 		if (bytes != (off_t)-1)
   3598  1.118     lukem 			len += snprintf(buf + len, sizeof(buf) - len,
   3599  1.118     lukem 			    " = " LLF " byte%s", (LLT) bytes, PLURAL(bytes));
   3600  1.118     lukem 		else if (r2 != NULL)
   3601  1.118     lukem 			len += snprintf(buf + len, sizeof(buf) - len,
   3602  1.118     lukem 			    " %s", r2);
   3603  1.118     lukem 		if (elapsed != NULL)
   3604  1.118     lukem 			len += snprintf(buf + len, sizeof(buf) - len,
   3605  1.192     lukem 			    " in " LLF ".%.03ld seconds",
   3606  1.192     lukem 			    (LLT)elapsed->tv_sec,
   3607  1.190  christos 			    (long)(elapsed->tv_usec / 1000));
   3608  1.118     lukem 		if (error != NULL)
   3609  1.118     lukem 			len += snprintf(buf + len, sizeof(buf) - len,
   3610  1.118     lukem 			    ": %s", error);
   3611  1.118     lukem 		syslog(LOG_INFO, "%s", buf);
   3612   1.62     lukem 	}
   3613   1.62     lukem 
   3614  1.118     lukem 		/*
   3615  1.118     lukem 		 * syslog wu-ftpd style log entry, prefixed with "xferlog: "
   3616  1.118     lukem 		 */
   3617  1.138     lukem 	if (!doxferlog || bytes == -1)
   3618  1.118     lukem 		return;
   3619  1.118     lukem 
   3620  1.118     lukem 	if (strcmp(command, "get") == 0)
   3621  1.118     lukem 		direction = 'o';
   3622  1.118     lukem 	else if (strcmp(command, "put") == 0 || strcmp(command, "append") == 0)
   3623  1.118     lukem 		direction = 'i';
   3624  1.118     lukem 	else
   3625  1.118     lukem 		return;
   3626   1.62     lukem 
   3627  1.118     lukem 	time(&now);
   3628  1.154     lukem 	len = snprintf(buf, sizeof(buf),
   3629  1.192     lukem 	    "%.24s " LLF " %s " LLF " %s %c %s %c %c %s FTP 0 * %c\n",
   3630  1.118     lukem 
   3631  1.118     lukem /*
   3632  1.154     lukem  * XXX: wu-ftpd puts ' (send)' or ' (recv)' in the syslog message, and removes
   3633  1.118     lukem  *	the full date.  This may be problematic for accurate log parsing,
   3634  1.118     lukem  *	given that syslog messages don't contain the full date.
   3635  1.118     lukem  */
   3636  1.118     lukem 	    ctime(&now),
   3637  1.192     lukem 	    (LLT)
   3638  1.190  christos 	    (elapsed == NULL ? 0 : elapsed->tv_sec + (elapsed->tv_usec > 0)),
   3639  1.118     lukem 	    remotehost,
   3640  1.138     lukem 	    (LLT) bytes,
   3641  1.118     lukem 	    r1,
   3642  1.118     lukem 	    type == TYPE_A ? 'a' : 'b',
   3643  1.118     lukem 	    "_",		/* XXX: take conversions into account? */
   3644  1.118     lukem 	    direction,
   3645  1.118     lukem 
   3646  1.118     lukem 	    curclass.type == CLASS_GUEST ?  'a' :
   3647  1.118     lukem 	    curclass.type == CLASS_CHROOT ? 'g' :
   3648  1.118     lukem 	    curclass.type == CLASS_REAL ?   'r' : '?',
   3649  1.118     lukem 
   3650  1.118     lukem 	    curclass.type == CLASS_GUEST ? pw->pw_passwd : pw->pw_name,
   3651  1.118     lukem 	    error != NULL ? 'i' : 'c'
   3652  1.118     lukem 	    );
   3653  1.154     lukem 
   3654  1.154     lukem 	if ((doxferlog & 2) && xferlogfd != -1)
   3655  1.154     lukem 		write(xferlogfd, buf, len);
   3656  1.154     lukem 	if ((doxferlog & 1)) {
   3657  1.154     lukem 		buf[len-1] = '\n';	/* strip \n from syslog message */
   3658  1.154     lukem 		syslog(LOG_INFO, "xferlog: %s", buf);
   3659  1.154     lukem 	}
   3660  1.139     enami }
   3661  1.139     enami 
   3662  1.139     enami /*
   3663  1.139     enami  * Log the resource usage.
   3664  1.139     enami  *
   3665  1.139     enami  * XXX: more resource usage to logging?
   3666  1.139     enami  */
   3667  1.139     enami void
   3668  1.139     enami logrusage(const struct rusage *rusage_before,
   3669  1.139     enami     const struct rusage *rusage_after)
   3670  1.139     enami {
   3671  1.139     enami 	struct timeval usrtime, systime;
   3672  1.139     enami 
   3673  1.139     enami 	if (logging <= 1)
   3674  1.139     enami 		return;
   3675  1.139     enami 
   3676  1.139     enami 	timersub(&rusage_after->ru_utime, &rusage_before->ru_utime, &usrtime);
   3677  1.139     enami 	timersub(&rusage_after->ru_stime, &rusage_before->ru_stime, &systime);
   3678  1.192     lukem 	syslog(LOG_INFO, LLF ".%.03ldu " LLF ".%.03lds %ld+%ldio %ldpf+%ldw",
   3679  1.192     lukem 	    (LLT)usrtime.tv_sec, (long)(usrtime.tv_usec / 1000),
   3680  1.192     lukem 	    (LLT)systime.tv_sec, (long)(systime.tv_usec / 1000),
   3681  1.139     enami 	    rusage_after->ru_inblock - rusage_before->ru_inblock,
   3682  1.139     enami 	    rusage_after->ru_oublock - rusage_before->ru_oublock,
   3683  1.139     enami 	    rusage_after->ru_majflt - rusage_before->ru_majflt,
   3684  1.139     enami 	    rusage_after->ru_nswap - rusage_before->ru_nswap);
   3685  1.115     lukem }
   3686  1.115     lukem 
   3687  1.115     lukem /*
   3688  1.116     lukem  * Determine if `password' is valid for user given in `pw'.
   3689  1.116     lukem  * Returns 2 if password expired, 1 if otherwise failed, 0 if ok
   3690  1.115     lukem  */
   3691  1.115     lukem int
   3692  1.132     lukem checkpassword(const struct passwd *pwent, const char *password)
   3693  1.115     lukem {
   3694  1.189     lukem 	const char *orig;
   3695  1.189     lukem 	char	*new;
   3696  1.161  ginsbach 	time_t	 change, expire, now;
   3697  1.116     lukem 
   3698  1.161  ginsbach 	change = expire = 0;
   3699  1.132     lukem 	if (pwent == NULL)
   3700  1.116     lukem 		return 1;
   3701  1.116     lukem 
   3702  1.161  ginsbach 	time(&now);
   3703  1.132     lukem 	orig = pwent->pw_passwd;	/* save existing password */
   3704  1.132     lukem 	expire = pwent->pw_expire;
   3705  1.189     lukem 	change = pwent->pw_change;
   3706  1.189     lukem 	if (change == _PASSWORD_CHGNOW)
   3707  1.189     lukem 		change = now;
   3708  1.116     lukem 
   3709  1.116     lukem 	if (orig[0] == '\0')		/* don't allow empty passwords */
   3710  1.116     lukem 		return 1;
   3711  1.116     lukem 
   3712  1.116     lukem 	new = crypt(password, orig);	/* encrypt given password */
   3713  1.116     lukem 	if (strcmp(new, orig) != 0)	/* compare */
   3714  1.116     lukem 		return 1;
   3715  1.116     lukem 
   3716  1.162  ginsbach 	if ((expire && now >= expire) || (change && now >= change))
   3717  1.116     lukem 		return 2;		/* check if expired */
   3718  1.115     lukem 
   3719  1.116     lukem 	return 0;			/* OK! */
   3720   1.62     lukem }
   3721   1.62     lukem 
   3722   1.62     lukem char *
   3723  1.171  christos ftpd_strdup(const char *s)
   3724   1.62     lukem {
   3725   1.62     lukem 	char *new = strdup(s);
   3726   1.62     lukem 
   3727   1.62     lukem 	if (new == NULL)
   3728   1.62     lukem 		fatal("Local resource failure: malloc");
   3729   1.62     lukem 		/* NOTREACHED */
   3730   1.62     lukem 	return (new);
   3731   1.95     lukem }
   3732   1.95     lukem 
   3733   1.95     lukem /*
   3734   1.95     lukem  * As per fprintf(), but increment total_bytes and total_bytes_out,
   3735   1.95     lukem  * by the appropriate amount.
   3736   1.95     lukem  */
   3737   1.95     lukem void
   3738   1.95     lukem cprintf(FILE *fd, const char *fmt, ...)
   3739   1.95     lukem {
   3740   1.95     lukem 	off_t b;
   3741   1.95     lukem 	va_list ap;
   3742   1.95     lukem 
   3743   1.95     lukem 	va_start(ap, fmt);
   3744   1.95     lukem 	b = vfprintf(fd, fmt, ap);
   3745  1.130       wiz 	va_end(ap);
   3746   1.95     lukem 	total_bytes += b;
   3747   1.95     lukem 	total_bytes_out += b;
   3748    1.1       cgd }
   3749  1.164  christos 
   3750  1.164  christos #ifdef USE_PAM
   3751  1.164  christos /*
   3752  1.164  christos  * the following code is stolen from imap-uw PAM authentication module and
   3753  1.164  christos  * login.c
   3754  1.164  christos  */
   3755  1.182     lukem typedef struct {
   3756  1.183     lukem 	const char *uname;	/* user name */
   3757  1.183     lukem 	int	    triedonce;	/* if non-zero, tried before */
   3758  1.182     lukem } ftpd_cred_t;
   3759  1.164  christos 
   3760  1.164  christos static int
   3761  1.164  christos auth_conv(int num_msg, const struct pam_message **msg,
   3762  1.164  christos     struct pam_response **resp, void *appdata)
   3763  1.164  christos {
   3764  1.187     lukem 	int i, ret;
   3765  1.183     lukem 	size_t n;
   3766  1.182     lukem 	ftpd_cred_t *cred = (ftpd_cred_t *) appdata;
   3767  1.164  christos 	struct pam_response *myreply;
   3768  1.183     lukem 	char pbuf[FTP_BUFLEN];
   3769  1.164  christos 
   3770  1.183     lukem 	if (num_msg <= 0 || num_msg > PAM_MAX_NUM_MSG)
   3771  1.183     lukem 		return (PAM_CONV_ERR);
   3772  1.164  christos 	myreply = calloc(num_msg, sizeof *myreply);
   3773  1.164  christos 	if (myreply == NULL)
   3774  1.164  christos 		return PAM_BUF_ERR;
   3775  1.164  christos 
   3776  1.164  christos 	for (i = 0; i < num_msg; i++) {
   3777  1.183     lukem 		myreply[i].resp_retcode = 0;
   3778  1.183     lukem 		myreply[i].resp = NULL;
   3779  1.164  christos 		switch (msg[i]->msg_style) {
   3780  1.183     lukem 		case PAM_PROMPT_ECHO_ON:	/* user */
   3781  1.183     lukem 			myreply[i].resp = ftpd_strdup(cred->uname);
   3782  1.164  christos 			/* PAM frees resp. */
   3783  1.164  christos 			break;
   3784  1.183     lukem 		case PAM_PROMPT_ECHO_OFF:	/* authtok (password) */
   3785  1.183     lukem 				/*
   3786  1.183     lukem 				 * Only send a single 331 reply and
   3787  1.183     lukem 				 * then expect a PASS.
   3788  1.183     lukem 				 */
   3789  1.183     lukem 			if (cred->triedonce) {
   3790  1.183     lukem 				syslog(LOG_ERR,
   3791  1.183     lukem 			"auth_conv: already performed PAM_PROMPT_ECHO_OFF");
   3792  1.183     lukem 				goto fail;
   3793  1.183     lukem 			}
   3794  1.183     lukem 			cred->triedonce++;
   3795  1.183     lukem 			if (msg[i]->msg[0] == '\0') {
   3796  1.183     lukem 				(void)strlcpy(pbuf, "password", sizeof(pbuf));
   3797  1.183     lukem 			} else {
   3798  1.185     lukem 					/* Uncapitalize msg */
   3799  1.183     lukem 				(void)strlcpy(pbuf, msg[i]->msg, sizeof(pbuf));
   3800  1.183     lukem 				if (isupper((unsigned char)pbuf[0]))
   3801  1.183     lukem 					pbuf[0] = tolower(
   3802  1.183     lukem 					    (unsigned char)pbuf[0]);
   3803  1.185     lukem 					/* Remove trailing ':' and whitespace */
   3804  1.185     lukem 				n = strlen(pbuf);
   3805  1.185     lukem 				while (n-- > 0) {
   3806  1.185     lukem 					if (isspace((unsigned char)pbuf[n]) ||
   3807  1.185     lukem 					    pbuf[n] == ':')
   3808  1.185     lukem 						pbuf[n] = '\0';
   3809  1.185     lukem 					else
   3810  1.185     lukem 						break;
   3811  1.185     lukem 				}
   3812  1.183     lukem 			}
   3813  1.183     lukem 				/* Send reply, wait for a response. */
   3814  1.183     lukem 			reply(331, "User %s accepted, provide %s.",
   3815  1.183     lukem 			    cred->uname, pbuf);
   3816  1.183     lukem 			(void) alarm(curclass.timeout);
   3817  1.194       roy 			ret = get_line(pbuf, sizeof(pbuf)-1, stdin);
   3818  1.187     lukem 			(void) alarm(0);
   3819  1.187     lukem 			if (ret == -1) {
   3820  1.183     lukem 				reply(221, "You could at least say goodbye.");
   3821  1.183     lukem 				dologout(0);
   3822  1.187     lukem 			} else if (ret == -2) {
   3823  1.187     lukem 			    /* XXX: should we do this reply(-530, ..) ? */
   3824  1.187     lukem 				reply(-530, "Command too long.");
   3825  1.187     lukem 				goto fail;
   3826  1.183     lukem 			}
   3827  1.183     lukem 				/* Ensure it is PASS */
   3828  1.183     lukem 			if (strncasecmp(pbuf, "PASS ", 5) != 0) {
   3829  1.187     lukem 				syslog(LOG_ERR,
   3830  1.187     lukem 				    "auth_conv: unexpected reply '%.4s'", pbuf);
   3831  1.187     lukem 				/* XXX: should we do this reply(-530, ..) ? */
   3832  1.187     lukem 				reply(-530, "Unexpected reply '%.4s'.", pbuf);
   3833  1.187     lukem 				goto fail;
   3834  1.183     lukem 			}
   3835  1.183     lukem 				/* Strip CRLF from "PASS" reply */
   3836  1.183     lukem 			n = strlen(pbuf);
   3837  1.183     lukem 			while (--n >= 5 &&
   3838  1.183     lukem 			    (pbuf[n] == '\r' || pbuf[n] == '\n'))
   3839  1.183     lukem 			    pbuf[n] = '\0';
   3840  1.183     lukem 				/* Copy password into reply */
   3841  1.183     lukem 			myreply[i].resp = ftpd_strdup(pbuf+5);
   3842  1.183     lukem 				/* PAM frees resp. */
   3843  1.164  christos 			break;
   3844  1.164  christos 		case PAM_TEXT_INFO:
   3845  1.164  christos 		case PAM_ERROR_MSG:
   3846  1.164  christos 			break;
   3847  1.164  christos 		default:			/* unknown message style */
   3848  1.183     lukem 			goto fail;
   3849  1.164  christos 		}
   3850  1.164  christos 	}
   3851  1.164  christos 
   3852  1.164  christos 	*resp = myreply;
   3853  1.164  christos 	return PAM_SUCCESS;
   3854  1.183     lukem 
   3855  1.183     lukem  fail:
   3856  1.183     lukem 	free(myreply);
   3857  1.183     lukem 	*resp = NULL;
   3858  1.183     lukem 	return PAM_CONV_ERR;
   3859  1.164  christos }
   3860  1.164  christos 
   3861  1.164  christos /*
   3862  1.164  christos  * Attempt to authenticate the user using PAM.  Returns 0 if the user is
   3863  1.164  christos  * authenticated, or 1 if not authenticated.  If some sort of PAM system
   3864  1.164  christos  * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
   3865  1.164  christos  * function returns -1.  This can be used as an indication that we should
   3866  1.164  christos  * fall back to a different authentication mechanism.
   3867  1.183     lukem  * pw maybe be updated to a new user if PAM_USER changes from curname.
   3868  1.164  christos  */
   3869  1.164  christos static int
   3870  1.183     lukem auth_pam(void)
   3871  1.164  christos {
   3872  1.164  christos 	const char *tmpl_user;
   3873  1.164  christos 	const void *item;
   3874  1.164  christos 	int rval;
   3875  1.164  christos 	int e;
   3876  1.183     lukem 	ftpd_cred_t auth_cred = { curname, 0 };
   3877  1.164  christos 	struct pam_conv conv = { &auth_conv, &auth_cred };
   3878  1.164  christos 
   3879  1.183     lukem 	e = pam_start("ftpd", curname, &conv, &pamh);
   3880  1.164  christos 	if (e != PAM_SUCCESS) {
   3881  1.164  christos 		/*
   3882  1.164  christos 		 * In OpenPAM, it's OK to pass NULL to pam_strerror()
   3883  1.164  christos 		 * if context creation has failed in the first place.
   3884  1.164  christos 		 */
   3885  1.164  christos 		syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
   3886  1.164  christos 		return -1;
   3887  1.164  christos 	}
   3888  1.164  christos 
   3889  1.164  christos 	e = pam_set_item(pamh, PAM_RHOST, remotehost);
   3890  1.164  christos 	if (e != PAM_SUCCESS) {
   3891  1.164  christos 		syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
   3892  1.164  christos 			pam_strerror(pamh, e));
   3893  1.164  christos 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
   3894  1.164  christos 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
   3895  1.164  christos 		}
   3896  1.164  christos 		pamh = NULL;
   3897  1.164  christos 		return -1;
   3898  1.164  christos 	}
   3899  1.164  christos 
   3900  1.179  christos 	e = pam_set_item(pamh, PAM_SOCKADDR, &his_addr);
   3901  1.179  christos 	if (e != PAM_SUCCESS) {
   3902  1.179  christos 		syslog(LOG_ERR, "pam_set_item(PAM_SOCKADDR): %s",
   3903  1.179  christos 			pam_strerror(pamh, e));
   3904  1.179  christos 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
   3905  1.179  christos 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
   3906  1.179  christos 		}
   3907  1.179  christos 		pamh = NULL;
   3908  1.179  christos 		return -1;
   3909  1.179  christos 	}
   3910  1.179  christos 
   3911  1.164  christos 	e = pam_authenticate(pamh, 0);
   3912  1.185     lukem 	if (ftpd_debug)
   3913  1.185     lukem 		syslog(LOG_DEBUG, "pam_authenticate: user '%s' returned %d",
   3914  1.185     lukem 		    curname, e);
   3915  1.164  christos 	switch (e) {
   3916  1.164  christos 	case PAM_SUCCESS:
   3917  1.164  christos 		/*
   3918  1.164  christos 		 * With PAM we support the concept of a "template"
   3919  1.164  christos 		 * user.  The user enters a login name which is
   3920  1.164  christos 		 * authenticated by PAM, usually via a remote service
   3921  1.164  christos 		 * such as RADIUS or TACACS+.  If authentication
   3922  1.164  christos 		 * succeeds, a different but related "template" name
   3923  1.164  christos 		 * is used for setting the credentials, shell, and
   3924  1.164  christos 		 * home directory.  The name the user enters need only
   3925  1.164  christos 		 * exist on the remote authentication server, but the
   3926  1.164  christos 		 * template name must be present in the local password
   3927  1.164  christos 		 * database.
   3928  1.164  christos 		 *
   3929  1.164  christos 		 * This is supported by two various mechanisms in the
   3930  1.164  christos 		 * individual modules.  However, from the application's
   3931  1.164  christos 		 * point of view, the template user is always passed
   3932  1.164  christos 		 * back as a changed value of the PAM_USER item.
   3933  1.164  christos 		 */
   3934  1.164  christos 		if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
   3935  1.164  christos 		    PAM_SUCCESS) {
   3936  1.164  christos 			tmpl_user = (const char *) item;
   3937  1.183     lukem 			if (pw == NULL
   3938  1.183     lukem 			    || strcmp(pw->pw_name, tmpl_user) != 0) {
   3939  1.183     lukem 				pw = sgetpwnam(tmpl_user);
   3940  1.183     lukem 				if (ftpd_debug)
   3941  1.183     lukem 					syslog(LOG_DEBUG,
   3942  1.185     lukem 					    "auth_pam: PAM changed "
   3943  1.185     lukem 					    "user from '%s' to '%s'",
   3944  1.183     lukem 					    curname, pw->pw_name);
   3945  1.183     lukem 				(void)strlcpy(curname, pw->pw_name,
   3946  1.183     lukem 				    curname_len);
   3947  1.183     lukem 			}
   3948  1.164  christos 		} else
   3949  1.164  christos 			syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
   3950  1.164  christos 			    pam_strerror(pamh, e));
   3951  1.164  christos 		rval = 0;
   3952  1.164  christos 		break;
   3953  1.164  christos 
   3954  1.164  christos 	case PAM_AUTH_ERR:
   3955  1.164  christos 	case PAM_USER_UNKNOWN:
   3956  1.164  christos 	case PAM_MAXTRIES:
   3957  1.164  christos 		rval = 1;
   3958  1.164  christos 		break;
   3959  1.164  christos 
   3960  1.164  christos 	default:
   3961  1.164  christos 		syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
   3962  1.164  christos 		rval = -1;
   3963  1.164  christos 		break;
   3964  1.164  christos 	}
   3965  1.164  christos 
   3966  1.164  christos 	if (rval == 0) {
   3967  1.164  christos 		e = pam_acct_mgmt(pamh, 0);
   3968  1.164  christos 		if (e != PAM_SUCCESS) {
   3969  1.164  christos 			syslog(LOG_ERR, "pam_acct_mgmt: %s",
   3970  1.164  christos 						pam_strerror(pamh, e));
   3971  1.164  christos 			rval = 1;
   3972  1.164  christos 		}
   3973  1.164  christos 	}
   3974  1.164  christos 
   3975  1.164  christos 	if (rval != 0) {
   3976  1.164  christos 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
   3977  1.164  christos 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
   3978  1.164  christos 		}
   3979  1.164  christos 		pamh = NULL;
   3980  1.164  christos 	}
   3981  1.164  christos 	return rval;
   3982  1.164  christos }
   3983  1.164  christos 
   3984  1.164  christos #endif /* USE_PAM */
   3985