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