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