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