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