ftpd.c revision 1.174 1 /* $NetBSD: ftpd.c,v 1.174 2006/03/17 21:26:55 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.174 2006/03/17 21:26:55 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 file = NULL;
1984 data = -1;
1985 if (conerrno == EADDRINUSE) {
1986 sleep((unsigned) swaitint);
1987 retry += swaitint;
1988 } else {
1989 break;
1990 }
1991 } while (retry <= swaitmax);
1992 if (conerrno != 0) {
1993 perror_reply(425, "Can't build data connection");
1994 return (NULL);
1995 }
1996 reply(150, "Opening %s mode data connection for '%s'%s.",
1997 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1998 return (file);
1999 }
2000
2001 void
2002 closedataconn(FILE *fd)
2003 {
2004
2005 if (fd == NULL)
2006 return;
2007 (void)fclose(fd);
2008 data = -1;
2009 if (pdata >= 0)
2010 (void)close(pdata);
2011 pdata = -1;
2012 }
2013
2014 int
2015 write_data(int fd, char *buf, size_t size, off_t *bufrem,
2016 struct timeval *then, int isdata)
2017 {
2018 struct timeval now, td;
2019 ssize_t c;
2020
2021 while (size > 0) {
2022 c = size;
2023 if (curclass.writesize) {
2024 if (curclass.writesize < c)
2025 c = curclass.writesize;
2026 }
2027 if (curclass.rateget) {
2028 if (*bufrem < c)
2029 c = *bufrem;
2030 }
2031 (void) alarm(curclass.timeout);
2032 c = write(fd, buf, c);
2033 if (c <= 0)
2034 return (1);
2035 buf += c;
2036 size -= c;
2037 byte_count += c;
2038 if (isdata) {
2039 total_data_out += c;
2040 total_data += c;
2041 }
2042 total_bytes_out += c;
2043 total_bytes += c;
2044 if (curclass.rateget) {
2045 *bufrem -= c;
2046 if (*bufrem == 0) {
2047 (void)gettimeofday(&now, NULL);
2048 timersub(&now, then, &td);
2049 if (td.tv_sec == 0) {
2050 usleep(1000000 - td.tv_usec);
2051 (void)gettimeofday(then, NULL);
2052 } else
2053 *then = now;
2054 *bufrem = curclass.rateget;
2055 }
2056 }
2057 }
2058 return (0);
2059 }
2060
2061 static enum send_status
2062 send_data_with_read(int filefd, int netfd, const struct stat *st, int isdata)
2063 {
2064 struct timeval then;
2065 off_t bufrem;
2066 size_t readsize;
2067 char *buf;
2068 int c, error;
2069
2070 if (curclass.readsize)
2071 readsize = curclass.readsize;
2072 else
2073 readsize = (size_t)st->st_blksize;
2074 if ((buf = malloc(readsize)) == NULL) {
2075 perror_reply(451, "Local resource failure: malloc");
2076 return (SS_NO_TRANSFER);
2077 }
2078
2079 if (curclass.rateget) {
2080 bufrem = curclass.rateget;
2081 (void)gettimeofday(&then, NULL);
2082 }
2083 while (1) {
2084 (void) alarm(curclass.timeout);
2085 c = read(filefd, buf, readsize);
2086 if (c == 0)
2087 error = SS_SUCCESS;
2088 else if (c < 0)
2089 error = SS_FILE_ERROR;
2090 else if (write_data(netfd, buf, c, &bufrem, &then, isdata))
2091 error = SS_DATA_ERROR;
2092 else if (urgflag && handleoobcmd())
2093 error = SS_ABORTED;
2094 else
2095 continue;
2096
2097 free(buf);
2098 return (error);
2099 }
2100 }
2101
2102 static enum send_status
2103 send_data_with_mmap(int filefd, int netfd, const struct stat *st, int isdata)
2104 {
2105 struct timeval then;
2106 off_t bufrem, filesize, off, origoff;
2107 size_t mapsize, winsize;
2108 int error, sendbufsize, sendlowat;
2109 void *win;
2110
2111 if (curclass.sendbufsize) {
2112 sendbufsize = curclass.sendbufsize;
2113 if (setsockopt(netfd, SOL_SOCKET, SO_SNDBUF,
2114 &sendbufsize, sizeof(int)) == -1)
2115 syslog(LOG_WARNING, "setsockopt(SO_SNDBUF, %d): %m",
2116 sendbufsize);
2117 }
2118
2119 if (curclass.sendlowat) {
2120 sendlowat = curclass.sendlowat;
2121 if (setsockopt(netfd, SOL_SOCKET, SO_SNDLOWAT,
2122 &sendlowat, sizeof(int)) == -1)
2123 syslog(LOG_WARNING, "setsockopt(SO_SNDLOWAT, %d): %m",
2124 sendlowat);
2125 }
2126
2127 winsize = curclass.mmapsize;
2128 filesize = st->st_size;
2129 if (ftpd_debug)
2130 syslog(LOG_INFO, "mmapsize = %ld, writesize = %ld",
2131 (long)winsize, (long)curclass.writesize);
2132 if (winsize == 0)
2133 goto try_read;
2134
2135 off = lseek(filefd, (off_t)0, SEEK_CUR);
2136 if (off == -1)
2137 goto try_read;
2138
2139 origoff = off;
2140 if (curclass.rateget) {
2141 bufrem = curclass.rateget;
2142 (void)gettimeofday(&then, NULL);
2143 }
2144 while (1) {
2145 mapsize = MIN(filesize - off, winsize);
2146 if (mapsize == 0)
2147 break;
2148 win = mmap(NULL, mapsize, PROT_READ,
2149 MAP_FILE|MAP_SHARED, filefd, off);
2150 if (win == MAP_FAILED) {
2151 if (off == origoff)
2152 goto try_read;
2153 return (SS_FILE_ERROR);
2154 }
2155 (void) madvise(win, mapsize, MADV_SEQUENTIAL);
2156 error = write_data(netfd, win, mapsize, &bufrem, &then,
2157 isdata);
2158 (void) madvise(win, mapsize, MADV_DONTNEED);
2159 munmap(win, mapsize);
2160 if (urgflag && handleoobcmd())
2161 return (SS_ABORTED);
2162 if (error)
2163 return (SS_DATA_ERROR);
2164 off += mapsize;
2165 }
2166 return (SS_SUCCESS);
2167
2168 try_read:
2169 return (send_data_with_read(filefd, netfd, st, isdata));
2170 }
2171
2172 /*
2173 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
2174 * encapsulation of the data subject to Mode, Structure, and Type.
2175 *
2176 * NB: Form isn't handled.
2177 */
2178 static int
2179 send_data(FILE *instr, FILE *outstr, const struct stat *st, int isdata)
2180 {
2181 int c, filefd, netfd, rval;
2182
2183 urgflag = 0;
2184 transflag = 1;
2185 rval = -1;
2186
2187 switch (type) {
2188
2189 case TYPE_A:
2190 /* XXXLUKEM: rate limit ascii send (get) */
2191 (void) alarm(curclass.timeout);
2192 while ((c = getc(instr)) != EOF) {
2193 if (urgflag && handleoobcmd())
2194 goto cleanup_send_data;
2195 byte_count++;
2196 if (c == '\n') {
2197 if (ferror(outstr))
2198 goto data_err;
2199 (void) putc('\r', outstr);
2200 if (isdata) {
2201 total_data_out++;
2202 total_data++;
2203 }
2204 total_bytes_out++;
2205 total_bytes++;
2206 }
2207 (void) putc(c, outstr);
2208 if (isdata) {
2209 total_data_out++;
2210 total_data++;
2211 }
2212 total_bytes_out++;
2213 total_bytes++;
2214 if ((byte_count % 4096) == 0)
2215 (void) alarm(curclass.timeout);
2216 }
2217 (void) alarm(0);
2218 fflush(outstr);
2219 if (ferror(instr))
2220 goto file_err;
2221 if (ferror(outstr))
2222 goto data_err;
2223 rval = 0;
2224 goto cleanup_send_data;
2225
2226 case TYPE_I:
2227 case TYPE_L:
2228 filefd = fileno(instr);
2229 netfd = fileno(outstr);
2230 switch (send_data_with_mmap(filefd, netfd, st, isdata)) {
2231
2232 case SS_SUCCESS:
2233 break;
2234
2235 case SS_ABORTED:
2236 case SS_NO_TRANSFER:
2237 goto cleanup_send_data;
2238
2239 case SS_FILE_ERROR:
2240 goto file_err;
2241
2242 case SS_DATA_ERROR:
2243 goto data_err;
2244 }
2245 rval = 0;
2246 goto cleanup_send_data;
2247
2248 default:
2249 reply(550, "Unimplemented TYPE %d in send_data", type);
2250 goto cleanup_send_data;
2251 }
2252
2253 data_err:
2254 (void) alarm(0);
2255 perror_reply(426, "Data connection");
2256 goto cleanup_send_data;
2257
2258 file_err:
2259 (void) alarm(0);
2260 perror_reply(551, "Error on input file");
2261 goto cleanup_send_data;
2262
2263 cleanup_send_data:
2264 (void) alarm(0);
2265 transflag = 0;
2266 urgflag = 0;
2267 if (isdata) {
2268 total_files_out++;
2269 total_files++;
2270 }
2271 total_xfers_out++;
2272 total_xfers++;
2273 return (rval);
2274 }
2275
2276 /*
2277 * Transfer data from peer to "outstr" using the appropriate encapulation of
2278 * the data subject to Mode, Structure, and Type.
2279 *
2280 * N.B.: Form isn't handled.
2281 */
2282 static int
2283 receive_data(FILE *instr, FILE *outstr)
2284 {
2285 int c, bare_lfs, netfd, filefd, rval;
2286 off_t byteswritten;
2287 char *buf;
2288 size_t readsize;
2289 struct sigaction sa, sa_saved;
2290 struct stat st;
2291 #ifdef __GNUC__
2292 (void) &bare_lfs;
2293 #endif
2294
2295 memset(&sa, 0, sizeof(sa));
2296 sigfillset(&sa.sa_mask);
2297 sa.sa_flags = SA_RESTART;
2298 sa.sa_handler = lostconn;
2299 (void) sigaction(SIGALRM, &sa, &sa_saved);
2300
2301 bare_lfs = 0;
2302 urgflag = 0;
2303 transflag = 1;
2304 rval = -1;
2305 byteswritten = 0;
2306 buf = NULL;
2307
2308 #define FILESIZECHECK(x) \
2309 do { \
2310 if (curclass.maxfilesize != -1 && \
2311 (x) > curclass.maxfilesize) { \
2312 errno = EFBIG; \
2313 goto file_err; \
2314 } \
2315 } while (0)
2316
2317 switch (type) {
2318
2319 case TYPE_I:
2320 case TYPE_L:
2321 netfd = fileno(instr);
2322 filefd = fileno(outstr);
2323 (void) alarm(curclass.timeout);
2324 if (curclass.readsize)
2325 readsize = curclass.readsize;
2326 else if (fstat(filefd, &st))
2327 readsize = (size_t)st.st_blksize;
2328 else
2329 readsize = BUFSIZ;
2330 if ((buf = malloc(readsize)) == NULL) {
2331 perror_reply(451, "Local resource failure: malloc");
2332 goto cleanup_recv_data;
2333 }
2334 if (curclass.rateput) {
2335 while (1) {
2336 int d;
2337 struct timeval then, now, td;
2338 off_t bufrem;
2339
2340 (void)gettimeofday(&then, NULL);
2341 errno = c = d = 0;
2342 for (bufrem = curclass.rateput; bufrem > 0; ) {
2343 if ((c = read(netfd, buf,
2344 MIN(readsize, bufrem))) <= 0)
2345 goto recvdone;
2346 if (urgflag && handleoobcmd())
2347 goto cleanup_recv_data;
2348 FILESIZECHECK(byte_count + c);
2349 if ((d = write(filefd, buf, c)) != c)
2350 goto file_err;
2351 (void) alarm(curclass.timeout);
2352 bufrem -= c;
2353 byte_count += c;
2354 total_data_in += c;
2355 total_data += c;
2356 total_bytes_in += c;
2357 total_bytes += c;
2358 }
2359 (void)gettimeofday(&now, NULL);
2360 timersub(&now, &then, &td);
2361 if (td.tv_sec == 0)
2362 usleep(1000000 - td.tv_usec);
2363 }
2364 } else {
2365 while ((c = read(netfd, buf, readsize)) > 0) {
2366 if (urgflag && handleoobcmd())
2367 goto cleanup_recv_data;
2368 FILESIZECHECK(byte_count + c);
2369 if (write(filefd, buf, c) != c)
2370 goto file_err;
2371 (void) alarm(curclass.timeout);
2372 byte_count += c;
2373 total_data_in += c;
2374 total_data += c;
2375 total_bytes_in += c;
2376 total_bytes += c;
2377 }
2378 }
2379 recvdone:
2380 if (c < 0)
2381 goto data_err;
2382 rval = 0;
2383 goto cleanup_recv_data;
2384
2385 case TYPE_E:
2386 reply(553, "TYPE E not implemented.");
2387 goto cleanup_recv_data;
2388
2389 case TYPE_A:
2390 (void) alarm(curclass.timeout);
2391 /* XXXLUKEM: rate limit ascii receive (put) */
2392 while ((c = getc(instr)) != EOF) {
2393 if (urgflag && handleoobcmd())
2394 goto cleanup_recv_data;
2395 byte_count++;
2396 total_data_in++;
2397 total_data++;
2398 total_bytes_in++;
2399 total_bytes++;
2400 if ((byte_count % 4096) == 0)
2401 (void) alarm(curclass.timeout);
2402 if (c == '\n')
2403 bare_lfs++;
2404 while (c == '\r') {
2405 if (ferror(outstr))
2406 goto data_err;
2407 if ((c = getc(instr)) != '\n') {
2408 byte_count++;
2409 total_data_in++;
2410 total_data++;
2411 total_bytes_in++;
2412 total_bytes++;
2413 if ((byte_count % 4096) == 0)
2414 (void) alarm(curclass.timeout);
2415 byteswritten++;
2416 FILESIZECHECK(byteswritten);
2417 (void) putc ('\r', outstr);
2418 if (c == '\0' || c == EOF)
2419 goto contin2;
2420 }
2421 }
2422 byteswritten++;
2423 FILESIZECHECK(byteswritten);
2424 (void) putc(c, outstr);
2425 contin2: ;
2426 }
2427 (void) alarm(0);
2428 fflush(outstr);
2429 if (ferror(instr))
2430 goto data_err;
2431 if (ferror(outstr))
2432 goto file_err;
2433 if (bare_lfs) {
2434 reply(-226,
2435 "WARNING! %d bare linefeeds received in ASCII mode",
2436 bare_lfs);
2437 reply(0, "File may not have transferred correctly.");
2438 }
2439 rval = 0;
2440 goto cleanup_recv_data;
2441
2442 default:
2443 reply(550, "Unimplemented TYPE %d in receive_data", type);
2444 goto cleanup_recv_data;
2445 }
2446 #undef FILESIZECHECK
2447
2448 data_err:
2449 (void) alarm(0);
2450 perror_reply(426, "Data Connection");
2451 goto cleanup_recv_data;
2452
2453 file_err:
2454 (void) alarm(0);
2455 perror_reply(452, "Error writing file");
2456 goto cleanup_recv_data;
2457
2458 cleanup_recv_data:
2459 (void) alarm(0);
2460 (void) sigaction(SIGALRM, &sa_saved, NULL);
2461 if (buf)
2462 free(buf);
2463 transflag = 0;
2464 urgflag = 0;
2465 total_files_in++;
2466 total_files++;
2467 total_xfers_in++;
2468 total_xfers++;
2469 return (rval);
2470 }
2471
2472 void
2473 statcmd(void)
2474 {
2475 struct sockinet *su = NULL;
2476 static char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
2477 u_char *a, *p;
2478 int ispassive, af;
2479 off_t otbi, otbo, otb;
2480
2481 a = p = (u_char *)NULL;
2482
2483 reply(-211, "%s FTP server status:", hostname);
2484 reply(0, "Version: %s", EMPTYSTR(version) ? "<suppressed>" : version);
2485 hbuf[0] = '\0';
2486 if (!getnameinfo((struct sockaddr *)&his_addr.si_su, his_addr.su_len,
2487 hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST)
2488 && strcmp(remotehost, hbuf) != 0)
2489 reply(0, "Connected to %s (%s)", remotehost, hbuf);
2490 else
2491 reply(0, "Connected to %s", remotehost);
2492
2493 if (logged_in) {
2494 if (curclass.type == CLASS_GUEST)
2495 reply(0, "Logged in anonymously");
2496 else
2497 reply(0, "Logged in as %s%s", pw->pw_name,
2498 curclass.type == CLASS_CHROOT ? " (chroot)" : "");
2499 } else if (askpasswd)
2500 reply(0, "Waiting for password");
2501 else
2502 reply(0, "Waiting for user name");
2503 cprintf(stdout, " TYPE: %s", typenames[type]);
2504 if (type == TYPE_A || type == TYPE_E)
2505 cprintf(stdout, ", FORM: %s", formnames[form]);
2506 if (type == TYPE_L) {
2507 #if NBBY == 8
2508 cprintf(stdout, " %d", NBBY);
2509 #else
2510 /* XXX: `bytesize' needs to be defined in this case */
2511 cprintf(stdout, " %d", bytesize);
2512 #endif
2513 }
2514 cprintf(stdout, "; STRUcture: %s; transfer MODE: %s\r\n",
2515 strunames[stru], modenames[mode]);
2516 ispassive = 0;
2517 if (data != -1) {
2518 reply(0, "Data connection open");
2519 su = NULL;
2520 } else if (pdata != -1) {
2521 reply(0, "in Passive mode");
2522 if (curclass.advertise.su_len != 0)
2523 su = &curclass.advertise;
2524 else
2525 su = &pasv_addr;
2526 ispassive = 1;
2527 goto printaddr;
2528 } else if (usedefault == 0) {
2529 su = (struct sockinet *)&data_dest;
2530
2531 if (epsvall) {
2532 reply(0, "EPSV only mode (EPSV ALL)");
2533 goto epsvonly;
2534 }
2535 printaddr:
2536 /* PASV/PORT */
2537 if (su->su_family == AF_INET) {
2538 a = (u_char *) &su->su_addr;
2539 p = (u_char *) &su->su_port;
2540 #define UC(b) (((int) b) & 0xff)
2541 reply(0, "%s (%d,%d,%d,%d,%d,%d)",
2542 ispassive ? "PASV" : "PORT" ,
2543 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2544 UC(p[0]), UC(p[1]));
2545 }
2546
2547 /* LPSV/LPRT */
2548 {
2549 int alen, i;
2550
2551 alen = 0;
2552 switch (su->su_family) {
2553 case AF_INET:
2554 a = (u_char *) &su->su_addr;
2555 p = (u_char *) &su->su_port;
2556 alen = sizeof(su->su_addr);
2557 af = 4;
2558 break;
2559 #ifdef INET6
2560 case AF_INET6:
2561 a = (u_char *) &su->su_6addr;
2562 p = (u_char *) &su->su_port;
2563 alen = sizeof(su->su_6addr);
2564 af = 6;
2565 break;
2566 #endif
2567 default:
2568 af = 0;
2569 break;
2570 }
2571 if (af) {
2572 cprintf(stdout, " %s (%d,%d",
2573 ispassive ? "LPSV" : "LPRT", af, alen);
2574 for (i = 0; i < alen; i++)
2575 cprintf(stdout, ",%d", UC(a[i]));
2576 cprintf(stdout, ",%d,%d,%d)\r\n",
2577 2, UC(p[0]), UC(p[1]));
2578 #undef UC
2579 }
2580 }
2581
2582 /* EPRT/EPSV */
2583 epsvonly:
2584 af = af2epsvproto(su->su_family);
2585 hbuf[0] = '\0';
2586 if (af > 0) {
2587 struct sockinet tmp;
2588
2589 tmp = *su;
2590 #ifdef INET6
2591 if (tmp.su_family == AF_INET6)
2592 tmp.su_scope_id = 0;
2593 #endif
2594 if (getnameinfo((struct sockaddr *)&tmp.si_su,
2595 tmp.su_len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
2596 NI_NUMERICHOST | NI_NUMERICSERV) == 0)
2597 reply(0, "%s (|%d|%s|%s|)",
2598 ispassive ? "EPSV" : "EPRT",
2599 af, hbuf, sbuf);
2600 }
2601 } else
2602 reply(0, "No data connection");
2603
2604 if (logged_in) {
2605 reply(0,
2606 "Data sent: " LLF " byte%s in " LLF " file%s",
2607 (LLT)total_data_out, PLURAL(total_data_out),
2608 (LLT)total_files_out, PLURAL(total_files_out));
2609 reply(0,
2610 "Data received: " LLF " byte%s in " LLF " file%s",
2611 (LLT)total_data_in, PLURAL(total_data_in),
2612 (LLT)total_files_in, PLURAL(total_files_in));
2613 reply(0,
2614 "Total data: " LLF " byte%s in " LLF " file%s",
2615 (LLT)total_data, PLURAL(total_data),
2616 (LLT)total_files, PLURAL(total_files));
2617 }
2618 otbi = total_bytes_in;
2619 otbo = total_bytes_out;
2620 otb = total_bytes;
2621 reply(0, "Traffic sent: " LLF " byte%s in " LLF " transfer%s",
2622 (LLT)otbo, PLURAL(otbo),
2623 (LLT)total_xfers_out, PLURAL(total_xfers_out));
2624 reply(0, "Traffic received: " LLF " byte%s in " LLF " transfer%s",
2625 (LLT)otbi, PLURAL(otbi),
2626 (LLT)total_xfers_in, PLURAL(total_xfers_in));
2627 reply(0, "Total traffic: " LLF " byte%s in " LLF " transfer%s",
2628 (LLT)otb, PLURAL(otb),
2629 (LLT)total_xfers, PLURAL(total_xfers));
2630
2631 if (logged_in && !CURCLASS_FLAGS_ISSET(private)) {
2632 struct ftpconv *cp;
2633
2634 reply(0, "%s", "");
2635 reply(0, "Class: %s, type: %s",
2636 curclass.classname, CURCLASSTYPE);
2637 reply(0, "Check PORT/LPRT commands: %sabled",
2638 CURCLASS_FLAGS_ISSET(checkportcmd) ? "en" : "dis");
2639 if (! EMPTYSTR(curclass.display))
2640 reply(0, "Display file: %s", curclass.display);
2641 if (! EMPTYSTR(curclass.notify))
2642 reply(0, "Notify fileglob: %s", curclass.notify);
2643 reply(0, "Idle timeout: " LLF ", maximum timeout: " LLF,
2644 (LLT)curclass.timeout, (LLT)curclass.maxtimeout);
2645 reply(0, "Current connections: %d", connections);
2646 if (curclass.limit == -1)
2647 reply(0, "Maximum connections: unlimited");
2648 else
2649 reply(0, "Maximum connections: " LLF,
2650 (LLT)curclass.limit);
2651 if (curclass.limitfile)
2652 reply(0, "Connection limit exceeded message file: %s",
2653 conffilename(curclass.limitfile));
2654 if (! EMPTYSTR(curclass.chroot))
2655 reply(0, "Chroot format: %s", curclass.chroot);
2656 reply(0, "Deny bad ftpusers(5) quickly: %sabled",
2657 CURCLASS_FLAGS_ISSET(denyquick) ? "en" : "dis");
2658 if (! EMPTYSTR(curclass.homedir))
2659 reply(0, "Homedir format: %s", curclass.homedir);
2660 if (curclass.maxfilesize == -1)
2661 reply(0, "Maximum file size: unlimited");
2662 else
2663 reply(0, "Maximum file size: " LLF,
2664 (LLT)curclass.maxfilesize);
2665 if (! EMPTYSTR(curclass.motd))
2666 reply(0, "MotD file: %s", conffilename(curclass.motd));
2667 reply(0,
2668 "Modify commands (CHMOD, DELE, MKD, RMD, RNFR, UMASK): %sabled",
2669 CURCLASS_FLAGS_ISSET(modify) ? "en" : "dis");
2670 reply(0, "Upload commands (APPE, STOR, STOU): %sabled",
2671 CURCLASS_FLAGS_ISSET(upload) ? "en" : "dis");
2672 reply(0, "Sanitize file names: %sabled",
2673 CURCLASS_FLAGS_ISSET(sanenames) ? "en" : "dis");
2674 reply(0, "PASV/LPSV/EPSV connections: %sabled",
2675 CURCLASS_FLAGS_ISSET(passive) ? "en" : "dis");
2676 if (curclass.advertise.su_len != 0) {
2677 char buf[50]; /* big enough for IPv6 address */
2678 const char *bp;
2679
2680 bp = inet_ntop(curclass.advertise.su_family,
2681 (void *)&curclass.advertise.su_addr,
2682 buf, sizeof(buf));
2683 if (bp != NULL)
2684 reply(0, "PASV advertise address: %s", bp);
2685 }
2686 if (curclass.portmin && curclass.portmax)
2687 reply(0, "PASV port range: " LLF " - " LLF,
2688 (LLT)curclass.portmin, (LLT)curclass.portmax);
2689 if (curclass.rateget)
2690 reply(0, "Rate get limit: " LLF " bytes/sec",
2691 (LLT)curclass.rateget);
2692 else
2693 reply(0, "Rate get limit: disabled");
2694 if (curclass.rateput)
2695 reply(0, "Rate put limit: " LLF " bytes/sec",
2696 (LLT)curclass.rateput);
2697 else
2698 reply(0, "Rate put limit: disabled");
2699 if (curclass.mmapsize)
2700 reply(0, "Mmap size: " LLF, (LLT)curclass.mmapsize);
2701 else
2702 reply(0, "Mmap size: disabled");
2703 if (curclass.readsize)
2704 reply(0, "Read size: " LLF, (LLT)curclass.readsize);
2705 else
2706 reply(0, "Read size: default");
2707 if (curclass.writesize)
2708 reply(0, "Write size: " LLF, (LLT)curclass.writesize);
2709 else
2710 reply(0, "Write size: default");
2711 if (curclass.recvbufsize)
2712 reply(0, "Receive buffer size: " LLF,
2713 (LLT)curclass.recvbufsize);
2714 else
2715 reply(0, "Receive buffer size: default");
2716 if (curclass.sendbufsize)
2717 reply(0, "Send buffer size: " LLF,
2718 (LLT)curclass.sendbufsize);
2719 else
2720 reply(0, "Send buffer size: default");
2721 if (curclass.sendlowat)
2722 reply(0, "Send low water mark: " LLF,
2723 (LLT)curclass.sendlowat);
2724 else
2725 reply(0, "Send low water mark: default");
2726 reply(0, "Umask: %.04o", curclass.umask);
2727 for (cp = curclass.conversions; cp != NULL; cp=cp->next) {
2728 if (cp->suffix == NULL || cp->types == NULL ||
2729 cp->command == NULL)
2730 continue;
2731 reply(0, "Conversion: %s [%s] disable: %s, command: %s",
2732 cp->suffix, cp->types, cp->disable, cp->command);
2733 }
2734 }
2735
2736 reply(211, "End of status");
2737 }
2738
2739 void
2740 fatal(const char *s)
2741 {
2742
2743 reply(451, "Error in server: %s\n", s);
2744 reply(221, "Closing connection due to server error.");
2745 dologout(0);
2746 /* NOTREACHED */
2747 }
2748
2749 /*
2750 * reply() --
2751 * depending on the value of n, display fmt with a trailing CRLF and
2752 * prefix of:
2753 * n < -1 prefix the message with abs(n) + "-" (initial line)
2754 * n == 0 prefix the message with 4 spaces (middle lines)
2755 * n > 0 prefix the message with n + " " (final line)
2756 */
2757 void
2758 reply(int n, const char *fmt, ...)
2759 {
2760 char msg[MAXPATHLEN * 2 + 100];
2761 size_t b;
2762 va_list ap;
2763
2764 b = 0;
2765 if (n == 0)
2766 b = snprintf(msg, sizeof(msg), " ");
2767 else if (n < 0)
2768 b = snprintf(msg, sizeof(msg), "%d-", -n);
2769 else
2770 b = snprintf(msg, sizeof(msg), "%d ", n);
2771 va_start(ap, fmt);
2772 vsnprintf(msg + b, sizeof(msg) - b, fmt, ap);
2773 va_end(ap);
2774 cprintf(stdout, "%s\r\n", msg);
2775 (void)fflush(stdout);
2776 if (ftpd_debug)
2777 syslog(LOG_DEBUG, "<--- %s", msg);
2778 }
2779
2780 static void
2781 logremotehost(struct sockinet *who)
2782 {
2783
2784 if (getnameinfo((struct sockaddr *)&who->si_su,
2785 who->su_len, remotehost, sizeof(remotehost), NULL, 0, 0))
2786 strlcpy(remotehost, "?", sizeof(remotehost));
2787
2788 #if HAVE_SETPROCTITLE
2789 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
2790 setproctitle("%s", proctitle);
2791 #endif /* HAVE_SETPROCTITLE */
2792 if (logging)
2793 syslog(LOG_INFO, "connection from %s to %s",
2794 remotehost, hostname);
2795 }
2796
2797 /*
2798 * Record logout in wtmp file and exit with supplied status.
2799 * NOTE: because this is called from signal handlers it cannot
2800 * use stdio (or call other functions that use stdio).
2801 */
2802 void
2803 dologout(int status)
2804 {
2805 /*
2806 * Prevent reception of SIGURG from resulting in a resumption
2807 * back to the main program loop.
2808 */
2809 transflag = 0;
2810 logout_utmp();
2811 if (logged_in) {
2812 #ifdef KERBEROS
2813 if (!notickets && krbtkfile_env)
2814 unlink(krbtkfile_env);
2815 #endif
2816 }
2817 /* beware of flushing buffers after a SIGPIPE */
2818 if (xferlogfd != -1)
2819 close(xferlogfd);
2820 _exit(status);
2821 }
2822
2823 void
2824 abor(void)
2825 {
2826
2827 if (!transflag)
2828 return;
2829 tmpline[0] = '\0';
2830 is_oob = 0;
2831 reply(426, "Transfer aborted. Data connection closed.");
2832 reply(226, "Abort successful");
2833 transflag = 0; /* flag that the transfer has aborted */
2834 }
2835
2836 void
2837 statxfer(void)
2838 {
2839
2840 if (!transflag)
2841 return;
2842 tmpline[0] = '\0';
2843 is_oob = 0;
2844 if (file_size != (off_t) -1)
2845 reply(213,
2846 "Status: " LLF " of " LLF " byte%s transferred",
2847 (LLT)byte_count, (LLT)file_size,
2848 PLURAL(byte_count));
2849 else
2850 reply(213, "Status: " LLF " byte%s transferred",
2851 (LLT)byte_count, PLURAL(byte_count));
2852 }
2853
2854 /*
2855 * Call when urgflag != 0 to handle Out Of Band commands.
2856 * Returns non zero if the OOB command aborted the transfer
2857 * by setting transflag to 0. (c.f., "ABOR").
2858 */
2859 static int
2860 handleoobcmd()
2861 {
2862 char *cp;
2863
2864 if (!urgflag)
2865 return (0);
2866 urgflag = 0;
2867 /* only process if transfer occurring */
2868 if (!transflag)
2869 return (0);
2870 cp = tmpline;
2871 if (getline(cp, sizeof(tmpline), stdin) == NULL) {
2872 reply(221, "You could at least say goodbye.");
2873 dologout(0);
2874 }
2875 /*
2876 * Manually parse OOB commands, because we can't
2877 * recursively call the yacc parser...
2878 */
2879 if (strcasecmp(cp, "ABOR\r\n") == 0) {
2880 abor();
2881 } else if (strcasecmp(cp, "STAT\r\n") == 0) {
2882 statxfer();
2883 } else {
2884 /* XXX: error with "500 unknown command" ? */
2885 }
2886 return (transflag == 0);
2887 }
2888
2889 static int
2890 bind_pasv_addr(void)
2891 {
2892 static int passiveport;
2893 int port, len;
2894
2895 len = pasv_addr.su_len;
2896 if (curclass.portmin == 0 && curclass.portmax == 0) {
2897 pasv_addr.su_port = 0;
2898 return (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len));
2899 }
2900
2901 if (passiveport == 0) {
2902 srand(getpid());
2903 passiveport = rand() % (curclass.portmax - curclass.portmin)
2904 + curclass.portmin;
2905 }
2906
2907 port = passiveport;
2908 while (1) {
2909 port++;
2910 if (port > curclass.portmax)
2911 port = curclass.portmin;
2912 else if (port == passiveport) {
2913 errno = EAGAIN;
2914 return (-1);
2915 }
2916 pasv_addr.su_port = htons(port);
2917 if (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len) == 0)
2918 break;
2919 if (errno != EADDRINUSE)
2920 return (-1);
2921 }
2922 passiveport = port;
2923 return (0);
2924 }
2925
2926 /*
2927 * Note: a response of 425 is not mentioned as a possible response to
2928 * the PASV command in RFC959. However, it has been blessed as
2929 * a legitimate response by Jon Postel in a telephone conversation
2930 * with Rick Adams on 25 Jan 89.
2931 */
2932 void
2933 passive(void)
2934 {
2935 int len, recvbufsize;
2936 char *p, *a;
2937
2938 if (pdata >= 0)
2939 close(pdata);
2940 pdata = socket(AF_INET, SOCK_STREAM, 0);
2941 if (pdata < 0 || !logged_in) {
2942 perror_reply(425, "Can't open passive connection");
2943 return;
2944 }
2945 pasv_addr = ctrl_addr;
2946
2947 if (bind_pasv_addr() < 0)
2948 goto pasv_error;
2949 len = pasv_addr.su_len;
2950 if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
2951 goto pasv_error;
2952 pasv_addr.su_len = len;
2953 if (curclass.recvbufsize) {
2954 recvbufsize = curclass.recvbufsize;
2955 if (setsockopt(pdata, SOL_SOCKET, SO_RCVBUF, &recvbufsize,
2956 sizeof(int)) == -1)
2957 syslog(LOG_WARNING, "setsockopt(SO_RCVBUF, %d): %m",
2958 recvbufsize);
2959 }
2960 if (listen(pdata, 1) < 0)
2961 goto pasv_error;
2962 if (curclass.advertise.su_len != 0)
2963 a = (char *) &curclass.advertise.su_addr;
2964 else
2965 a = (char *) &pasv_addr.su_addr;
2966 p = (char *) &pasv_addr.su_port;
2967
2968 #define UC(b) (((int) b) & 0xff)
2969
2970 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2971 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2972 return;
2973
2974 pasv_error:
2975 (void) close(pdata);
2976 pdata = -1;
2977 perror_reply(425, "Can't open passive connection");
2978 return;
2979 }
2980
2981 /*
2982 * convert protocol identifier to/from AF
2983 */
2984 int
2985 lpsvproto2af(int proto)
2986 {
2987
2988 switch (proto) {
2989 case 4:
2990 return AF_INET;
2991 #ifdef INET6
2992 case 6:
2993 return AF_INET6;
2994 #endif
2995 default:
2996 return -1;
2997 }
2998 }
2999
3000 int
3001 af2lpsvproto(int af)
3002 {
3003
3004 switch (af) {
3005 case AF_INET:
3006 return 4;
3007 #ifdef INET6
3008 case AF_INET6:
3009 return 6;
3010 #endif
3011 default:
3012 return -1;
3013 }
3014 }
3015
3016 int
3017 epsvproto2af(int proto)
3018 {
3019
3020 switch (proto) {
3021 case 1:
3022 return AF_INET;
3023 #ifdef INET6
3024 case 2:
3025 return AF_INET6;
3026 #endif
3027 default:
3028 return -1;
3029 }
3030 }
3031
3032 int
3033 af2epsvproto(int af)
3034 {
3035
3036 switch (af) {
3037 case AF_INET:
3038 return 1;
3039 #ifdef INET6
3040 case AF_INET6:
3041 return 2;
3042 #endif
3043 default:
3044 return -1;
3045 }
3046 }
3047
3048 /*
3049 * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)
3050 * 229 Entering Extended Passive Mode (|||port|)
3051 */
3052 void
3053 long_passive(char *cmd, int pf)
3054 {
3055 int len;
3056 char *p, *a;
3057
3058 if (!logged_in) {
3059 syslog(LOG_NOTICE, "long passive but not logged in");
3060 reply(503, "Login with USER first.");
3061 return;
3062 }
3063
3064 if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) {
3065 /*
3066 * XXX: only EPRT/EPSV ready clients will understand this
3067 */
3068 if (strcmp(cmd, "EPSV") != 0)
3069 reply(501, "Network protocol mismatch"); /*XXX*/
3070 else
3071 epsv_protounsupp("Network protocol mismatch");
3072
3073 return;
3074 }
3075
3076 if (pdata >= 0)
3077 close(pdata);
3078 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
3079 if (pdata < 0) {
3080 perror_reply(425, "Can't open passive connection");
3081 return;
3082 }
3083 pasv_addr = ctrl_addr;
3084 if (bind_pasv_addr() < 0)
3085 goto pasv_error;
3086 len = pasv_addr.su_len;
3087 if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
3088 goto pasv_error;
3089 pasv_addr.su_len = len;
3090 if (listen(pdata, 1) < 0)
3091 goto pasv_error;
3092 p = (char *) &pasv_addr.su_port;
3093
3094 #define UC(b) (((int) b) & 0xff)
3095
3096 if (strcmp(cmd, "LPSV") == 0) {
3097 struct sockinet *advert;
3098
3099 if (curclass.advertise.su_len != 0)
3100 advert = &curclass.advertise;
3101 else
3102 advert = &pasv_addr;
3103 switch (advert->su_family) {
3104 case AF_INET:
3105 a = (char *) &advert->su_addr;
3106 reply(228,
3107 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3108 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3109 2, UC(p[0]), UC(p[1]));
3110 return;
3111 #ifdef INET6
3112 case AF_INET6:
3113 a = (char *) &advert->su_6addr;
3114 reply(228,
3115 "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)",
3116 6, 16,
3117 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3118 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3119 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3120 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3121 2, UC(p[0]), UC(p[1]));
3122 return;
3123 #endif
3124 }
3125 #undef UC
3126 } else if (strcmp(cmd, "EPSV") == 0) {
3127 switch (pasv_addr.su_family) {
3128 case AF_INET:
3129 #ifdef INET6
3130 case AF_INET6:
3131 #endif
3132 reply(229, "Entering Extended Passive Mode (|||%d|)",
3133 ntohs(pasv_addr.su_port));
3134 return;
3135 }
3136 } else {
3137 /* more proper error code? */
3138 }
3139
3140 pasv_error:
3141 (void) close(pdata);
3142 pdata = -1;
3143 perror_reply(425, "Can't open passive connection");
3144 return;
3145 }
3146
3147 int
3148 extended_port(const char *arg)
3149 {
3150 char *tmp = NULL;
3151 char *result[3];
3152 char *p, *q;
3153 char delim;
3154 struct addrinfo hints;
3155 struct addrinfo *res = NULL;
3156 int i;
3157 unsigned long proto;
3158
3159 tmp = ftpd_strdup(arg);
3160 p = tmp;
3161 delim = p[0];
3162 p++;
3163 memset(result, 0, sizeof(result));
3164 for (i = 0; i < 3; i++) {
3165 q = strchr(p, delim);
3166 if (!q || *q != delim)
3167 goto parsefail;
3168 *q++ = '\0';
3169 result[i] = p;
3170 p = q;
3171 }
3172
3173 /* some more sanity checks */
3174 errno = 0;
3175 p = NULL;
3176 (void)strtoul(result[2], &p, 10);
3177 if (errno || !*result[2] || *p)
3178 goto parsefail;
3179 errno = 0;
3180 p = NULL;
3181 proto = strtoul(result[0], &p, 10);
3182 if (errno || !*result[0] || *p)
3183 goto protounsupp;
3184
3185 memset(&hints, 0, sizeof(hints));
3186 hints.ai_family = epsvproto2af((int)proto);
3187 if (hints.ai_family < 0)
3188 goto protounsupp;
3189 hints.ai_socktype = SOCK_STREAM;
3190 hints.ai_flags = AI_NUMERICHOST;
3191 if (getaddrinfo(result[1], result[2], &hints, &res))
3192 goto parsefail;
3193 if (res->ai_next)
3194 goto parsefail;
3195 if (sizeof(data_dest) < res->ai_addrlen)
3196 goto parsefail;
3197 memcpy(&data_dest.si_su, res->ai_addr, res->ai_addrlen);
3198 data_dest.su_len = res->ai_addrlen;
3199 #ifdef INET6
3200 if (his_addr.su_family == AF_INET6 &&
3201 data_dest.su_family == AF_INET6) {
3202 /* XXX: more sanity checks! */
3203 data_dest.su_scope_id = his_addr.su_scope_id;
3204 }
3205 #endif
3206
3207 if (tmp != NULL)
3208 free(tmp);
3209 if (res)
3210 freeaddrinfo(res);
3211 return 0;
3212
3213 parsefail:
3214 reply(500, "Invalid argument, rejected.");
3215 usedefault = 1;
3216 if (tmp != NULL)
3217 free(tmp);
3218 if (res)
3219 freeaddrinfo(res);
3220 return -1;
3221
3222 protounsupp:
3223 epsv_protounsupp("Protocol not supported");
3224 usedefault = 1;
3225 if (tmp != NULL)
3226 free(tmp);
3227 if (res)
3228 freeaddrinfo(res);
3229 return -1;
3230 }
3231
3232 /*
3233 * 522 Protocol not supported (proto,...)
3234 * as we assume address family for control and data connections are the same,
3235 * we do not return the list of address families we support - instead, we
3236 * return the address family of the control connection.
3237 */
3238 void
3239 epsv_protounsupp(const char *message)
3240 {
3241 int proto;
3242
3243 proto = af2epsvproto(ctrl_addr.su_family);
3244 if (proto < 0)
3245 reply(501, "%s", message); /* XXX */
3246 else
3247 reply(522, "%s, use (%d)", message, proto);
3248 }
3249
3250 /*
3251 * Generate unique name for file with basename "local".
3252 * The file named "local" is already known to exist.
3253 * Generates failure reply on error.
3254 *
3255 * XXX: this function should under go changes similar to
3256 * the mktemp(3)/mkstemp(3) changes.
3257 */
3258 static char *
3259 gunique(const char *local)
3260 {
3261 static char new[MAXPATHLEN];
3262 struct stat st;
3263 char *cp;
3264 int count;
3265
3266 cp = strrchr(local, '/');
3267 if (cp)
3268 *cp = '\0';
3269 if (stat(cp ? local : ".", &st) < 0) {
3270 perror_reply(553, cp ? local : ".");
3271 return (NULL);
3272 }
3273 if (cp)
3274 *cp = '/';
3275 for (count = 1; count < 100; count++) {
3276 (void)snprintf(new, sizeof(new) - 1, "%s.%d", local, count);
3277 if (stat(new, &st) < 0)
3278 return (new);
3279 }
3280 reply(452, "Unique file name cannot be created.");
3281 return (NULL);
3282 }
3283
3284 /*
3285 * Format and send reply containing system error number.
3286 */
3287 void
3288 perror_reply(int code, const char *string)
3289 {
3290 int save_errno;
3291
3292 save_errno = errno;
3293 reply(code, "%s: %s.", string, strerror(errno));
3294 errno = save_errno;
3295 }
3296
3297 static char *onefile[] = {
3298 "",
3299 0
3300 };
3301
3302 void
3303 send_file_list(const char *whichf)
3304 {
3305 struct stat st;
3306 DIR *dirp = NULL;
3307 struct dirent *dir;
3308 FILE *dout = NULL;
3309 char **dirlist, *dirname, *p;
3310 char *notglob = NULL;
3311 int simple = 0;
3312 int freeglob = 0;
3313 glob_t gl;
3314
3315 #ifdef __GNUC__
3316 (void) &dout;
3317 (void) &dirlist;
3318 (void) &simple;
3319 (void) &freeglob;
3320 #endif
3321 urgflag = 0;
3322
3323 p = NULL;
3324 if (strpbrk(whichf, "~{[*?") != NULL) {
3325 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE|GLOB_LIMIT;
3326
3327 memset(&gl, 0, sizeof(gl));
3328 freeglob = 1;
3329 if (glob(whichf, flags, 0, &gl)) {
3330 reply(450, "Not found");
3331 goto cleanup_send_file_list;
3332 } else if (gl.gl_pathc == 0) {
3333 errno = ENOENT;
3334 perror_reply(450, whichf);
3335 goto cleanup_send_file_list;
3336 }
3337 dirlist = gl.gl_pathv;
3338 } else {
3339 notglob = ftpd_strdup(whichf);
3340 onefile[0] = notglob;
3341 dirlist = onefile;
3342 simple = 1;
3343 }
3344 /* XXX: } for vi sm */
3345
3346 while ((dirname = *dirlist++) != NULL) {
3347 int trailingslash = 0;
3348
3349 if (stat(dirname, &st) < 0) {
3350 /*
3351 * If user typed "ls -l", etc, and the client
3352 * used NLST, do what the user meant.
3353 */
3354 /* XXX: nuke this support? */
3355 if (dirname[0] == '-' && *dirlist == NULL &&
3356 transflag == 0) {
3357 char *argv[] = { INTERNAL_LS, "", NULL };
3358
3359 argv[1] = dirname;
3360 retrieve(argv, dirname);
3361 goto cleanup_send_file_list;
3362 }
3363 perror_reply(450, whichf);
3364 goto cleanup_send_file_list;
3365 }
3366
3367 if (S_ISREG(st.st_mode)) {
3368 /*
3369 * XXXRFC:
3370 * should we follow RFC959 and not work
3371 * for non directories?
3372 */
3373 if (dout == NULL) {
3374 dout = dataconn("file list", (off_t)-1, "w");
3375 if (dout == NULL)
3376 goto cleanup_send_file_list;
3377 transflag = 1;
3378 }
3379 cprintf(dout, "%s%s\n", dirname,
3380 type == TYPE_A ? "\r" : "");
3381 continue;
3382 } else if (!S_ISDIR(st.st_mode))
3383 continue;
3384
3385 if (dirname[strlen(dirname) - 1] == '/')
3386 trailingslash++;
3387
3388 if ((dirp = opendir(dirname)) == NULL)
3389 continue;
3390
3391 while ((dir = readdir(dirp)) != NULL) {
3392 char nbuf[MAXPATHLEN];
3393
3394 if (urgflag && handleoobcmd())
3395 goto cleanup_send_file_list;
3396
3397 if (ISDOTDIR(dir->d_name) || ISDOTDOTDIR(dir->d_name))
3398 continue;
3399
3400 (void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
3401 trailingslash ? "" : "/", dir->d_name);
3402
3403 /*
3404 * We have to do a stat to ensure it's
3405 * not a directory or special file.
3406 */
3407 /*
3408 * XXXRFC:
3409 * should we follow RFC959 and filter out
3410 * non files ? lukem - NO!, or not until
3411 * our ftp client uses MLS{T,D} for completion.
3412 */
3413 if (simple || (stat(nbuf, &st) == 0 &&
3414 S_ISREG(st.st_mode))) {
3415 if (dout == NULL) {
3416 dout = dataconn("file list", (off_t)-1,
3417 "w");
3418 if (dout == NULL)
3419 goto cleanup_send_file_list;
3420 transflag = 1;
3421 }
3422 p = nbuf;
3423 if (nbuf[0] == '.' && nbuf[1] == '/')
3424 p = &nbuf[2];
3425 cprintf(dout, "%s%s\n", p,
3426 type == TYPE_A ? "\r" : "");
3427 }
3428 }
3429 (void) closedir(dirp);
3430 }
3431
3432 if (dout == NULL)
3433 reply(450, "No files found.");
3434 else if (ferror(dout) != 0)
3435 perror_reply(451, "Data connection");
3436 else
3437 reply(226, "Transfer complete.");
3438
3439 cleanup_send_file_list:
3440 closedataconn(dout);
3441 transflag = 0;
3442 urgflag = 0;
3443 total_xfers++;
3444 total_xfers_out++;
3445 if (notglob)
3446 free(notglob);
3447 if (freeglob)
3448 globfree(&gl);
3449 }
3450
3451 char *
3452 conffilename(const char *s)
3453 {
3454 static char filename[MAXPATHLEN];
3455
3456 if (*s == '/')
3457 strlcpy(filename, s, sizeof(filename));
3458 else
3459 (void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
3460 return (filename);
3461 }
3462
3463 /*
3464 * logxfer --
3465 * if logging > 1, then based on the arguments, syslog a message:
3466 * if bytes != -1 "<command> <file1> = <bytes> bytes"
3467 * else if file2 != NULL "<command> <file1> <file2>"
3468 * else "<command> <file1>"
3469 * if elapsed != NULL, append "in xxx.yyy seconds"
3470 * if error != NULL, append ": " + error
3471 *
3472 * if doxferlog != 0, bytes != -1, and command is "get", "put",
3473 * or "append", syslog and/or write a wu-ftpd style xferlog entry
3474 */
3475 void
3476 logxfer(const char *command, off_t bytes, const char *file1, const char *file2,
3477 const struct timeval *elapsed, const char *error)
3478 {
3479 char buf[MAXPATHLEN * 2 + 100];
3480 char realfile1[MAXPATHLEN], realfile2[MAXPATHLEN];
3481 const char *r1, *r2;
3482 char direction;
3483 size_t len;
3484 time_t now;
3485
3486 if (logging <=1 && !doxferlog)
3487 return;
3488
3489 r1 = r2 = NULL;
3490 if ((r1 = realpath(file1, realfile1)) == NULL)
3491 r1 = file1;
3492 if (file2 != NULL)
3493 if ((r2 = realpath(file2, realfile2)) == NULL)
3494 r2 = file2;
3495
3496 /*
3497 * syslog command
3498 */
3499 if (logging > 1) {
3500 len = snprintf(buf, sizeof(buf), "%s %s", command, r1);
3501 if (bytes != (off_t)-1)
3502 len += snprintf(buf + len, sizeof(buf) - len,
3503 " = " LLF " byte%s", (LLT) bytes, PLURAL(bytes));
3504 else if (r2 != NULL)
3505 len += snprintf(buf + len, sizeof(buf) - len,
3506 " %s", r2);
3507 if (elapsed != NULL)
3508 len += snprintf(buf + len, sizeof(buf) - len,
3509 " in %ld.%.03d seconds", elapsed->tv_sec,
3510 (int)(elapsed->tv_usec / 1000));
3511 if (error != NULL)
3512 len += snprintf(buf + len, sizeof(buf) - len,
3513 ": %s", error);
3514 syslog(LOG_INFO, "%s", buf);
3515 }
3516
3517 /*
3518 * syslog wu-ftpd style log entry, prefixed with "xferlog: "
3519 */
3520 if (!doxferlog || bytes == -1)
3521 return;
3522
3523 if (strcmp(command, "get") == 0)
3524 direction = 'o';
3525 else if (strcmp(command, "put") == 0 || strcmp(command, "append") == 0)
3526 direction = 'i';
3527 else
3528 return;
3529
3530 time(&now);
3531 len = snprintf(buf, sizeof(buf),
3532 "%.24s %ld %s " LLF " %s %c %s %c %c %s FTP 0 * %c\n",
3533
3534 /*
3535 * XXX: wu-ftpd puts ' (send)' or ' (recv)' in the syslog message, and removes
3536 * the full date. This may be problematic for accurate log parsing,
3537 * given that syslog messages don't contain the full date.
3538 */
3539 ctime(&now),
3540 elapsed == NULL ? 0 : elapsed->tv_sec + (elapsed->tv_usec > 0),
3541 remotehost,
3542 (LLT) bytes,
3543 r1,
3544 type == TYPE_A ? 'a' : 'b',
3545 "_", /* XXX: take conversions into account? */
3546 direction,
3547
3548 curclass.type == CLASS_GUEST ? 'a' :
3549 curclass.type == CLASS_CHROOT ? 'g' :
3550 curclass.type == CLASS_REAL ? 'r' : '?',
3551
3552 curclass.type == CLASS_GUEST ? pw->pw_passwd : pw->pw_name,
3553 error != NULL ? 'i' : 'c'
3554 );
3555
3556 if ((doxferlog & 2) && xferlogfd != -1)
3557 write(xferlogfd, buf, len);
3558 if ((doxferlog & 1)) {
3559 buf[len-1] = '\n'; /* strip \n from syslog message */
3560 syslog(LOG_INFO, "xferlog: %s", buf);
3561 }
3562 }
3563
3564 /*
3565 * Log the resource usage.
3566 *
3567 * XXX: more resource usage to logging?
3568 */
3569 void
3570 logrusage(const struct rusage *rusage_before,
3571 const struct rusage *rusage_after)
3572 {
3573 struct timeval usrtime, systime;
3574
3575 if (logging <= 1)
3576 return;
3577
3578 timersub(&rusage_after->ru_utime, &rusage_before->ru_utime, &usrtime);
3579 timersub(&rusage_after->ru_stime, &rusage_before->ru_stime, &systime);
3580 syslog(LOG_INFO, "%ld.%.03du %ld.%.03ds %ld+%ldio %ldpf+%ldw",
3581 usrtime.tv_sec, (int)(usrtime.tv_usec / 1000),
3582 systime.tv_sec, (int)(systime.tv_usec / 1000),
3583 rusage_after->ru_inblock - rusage_before->ru_inblock,
3584 rusage_after->ru_oublock - rusage_before->ru_oublock,
3585 rusage_after->ru_majflt - rusage_before->ru_majflt,
3586 rusage_after->ru_nswap - rusage_before->ru_nswap);
3587 }
3588
3589 /*
3590 * Determine if `password' is valid for user given in `pw'.
3591 * Returns 2 if password expired, 1 if otherwise failed, 0 if ok
3592 */
3593 int
3594 checkpassword(const struct passwd *pwent, const char *password)
3595 {
3596 char *orig, *new;
3597 time_t change, expire, now;
3598
3599 change = expire = 0;
3600 if (pwent == NULL)
3601 return 1;
3602
3603 time(&now);
3604 orig = pwent->pw_passwd; /* save existing password */
3605 expire = pwent->pw_expire;
3606 change = (pwent->pw_change == _PASSWORD_CHGNOW)? now : pwent->pw_change;
3607
3608 if (orig[0] == '\0') /* don't allow empty passwords */
3609 return 1;
3610
3611 new = crypt(password, orig); /* encrypt given password */
3612 if (strcmp(new, orig) != 0) /* compare */
3613 return 1;
3614
3615 if ((expire && now >= expire) || (change && now >= change))
3616 return 2; /* check if expired */
3617
3618 return 0; /* OK! */
3619 }
3620
3621 char *
3622 ftpd_strdup(const char *s)
3623 {
3624 char *new = strdup(s);
3625
3626 if (new == NULL)
3627 fatal("Local resource failure: malloc");
3628 /* NOTREACHED */
3629 return (new);
3630 }
3631
3632 /*
3633 * As per fprintf(), but increment total_bytes and total_bytes_out,
3634 * by the appropriate amount.
3635 */
3636 void
3637 cprintf(FILE *fd, const char *fmt, ...)
3638 {
3639 off_t b;
3640 va_list ap;
3641
3642 va_start(ap, fmt);
3643 b = vfprintf(fd, fmt, ap);
3644 va_end(ap);
3645 total_bytes += b;
3646 total_bytes_out += b;
3647 }
3648
3649 #ifdef USE_PAM
3650 /*
3651 * the following code is stolen from imap-uw PAM authentication module and
3652 * login.c
3653 */
3654 #define COPY_STRING(s) (s ? strdup(s) : NULL)
3655
3656 struct cred_t {
3657 const char *uname; /* user name */
3658 const char *pass; /* password */
3659 };
3660 typedef struct cred_t cred_t;
3661
3662 static int
3663 auth_conv(int num_msg, const struct pam_message **msg,
3664 struct pam_response **resp, void *appdata)
3665 {
3666 int i;
3667 cred_t *cred = (cred_t *) appdata;
3668 struct pam_response *myreply;
3669
3670 myreply = calloc(num_msg, sizeof *myreply);
3671 if (myreply == NULL)
3672 return PAM_BUF_ERR;
3673
3674 for (i = 0; i < num_msg; i++) {
3675 switch (msg[i]->msg_style) {
3676 case PAM_PROMPT_ECHO_ON: /* assume want user name */
3677 myreply[i].resp_retcode = PAM_SUCCESS;
3678 myreply[i].resp = COPY_STRING(cred->uname);
3679 /* PAM frees resp. */
3680 break;
3681 case PAM_PROMPT_ECHO_OFF: /* assume want password */
3682 myreply[i].resp_retcode = PAM_SUCCESS;
3683 myreply[i].resp = COPY_STRING(cred->pass);
3684 /* PAM frees resp. */
3685 break;
3686 case PAM_TEXT_INFO:
3687 case PAM_ERROR_MSG:
3688 myreply[i].resp_retcode = PAM_SUCCESS;
3689 myreply[i].resp = NULL;
3690 break;
3691 default: /* unknown message style */
3692 free(myreply);
3693 return PAM_CONV_ERR;
3694 }
3695 }
3696
3697 *resp = myreply;
3698 return PAM_SUCCESS;
3699 }
3700
3701 /*
3702 * Attempt to authenticate the user using PAM. Returns 0 if the user is
3703 * authenticated, or 1 if not authenticated. If some sort of PAM system
3704 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
3705 * function returns -1. This can be used as an indication that we should
3706 * fall back to a different authentication mechanism.
3707 */
3708 static int
3709 auth_pam(struct passwd **ppw, const char *pwstr)
3710 {
3711 const char *tmpl_user;
3712 const void *item;
3713 int rval;
3714 int e;
3715 cred_t auth_cred = { (*ppw)->pw_name, pwstr };
3716 struct pam_conv conv = { &auth_conv, &auth_cred };
3717
3718 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
3719 if (e != PAM_SUCCESS) {
3720 /*
3721 * In OpenPAM, it's OK to pass NULL to pam_strerror()
3722 * if context creation has failed in the first place.
3723 */
3724 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
3725 return -1;
3726 }
3727
3728 e = pam_set_item(pamh, PAM_RHOST, remotehost);
3729 if (e != PAM_SUCCESS) {
3730 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
3731 pam_strerror(pamh, e));
3732 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
3733 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
3734 }
3735 pamh = NULL;
3736 return -1;
3737 }
3738
3739 e = pam_authenticate(pamh, 0);
3740 switch (e) {
3741 case PAM_SUCCESS:
3742 /*
3743 * With PAM we support the concept of a "template"
3744 * user. The user enters a login name which is
3745 * authenticated by PAM, usually via a remote service
3746 * such as RADIUS or TACACS+. If authentication
3747 * succeeds, a different but related "template" name
3748 * is used for setting the credentials, shell, and
3749 * home directory. The name the user enters need only
3750 * exist on the remote authentication server, but the
3751 * template name must be present in the local password
3752 * database.
3753 *
3754 * This is supported by two various mechanisms in the
3755 * individual modules. However, from the application's
3756 * point of view, the template user is always passed
3757 * back as a changed value of the PAM_USER item.
3758 */
3759 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
3760 PAM_SUCCESS) {
3761 tmpl_user = (const char *) item;
3762 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
3763 *ppw = sgetpwnam(tmpl_user);
3764 } else
3765 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
3766 pam_strerror(pamh, e));
3767 rval = 0;
3768 break;
3769
3770 case PAM_AUTH_ERR:
3771 case PAM_USER_UNKNOWN:
3772 case PAM_MAXTRIES:
3773 rval = 1;
3774 break;
3775
3776 default:
3777 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
3778 rval = -1;
3779 break;
3780 }
3781
3782 if (rval == 0) {
3783 e = pam_acct_mgmt(pamh, 0);
3784 if (e != PAM_SUCCESS) {
3785 syslog(LOG_ERR, "pam_acct_mgmt: %s",
3786 pam_strerror(pamh, e));
3787 rval = 1;
3788 }
3789 }
3790
3791 if (rval != 0) {
3792 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
3793 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
3794 }
3795 pamh = NULL;
3796 }
3797 return rval;
3798 }
3799
3800 #endif /* USE_PAM */
3801