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