ftpd.c revision 1.129 1 /* $NetBSD: ftpd.c,v 1.129 2001/09/19 00:50:52 lukem 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.129 2001/09/19 00:50:52 lukem 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 total_bytes += b;
2133 total_bytes_out += b;
2134 cprintf(stdout, "\r\n");
2135 (void)fflush(stdout);
2136 if (debug) {
2137 syslog(LOG_DEBUG, "<--- %d%c", abs(n), (n < 0) ? '-' : ' ');
2138 vsyslog(LOG_DEBUG, fmt, ap);
2139 }
2140 }
2141
2142 static void
2143 logremotehost(struct sockinet *who)
2144 {
2145
2146 if (getnameinfo((struct sockaddr *)&who->si_su,
2147 who->su_len, remotehost, sizeof(remotehost), NULL, 0, 0))
2148 strlcpy(remotehost, "?", sizeof(remotehost));
2149
2150 #if HAVE_SETPROCTITLE
2151 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
2152 setproctitle("%s", proctitle);
2153 #endif /* HAVE_SETPROCTITLE */
2154 if (logging)
2155 syslog(LOG_INFO, "connection from %s to %s",
2156 remotehost, hostname);
2157 }
2158
2159 /*
2160 * Record logout in wtmp file and exit with supplied status.
2161 */
2162 void
2163 dologout(int status)
2164 {
2165 /*
2166 * Prevent reception of SIGURG from resulting in a resumption
2167 * back to the main program loop.
2168 */
2169 transflag = 0;
2170
2171 if (logged_in) {
2172 if (dowtmp)
2173 logwtmp(ttyline, "", "");
2174 if (doutmp)
2175 logout(utmp.ut_line);
2176 #ifdef KERBEROS
2177 if (!notickets && krbtkfile_env)
2178 unlink(krbtkfile_env);
2179 #endif
2180 }
2181 /* beware of flushing buffers after a SIGPIPE */
2182 _exit(status);
2183 }
2184
2185 void
2186 abor(void)
2187 {
2188
2189 tmpline[0] = '\0';
2190 is_oob = 0;
2191 reply(426, "Transfer aborted. Data connection closed.");
2192 reply(226, "Abort successful");
2193 longjmp(urgcatch, 1);
2194 }
2195
2196 void
2197 statxfer(void)
2198 {
2199
2200 tmpline[0] = '\0';
2201 is_oob = 0;
2202 if (file_size != (off_t) -1)
2203 reply(213,
2204 "Status: " LLF " of " LLF " byte%s transferred",
2205 (LLT)byte_count, (LLT)file_size,
2206 PLURAL(byte_count));
2207 else
2208 reply(213, "Status: " LLF " byte%s transferred",
2209 (LLT)byte_count, PLURAL(byte_count));
2210 }
2211
2212 static void
2213 myoob(int signo)
2214 {
2215 char *cp;
2216
2217 /* only process if transfer occurring */
2218 if (!transflag)
2219 return;
2220 cp = tmpline;
2221 if (getline(cp, sizeof(tmpline), stdin) == NULL) {
2222 reply(221, "You could at least say goodbye.");
2223 dologout(0);
2224 }
2225 is_oob = 1;
2226 ftp_handle_line(cp);
2227 is_oob = 0;
2228 }
2229
2230 static int
2231 bind_pasv_addr(void)
2232 {
2233 static int passiveport;
2234 int port, len;
2235
2236 len = pasv_addr.su_len;
2237 if (curclass.portmin == 0 && curclass.portmax == 0) {
2238 pasv_addr.su_port = 0;
2239 return (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len));
2240 }
2241
2242 if (passiveport == 0) {
2243 srand(getpid());
2244 passiveport = rand() % (curclass.portmax - curclass.portmin)
2245 + curclass.portmin;
2246 }
2247
2248 port = passiveport;
2249 while (1) {
2250 port++;
2251 if (port > curclass.portmax)
2252 port = curclass.portmin;
2253 else if (port == passiveport) {
2254 errno = EAGAIN;
2255 return (-1);
2256 }
2257 pasv_addr.su_port = htons(port);
2258 if (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len) == 0)
2259 break;
2260 if (errno != EADDRINUSE)
2261 return (-1);
2262 }
2263 passiveport = port;
2264 return (0);
2265 }
2266
2267 /*
2268 * Note: a response of 425 is not mentioned as a possible response to
2269 * the PASV command in RFC959. However, it has been blessed as
2270 * a legitimate response by Jon Postel in a telephone conversation
2271 * with Rick Adams on 25 Jan 89.
2272 */
2273 void
2274 passive(void)
2275 {
2276 int len;
2277 char *p, *a;
2278
2279 if (pdata >= 0)
2280 close(pdata);
2281 pdata = socket(AF_INET, SOCK_STREAM, 0);
2282 if (pdata < 0 || !logged_in) {
2283 perror_reply(425, "Can't open passive connection");
2284 return;
2285 }
2286 pasv_addr = ctrl_addr;
2287
2288 if (bind_pasv_addr() < 0)
2289 goto pasv_error;
2290 len = pasv_addr.su_len;
2291 if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
2292 goto pasv_error;
2293 pasv_addr.su_len = len;
2294 if (listen(pdata, 1) < 0)
2295 goto pasv_error;
2296 if (curclass.advertise.su_len != 0)
2297 a = (char *) &curclass.advertise.su_addr;
2298 else
2299 a = (char *) &pasv_addr.su_addr;
2300 p = (char *) &pasv_addr.su_port;
2301
2302 #define UC(b) (((int) b) & 0xff)
2303
2304 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2305 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2306 return;
2307
2308 pasv_error:
2309 (void) close(pdata);
2310 pdata = -1;
2311 perror_reply(425, "Can't open passive connection");
2312 return;
2313 }
2314
2315 /*
2316 * convert protocol identifier to/from AF
2317 */
2318 int
2319 lpsvproto2af(int proto)
2320 {
2321
2322 switch (proto) {
2323 case 4:
2324 return AF_INET;
2325 #ifdef INET6
2326 case 6:
2327 return AF_INET6;
2328 #endif
2329 default:
2330 return -1;
2331 }
2332 }
2333
2334 int
2335 af2lpsvproto(int af)
2336 {
2337
2338 switch (af) {
2339 case AF_INET:
2340 return 4;
2341 #ifdef INET6
2342 case AF_INET6:
2343 return 6;
2344 #endif
2345 default:
2346 return -1;
2347 }
2348 }
2349
2350 int
2351 epsvproto2af(int proto)
2352 {
2353
2354 switch (proto) {
2355 case 1:
2356 return AF_INET;
2357 #ifdef INET6
2358 case 2:
2359 return AF_INET6;
2360 #endif
2361 default:
2362 return -1;
2363 }
2364 }
2365
2366 int
2367 af2epsvproto(int af)
2368 {
2369
2370 switch (af) {
2371 case AF_INET:
2372 return 1;
2373 #ifdef INET6
2374 case AF_INET6:
2375 return 2;
2376 #endif
2377 default:
2378 return -1;
2379 }
2380 }
2381
2382 /*
2383 * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)
2384 * 229 Entering Extended Passive Mode (|||port|)
2385 */
2386 void
2387 long_passive(char *cmd, int pf)
2388 {
2389 int len;
2390 char *p, *a;
2391
2392 if (!logged_in) {
2393 syslog(LOG_NOTICE, "long passive but not logged in");
2394 reply(503, "Login with USER first.");
2395 return;
2396 }
2397
2398 if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) {
2399 /*
2400 * XXX: only EPRT/EPSV ready clients will understand this
2401 */
2402 if (strcmp(cmd, "EPSV") != 0)
2403 reply(501, "Network protocol mismatch"); /*XXX*/
2404 else
2405 epsv_protounsupp("Network protocol mismatch");
2406
2407 return;
2408 }
2409
2410 if (pdata >= 0)
2411 close(pdata);
2412 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2413 if (pdata < 0) {
2414 perror_reply(425, "Can't open passive connection");
2415 return;
2416 }
2417 pasv_addr = ctrl_addr;
2418 if (bind_pasv_addr() < 0)
2419 goto pasv_error;
2420 len = pasv_addr.su_len;
2421 if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
2422 goto pasv_error;
2423 pasv_addr.su_len = len;
2424 if (listen(pdata, 1) < 0)
2425 goto pasv_error;
2426 p = (char *) &pasv_addr.su_port;
2427
2428 #define UC(b) (((int) b) & 0xff)
2429
2430 if (strcmp(cmd, "LPSV") == 0) {
2431 struct sockinet *advert;
2432
2433 if (curclass.advertise.su_len != 0)
2434 advert = &curclass.advertise;
2435 else
2436 advert = &pasv_addr;
2437 switch (advert->su_family) {
2438 case AF_INET:
2439 a = (char *) &advert->su_addr;
2440 reply(228,
2441 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2442 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2443 2, UC(p[0]), UC(p[1]));
2444 return;
2445 #ifdef INET6
2446 case AF_INET6:
2447 a = (char *) &advert->su_6addr;
2448 reply(228,
2449 "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)",
2450 6, 16,
2451 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2452 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2453 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2454 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2455 2, UC(p[0]), UC(p[1]));
2456 return;
2457 #endif
2458 }
2459 #undef UC
2460 } else if (strcmp(cmd, "EPSV") == 0) {
2461 switch (pasv_addr.su_family) {
2462 case AF_INET:
2463 #ifdef INET6
2464 case AF_INET6:
2465 #endif
2466 reply(229, "Entering Extended Passive Mode (|||%d|)",
2467 ntohs(pasv_addr.su_port));
2468 return;
2469 }
2470 } else {
2471 /* more proper error code? */
2472 }
2473
2474 pasv_error:
2475 (void) close(pdata);
2476 pdata = -1;
2477 perror_reply(425, "Can't open passive connection");
2478 return;
2479 }
2480
2481 int
2482 extended_port(const char *arg)
2483 {
2484 char *tmp = NULL;
2485 char *result[3];
2486 char *p, *q;
2487 char delim;
2488 struct addrinfo hints;
2489 struct addrinfo *res = NULL;
2490 int i;
2491 unsigned long proto;
2492
2493 tmp = xstrdup(arg);
2494 p = tmp;
2495 delim = p[0];
2496 p++;
2497 memset(result, 0, sizeof(result));
2498 for (i = 0; i < 3; i++) {
2499 q = strchr(p, delim);
2500 if (!q || *q != delim)
2501 goto parsefail;
2502 *q++ = '\0';
2503 result[i] = p;
2504 p = q;
2505 }
2506
2507 /* some more sanity checks */
2508 p = NULL;
2509 (void)strtoul(result[2], &p, 10);
2510 if (!*result[2] || *p)
2511 goto parsefail;
2512 p = NULL;
2513 proto = strtoul(result[0], &p, 10);
2514 if (!*result[0] || *p)
2515 goto protounsupp;
2516
2517 memset(&hints, 0, sizeof(hints));
2518 hints.ai_family = epsvproto2af((int)proto);
2519 if (hints.ai_family < 0)
2520 goto protounsupp;
2521 hints.ai_socktype = SOCK_STREAM;
2522 hints.ai_flags = AI_NUMERICHOST;
2523 if (getaddrinfo(result[1], result[2], &hints, &res))
2524 goto parsefail;
2525 if (res->ai_next)
2526 goto parsefail;
2527 if (sizeof(data_dest) < res->ai_addrlen)
2528 goto parsefail;
2529 memcpy(&data_dest.si_su, res->ai_addr, res->ai_addrlen);
2530 data_dest.su_len = res->ai_addrlen;
2531 #ifdef INET6
2532 if (his_addr.su_family == AF_INET6 &&
2533 data_dest.su_family == AF_INET6) {
2534 /* XXX: more sanity checks! */
2535 data_dest.su_scope_id = his_addr.su_scope_id;
2536 }
2537 #endif
2538
2539 if (tmp != NULL)
2540 free(tmp);
2541 if (res)
2542 freeaddrinfo(res);
2543 return 0;
2544
2545 parsefail:
2546 reply(500, "Invalid argument, rejected.");
2547 usedefault = 1;
2548 if (tmp != NULL)
2549 free(tmp);
2550 if (res)
2551 freeaddrinfo(res);
2552 return -1;
2553
2554 protounsupp:
2555 epsv_protounsupp("Protocol not supported");
2556 usedefault = 1;
2557 if (tmp != NULL)
2558 free(tmp);
2559 if (res)
2560 freeaddrinfo(res);
2561 return -1;
2562 }
2563
2564 /*
2565 * 522 Protocol not supported (proto,...)
2566 * as we assume address family for control and data connections are the same,
2567 * we do not return the list of address families we support - instead, we
2568 * return the address family of the control connection.
2569 */
2570 void
2571 epsv_protounsupp(const char *message)
2572 {
2573 int proto;
2574
2575 proto = af2epsvproto(ctrl_addr.su_family);
2576 if (proto < 0)
2577 reply(501, "%s", message); /* XXX */
2578 else
2579 reply(522, "%s, use (%d)", message, proto);
2580 }
2581
2582 /*
2583 * Generate unique name for file with basename "local".
2584 * The file named "local" is already known to exist.
2585 * Generates failure reply on error.
2586 *
2587 * XXX: this function should under go changes similar to
2588 * the mktemp(3)/mkstemp(3) changes.
2589 */
2590 static char *
2591 gunique(const char *local)
2592 {
2593 static char new[MAXPATHLEN];
2594 struct stat st;
2595 char *cp;
2596 int count;
2597
2598 cp = strrchr(local, '/');
2599 if (cp)
2600 *cp = '\0';
2601 if (stat(cp ? local : ".", &st) < 0) {
2602 perror_reply(553, cp ? local : ".");
2603 return (NULL);
2604 }
2605 if (cp)
2606 *cp = '/';
2607 for (count = 1; count < 100; count++) {
2608 (void)snprintf(new, sizeof(new) - 1, "%s.%d", local, count);
2609 if (stat(new, &st) < 0)
2610 return (new);
2611 }
2612 reply(452, "Unique file name cannot be created.");
2613 return (NULL);
2614 }
2615
2616 /*
2617 * Format and send reply containing system error number.
2618 */
2619 void
2620 perror_reply(int code, const char *string)
2621 {
2622 int save_errno;
2623
2624 save_errno = errno;
2625 reply(code, "%s: %s.", string, strerror(errno));
2626 errno = save_errno;
2627 }
2628
2629 static char *onefile[] = {
2630 "",
2631 0
2632 };
2633
2634 void
2635 send_file_list(const char *whichf)
2636 {
2637 struct stat st;
2638 DIR *dirp = NULL;
2639 struct dirent *dir;
2640 FILE *dout = NULL;
2641 char **dirlist, *dirname, *p;
2642 int simple = 0;
2643 int freeglob = 0;
2644 glob_t gl;
2645
2646 #ifdef __GNUC__
2647 (void) &dout;
2648 (void) &dirlist;
2649 (void) &simple;
2650 (void) &freeglob;
2651 #endif
2652
2653 p = NULL;
2654 if (strpbrk(whichf, "~{[*?") != NULL) {
2655 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE|GLOB_LIMIT;
2656
2657 memset(&gl, 0, sizeof(gl));
2658 freeglob = 1;
2659 if (glob(whichf, flags, 0, &gl)) {
2660 reply(550, "not found");
2661 goto out;
2662 } else if (gl.gl_pathc == 0) {
2663 errno = ENOENT;
2664 perror_reply(550, whichf);
2665 goto out;
2666 }
2667 dirlist = gl.gl_pathv;
2668 } else {
2669 p = xstrdup(whichf);
2670 onefile[0] = p;
2671 dirlist = onefile;
2672 simple = 1;
2673 }
2674 /* XXX: } for vi sm */
2675
2676 if (setjmp(urgcatch)) {
2677 transflag = 0;
2678 goto out;
2679 }
2680 while ((dirname = *dirlist++) != NULL) {
2681 int trailingslash = 0;
2682
2683 if (stat(dirname, &st) < 0) {
2684 /*
2685 * If user typed "ls -l", etc, and the client
2686 * used NLST, do what the user meant.
2687 */
2688 /* XXX: nuke this support? */
2689 if (dirname[0] == '-' && *dirlist == NULL &&
2690 transflag == 0) {
2691 char *argv[] = { INTERNAL_LS, "", NULL };
2692
2693 argv[1] = dirname;
2694 retrieve(argv, dirname);
2695 goto out;
2696 }
2697 perror_reply(550, whichf);
2698 goto cleanup_send_file_list;
2699 }
2700
2701 if (S_ISREG(st.st_mode)) {
2702 /*
2703 * XXXRFC:
2704 * should we follow RFC959 and not work
2705 * for non directories?
2706 */
2707 if (dout == NULL) {
2708 dout = dataconn("file list", (off_t)-1, "w");
2709 if (dout == NULL)
2710 goto out;
2711 transflag++;
2712 }
2713 cprintf(dout, "%s%s\n", dirname,
2714 type == TYPE_A ? "\r" : "");
2715 continue;
2716 } else if (!S_ISDIR(st.st_mode))
2717 continue;
2718
2719 if (dirname[strlen(dirname) - 1] == '/')
2720 trailingslash++;
2721
2722 if ((dirp = opendir(dirname)) == NULL)
2723 continue;
2724
2725 while ((dir = readdir(dirp)) != NULL) {
2726 char nbuf[MAXPATHLEN];
2727
2728 if (ISDOTDIR(dir->d_name) || ISDOTDOTDIR(dir->d_name))
2729 continue;
2730
2731 (void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
2732 trailingslash ? "" : "/", dir->d_name);
2733
2734 /*
2735 * We have to do a stat to ensure it's
2736 * not a directory or special file.
2737 */
2738 /*
2739 * XXXRFC:
2740 * should we follow RFC959 and filter out
2741 * non files ? lukem - NO!, or not until
2742 * our ftp client uses MLS{T,D} for completion.
2743 */
2744 if (simple || (stat(nbuf, &st) == 0 &&
2745 S_ISREG(st.st_mode))) {
2746 char *p;
2747
2748 if (dout == NULL) {
2749 dout = dataconn("file list", (off_t)-1,
2750 "w");
2751 if (dout == NULL)
2752 goto out;
2753 transflag++;
2754 }
2755 p = nbuf;
2756 if (nbuf[0] == '.' && nbuf[1] == '/')
2757 p = &nbuf[2];
2758 cprintf(dout, "%s%s\n", p,
2759 type == TYPE_A ? "\r" : "");
2760 }
2761 }
2762 (void) closedir(dirp);
2763 }
2764
2765 if (dout == NULL)
2766 reply(550, "No files found.");
2767 else if (ferror(dout) != 0)
2768 perror_reply(550, "Data connection");
2769 else
2770 reply(226, "Transfer complete.");
2771
2772 cleanup_send_file_list:
2773 transflag = 0;
2774 closedataconn(dout);
2775 out:
2776 total_xfers++;
2777 total_xfers_out++;
2778 if (p)
2779 free(p);
2780 if (freeglob)
2781 globfree(&gl);
2782 }
2783
2784 char *
2785 conffilename(const char *s)
2786 {
2787 static char filename[MAXPATHLEN];
2788
2789 if (*s == '/')
2790 strlcpy(filename, s, sizeof(filename));
2791 else
2792 (void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
2793 return (filename);
2794 }
2795
2796 /*
2797 * logxfer --
2798 * if logging > 1, then based on the arguments, syslog a message:
2799 * if bytes != -1 "<command> <file1> = <bytes> bytes"
2800 * else if file2 != NULL "<command> <file1> <file2>"
2801 * else "<command> <file1>"
2802 * if elapsed != NULL, append "in xxx.yyy seconds"
2803 * if error != NULL, append ": " + error
2804 *
2805 * if doxferlog != 0, syslog a wu-ftpd style xferlog entry
2806 */
2807 void
2808 logxfer(const char *command, off_t bytes, const char *file1, const char *file2,
2809 const struct timeval *elapsed, const char *error)
2810 {
2811 char buf[MAXPATHLEN * 2 + 100], realfile[MAXPATHLEN];
2812 const char *r1, *r2;
2813 char direction;
2814 size_t len;
2815 time_t now;
2816
2817 if (logging <=1 && !doxferlog)
2818 return;
2819
2820 r1 = r2 = NULL;
2821 if ((r1 = realpath(file1, realfile)) == NULL)
2822 r1 = file1;
2823 if (file2 != NULL)
2824 if ((r2 = realpath(file2, realfile)) == NULL)
2825 r2 = file2;
2826
2827 /*
2828 * syslog command
2829 */
2830 if (logging > 1) {
2831 len = snprintf(buf, sizeof(buf), "%s %s", command, r1);
2832 if (bytes != (off_t)-1)
2833 len += snprintf(buf + len, sizeof(buf) - len,
2834 " = " LLF " byte%s", (LLT) bytes, PLURAL(bytes));
2835 else if (r2 != NULL)
2836 len += snprintf(buf + len, sizeof(buf) - len,
2837 " %s", r2);
2838 if (elapsed != NULL)
2839 len += snprintf(buf + len, sizeof(buf) - len,
2840 " in %ld.%.03d seconds", elapsed->tv_sec,
2841 (int)(elapsed->tv_usec / 1000));
2842 if (error != NULL)
2843 len += snprintf(buf + len, sizeof(buf) - len,
2844 ": %s", error);
2845 syslog(LOG_INFO, "%s", buf);
2846 }
2847
2848
2849 /*
2850 * syslog wu-ftpd style log entry, prefixed with "xferlog: "
2851 */
2852 if (!doxferlog)
2853 return;
2854
2855 if (strcmp(command, "get") == 0)
2856 direction = 'o';
2857 else if (strcmp(command, "put") == 0 || strcmp(command, "append") == 0)
2858 direction = 'i';
2859 else
2860 return;
2861
2862 time(&now);
2863 syslog(LOG_INFO,
2864 "xferlog%s: %.24s %ld %s " LLF " %s %c %s %c %c %s FTP 0 * %c",
2865
2866 /*
2867 * XXX: wu-ftpd puts (send) or (recv) in the syslog message, and removes
2868 * the full date. This may be problematic for accurate log parsing,
2869 * given that syslog messages don't contain the full date.
2870 */
2871 #if 1 /* lukem's method; easier to convert to actual xferlog file */
2872 "",
2873 ctime(&now),
2874 #else /* wu-ftpd's syslog method, with an extra unneeded space */
2875 (direction == 'i') ? " (recv)" : " (send)",
2876 "",
2877 #endif
2878 elapsed == NULL ? 0 : elapsed->tv_sec + (elapsed->tv_usec > 0),
2879 remotehost,
2880 bytes == (off_t)-1 ? 0 : (LLT) bytes,
2881 r1,
2882 type == TYPE_A ? 'a' : 'b',
2883 "_", /* XXX: take conversions into account? */
2884 direction,
2885
2886 curclass.type == CLASS_GUEST ? 'a' :
2887 curclass.type == CLASS_CHROOT ? 'g' :
2888 curclass.type == CLASS_REAL ? 'r' : '?',
2889
2890 curclass.type == CLASS_GUEST ? pw->pw_passwd : pw->pw_name,
2891 error != NULL ? 'i' : 'c'
2892 );
2893 }
2894
2895 /*
2896 * Determine if `password' is valid for user given in `pw'.
2897 * Returns 2 if password expired, 1 if otherwise failed, 0 if ok
2898 */
2899 int
2900 checkpassword(const struct passwd *pw, const char *password)
2901 {
2902 char *orig, *new;
2903 time_t expire;
2904
2905 expire = 0;
2906 if (pw == NULL)
2907 return 1;
2908
2909 orig = pw->pw_passwd; /* save existing password */
2910 expire = pw->pw_expire;
2911
2912 if (orig[0] == '\0') /* don't allow empty passwords */
2913 return 1;
2914
2915 new = crypt(password, orig); /* encrypt given password */
2916 if (strcmp(new, orig) != 0) /* compare */
2917 return 1;
2918
2919 if (expire && time(NULL) >= expire)
2920 return 2; /* check if expired */
2921
2922 return 0; /* OK! */
2923 }
2924
2925 char *
2926 xstrdup(const char *s)
2927 {
2928 char *new = strdup(s);
2929
2930 if (new == NULL)
2931 fatal("Local resource failure: malloc");
2932 /* NOTREACHED */
2933 return (new);
2934 }
2935
2936 /*
2937 * As per fprintf(), but increment total_bytes and total_bytes_out,
2938 * by the appropriate amount.
2939 */
2940 void
2941 cprintf(FILE *fd, const char *fmt, ...)
2942 {
2943 off_t b;
2944 va_list ap;
2945
2946 va_start(ap, fmt);
2947 b = vfprintf(fd, fmt, ap);
2948 total_bytes += b;
2949 total_bytes_out += b;
2950 }
2951