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