ftpd.c revision 1.134 1 /* $NetBSD: ftpd.c,v 1.134 2001/12/06 02:00:06 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.134 2001/12/06 02:00:06 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 (void) fclose(dout); /* close now to affect timing stats */
1288 dout = NULL;
1289 timersub(&finish, &start, &td);
1290 tdp = &td;
1291 done:
1292 if (log)
1293 logxfer("get", byte_count, name, NULL, tdp, NULL);
1294 closerv = (*closefunc)(fin);
1295 if (sendrv == 0) {
1296 FILE *errf;
1297 struct stat sb;
1298
1299 if (!isls && argv != NULL && closerv != 0) {
1300 reply(-226,
1301 "Command returned an exit status of %d",
1302 closerv);
1303 if (isconversion)
1304 syslog(LOG_WARNING,
1305 "retrieve command: '%s' returned %d",
1306 argv[0], closerv);
1307 }
1308 if (!isls && argv != NULL && stderrfd != -1 &&
1309 (fstat(stderrfd, &sb) == 0) && sb.st_size > 0 &&
1310 ((errf = fdopen(stderrfd, "r")) != NULL)) {
1311 char *cp, line[LINE_MAX];
1312
1313 reply(-226, "Command error messages:");
1314 rewind(errf);
1315 while (fgets(line, sizeof(line), errf) != NULL) {
1316 if ((cp = strchr(line, '\n')) != NULL)
1317 *cp = '\0';
1318 reply(0, " %s", line);
1319 }
1320 (void) fflush(stdout);
1321 (void) fclose(errf);
1322 /* a reply(226,) must follow */
1323 }
1324 reply(226, "Transfer complete.");
1325 }
1326 cleanupretrieve:
1327 closedataconn(dout);
1328 if (stderrfd != -1)
1329 (void)close(stderrfd);
1330 if (isconversion)
1331 free(argv);
1332 }
1333
1334 void
1335 store(const char *name, const char *fmode, int unique)
1336 {
1337 FILE *fout, *din;
1338 struct stat st;
1339 int (*closefunc)(FILE *);
1340 struct timeval start, finish, td, *tdp;
1341 char *desc;
1342
1343 din = NULL;
1344 desc = (*fmode == 'w') ? "put" : "append";
1345 if (unique && stat(name, &st) == 0 &&
1346 (name = gunique(name)) == NULL) {
1347 logxfer(desc, -1, name, NULL, NULL,
1348 "cannot create unique file");
1349 goto cleanupstore;
1350 }
1351
1352 if (restart_point)
1353 fmode = "r+";
1354 fout = fopen(name, fmode);
1355 closefunc = fclose;
1356 tdp = NULL;
1357 if (fout == NULL) {
1358 perror_reply(553, name);
1359 logxfer(desc, -1, name, NULL, NULL, strerror(errno));
1360 goto cleanupstore;
1361 }
1362 byte_count = -1;
1363 if (restart_point) {
1364 if (type == TYPE_A) {
1365 off_t i;
1366 int c;
1367
1368 for (i = 0; i < restart_point; i++) {
1369 if ((c=getc(fout)) == EOF) {
1370 perror_reply(550, name);
1371 goto done;
1372 }
1373 if (c == '\n')
1374 i++;
1375 }
1376 /*
1377 * We must do this seek to "current" position
1378 * because we are changing from reading to
1379 * writing.
1380 */
1381 if (fseek(fout, 0L, SEEK_CUR) < 0) {
1382 perror_reply(550, name);
1383 goto done;
1384 }
1385 } else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1386 perror_reply(550, name);
1387 goto done;
1388 }
1389 }
1390 din = dataconn(name, (off_t)-1, "r");
1391 if (din == NULL)
1392 goto done;
1393 (void)gettimeofday(&start, NULL);
1394 if (receive_data(din, fout) == 0) {
1395 if (unique)
1396 reply(226, "Transfer complete (unique file name:%s).",
1397 name);
1398 else
1399 reply(226, "Transfer complete.");
1400 }
1401 (void)gettimeofday(&finish, NULL);
1402 (void) fclose(din); /* close now to affect timing stats */
1403 din = NULL;
1404 timersub(&finish, &start, &td);
1405 tdp = &td;
1406 done:
1407 logxfer(desc, byte_count, name, NULL, tdp, NULL);
1408 (*closefunc)(fout);
1409 cleanupstore:
1410 closedataconn(din);
1411 }
1412
1413 static FILE *
1414 getdatasock(const char *fmode)
1415 {
1416 int on, s, t, tries;
1417 in_port_t port;
1418
1419 on = 1;
1420 if (data >= 0)
1421 return (fdopen(data, fmode));
1422 if (! dropprivs)
1423 (void) seteuid((uid_t)0);
1424 s = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
1425 if (s < 0)
1426 goto bad;
1427 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
1428 (char *) &on, sizeof(on)) < 0)
1429 goto bad;
1430 if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
1431 (char *) &on, sizeof(on)) < 0)
1432 goto bad;
1433 /* anchor socket to avoid multi-homing problems */
1434 data_source = ctrl_addr;
1435 /*
1436 * By default source port for PORT connctions is
1437 * ctrlport-1 (see RFC959 section 5.2).
1438 * However, if privs have been dropped and that
1439 * would be < IPPORT_RESERVED, use a random port
1440 * instead.
1441 */
1442 if (dataport)
1443 port = dataport;
1444 else
1445 port = ntohs(ctrl_addr.su_port) - 1;
1446 if (dropprivs && port < IPPORT_RESERVED)
1447 port = 0; /* use random port */
1448 data_source.su_port = htons(port);
1449
1450 for (tries = 1; ; tries++) {
1451 if (bind(s, (struct sockaddr *)&data_source.si_su,
1452 data_source.su_len) >= 0)
1453 break;
1454 if (errno != EADDRINUSE || tries > 10)
1455 goto bad;
1456 sleep(tries);
1457 }
1458 if (! dropprivs)
1459 (void) seteuid((uid_t)pw->pw_uid);
1460 #ifdef IP_TOS
1461 if (!mapped && ctrl_addr.su_family == AF_INET) {
1462 on = IPTOS_THROUGHPUT;
1463 if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on,
1464 sizeof(int)) < 0)
1465 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
1466 }
1467 #endif
1468 return (fdopen(s, fmode));
1469 bad:
1470 /* Return the real value of errno (close may change it) */
1471 t = errno;
1472 if (! dropprivs)
1473 (void) seteuid((uid_t)pw->pw_uid);
1474 (void) close(s);
1475 errno = t;
1476 return (NULL);
1477 }
1478
1479 FILE *
1480 dataconn(const char *name, off_t size, const char *fmode)
1481 {
1482 char sizebuf[32];
1483 FILE *file;
1484 int retry = 0, tos, keepalive;
1485
1486 file_size = size;
1487 byte_count = 0;
1488 if (size != (off_t) -1)
1489 (void)snprintf(sizebuf, sizeof(sizebuf), " (" LLF " byte%s)",
1490 (LLT)size, PLURAL(size));
1491 else
1492 sizebuf[0] = '\0';
1493 if (pdata >= 0) {
1494 struct sockinet from;
1495 int s, fromlen = sizeof(from.su_len);
1496
1497 (void) alarm(curclass.timeout);
1498 s = accept(pdata, (struct sockaddr *)&from.si_su, &fromlen);
1499 (void) alarm(0);
1500 if (s < 0) {
1501 reply(425, "Can't open data connection.");
1502 (void) close(pdata);
1503 pdata = -1;
1504 return (NULL);
1505 }
1506 (void) close(pdata);
1507 pdata = s;
1508 switch (from.su_family) {
1509 case AF_INET:
1510 #ifdef IP_TOS
1511 if (!mapped) {
1512 tos = IPTOS_THROUGHPUT;
1513 (void) setsockopt(s, IPPROTO_IP, IP_TOS,
1514 (char *)&tos, sizeof(int));
1515 }
1516 break;
1517 #endif
1518 }
1519 /* Set keepalives on the socket to detect dropped conns. */
1520 #ifdef SO_KEEPALIVE
1521 keepalive = 1;
1522 (void) setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
1523 (char *)&keepalive, sizeof(int));
1524 #endif
1525 reply(150, "Opening %s mode data connection for '%s'%s.",
1526 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1527 return (fdopen(pdata, fmode));
1528 }
1529 if (data >= 0) {
1530 reply(125, "Using existing data connection for '%s'%s.",
1531 name, sizebuf);
1532 usedefault = 1;
1533 return (fdopen(data, fmode));
1534 }
1535 if (usedefault)
1536 data_dest = his_addr;
1537 usedefault = 1;
1538 file = getdatasock(fmode);
1539 if (file == NULL) {
1540 char hbuf[NI_MAXHOST];
1541 char pbuf[NI_MAXSERV];
1542
1543 if (getnameinfo((struct sockaddr *)&data_source.si_su,
1544 data_source.su_len, hbuf, sizeof(hbuf), pbuf, sizeof(pbuf),
1545 NI_NUMERICHOST | NI_NUMERICSERV))
1546 strlcpy(hbuf, "?", sizeof(hbuf));
1547 reply(425, "Can't create data socket (%s,%s): %s.",
1548 hbuf, pbuf, strerror(errno));
1549 return (NULL);
1550 }
1551 data = fileno(file);
1552 while (connect(data, (struct sockaddr *)&data_dest.si_su,
1553 data_dest.su_len) < 0) {
1554 if (errno == EADDRINUSE && retry < swaitmax) {
1555 sleep((unsigned) swaitint);
1556 retry += swaitint;
1557 continue;
1558 }
1559 perror_reply(425, "Can't build data connection");
1560 (void) fclose(file);
1561 data = -1;
1562 return (NULL);
1563 }
1564 reply(150, "Opening %s mode data connection for '%s'%s.",
1565 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1566 return (file);
1567 }
1568
1569 void
1570 closedataconn(FILE *fd)
1571 {
1572
1573 if (fd != NULL)
1574 (void)fclose(fd);
1575 data = -1;
1576 if (pdata >= 0)
1577 (void)close(pdata);
1578 pdata = -1;
1579 }
1580
1581 /*
1582 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1583 * encapsulation of the data subject * to Mode, Structure, and Type.
1584 *
1585 * NB: Form isn't handled.
1586 */
1587 static int
1588 send_data(FILE *instr, FILE *outstr, off_t blksize, int isdata)
1589 {
1590 int c, filefd, netfd, rval;
1591 char *buf;
1592
1593 transflag = 1;
1594 rval = -1;
1595 buf = NULL;
1596 if (setjmp(urgcatch))
1597 goto cleanup_send_data;
1598
1599 switch (type) {
1600
1601 case TYPE_A:
1602 /* XXXLUKEM: rate limit ascii send (get) */
1603 (void) alarm(curclass.timeout);
1604 while ((c = getc(instr)) != EOF) {
1605 byte_count++;
1606 if (c == '\n') {
1607 if (ferror(outstr))
1608 goto data_err;
1609 (void) putc('\r', outstr);
1610 if (isdata) {
1611 total_data_out++;
1612 total_data++;
1613 }
1614 total_bytes_out++;
1615 total_bytes++;
1616 }
1617 (void) putc(c, outstr);
1618 if (isdata) {
1619 total_data_out++;
1620 total_data++;
1621 }
1622 total_bytes_out++;
1623 total_bytes++;
1624 if ((byte_count % 4096) == 0)
1625 (void) alarm(curclass.timeout);
1626 }
1627 (void) alarm(0);
1628 fflush(outstr);
1629 if (ferror(instr))
1630 goto file_err;
1631 if (ferror(outstr))
1632 goto data_err;
1633 rval = 0;
1634 goto cleanup_send_data;
1635
1636 case TYPE_I:
1637 case TYPE_L:
1638 if ((buf = malloc((size_t)blksize)) == NULL) {
1639 perror_reply(451, "Local resource failure: malloc");
1640 goto cleanup_send_data;
1641 }
1642 filefd = fileno(instr);
1643 netfd = fileno(outstr);
1644 (void) alarm(curclass.timeout);
1645 if (curclass.rateget) {
1646 while (1) {
1647 int d;
1648 struct timeval then, now, td;
1649 off_t bufrem;
1650 char *bufp;
1651
1652 (void)gettimeofday(&then, NULL);
1653 errno = c = d = 0;
1654 bufrem = curclass.rateget;
1655 while (bufrem > 0) {
1656 if ((c = read(filefd, buf,
1657 MIN(blksize, bufrem))) <= 0)
1658 goto senddone;
1659 (void) alarm(curclass.timeout);
1660 bufrem -= c;
1661 byte_count += c;
1662 if (isdata) {
1663 total_data_out += c;
1664 total_data += c;
1665 }
1666 total_bytes_out += c;
1667 total_bytes += c;
1668 for (bufp = buf; c > 0;
1669 c -= d, bufp += d)
1670 if ((d =
1671 write(netfd, bufp, c)) <= 0)
1672 break;
1673 if (d < 0)
1674 goto data_err;
1675 }
1676 (void)gettimeofday(&now, NULL);
1677 timersub(&now, &then, &td);
1678 if (td.tv_sec == 0)
1679 usleep(1000000 - td.tv_usec);
1680 }
1681 } else {
1682 while ((c = read(filefd, buf, (size_t)blksize)) > 0) {
1683 if (write(netfd, buf, c) != c)
1684 goto data_err;
1685 (void) alarm(curclass.timeout);
1686 byte_count += c;
1687 if (isdata) {
1688 total_data_out += c;
1689 total_data += c;
1690 }
1691 total_bytes_out += c;
1692 total_bytes += c;
1693 }
1694 }
1695 senddone:
1696 if (c < 0)
1697 goto file_err;
1698 rval = 0;
1699 goto cleanup_send_data;
1700
1701 default:
1702 reply(550, "Unimplemented TYPE %d in send_data", type);
1703 goto cleanup_send_data;
1704 }
1705
1706 data_err:
1707 (void) alarm(0);
1708 perror_reply(426, "Data connection");
1709 goto cleanup_send_data;
1710
1711 file_err:
1712 (void) alarm(0);
1713 perror_reply(551, "Error on input file");
1714 /* FALLTHROUGH */
1715
1716 cleanup_send_data:
1717 (void) alarm(0);
1718 transflag = 0;
1719 if (buf)
1720 free(buf);
1721 if (isdata) {
1722 total_files_out++;
1723 total_files++;
1724 }
1725 total_xfers_out++;
1726 total_xfers++;
1727 return (rval);
1728 }
1729
1730 /*
1731 * Transfer data from peer to "outstr" using the appropriate encapulation of
1732 * the data subject to Mode, Structure, and Type.
1733 *
1734 * N.B.: Form isn't handled.
1735 */
1736 static int
1737 receive_data(FILE *instr, FILE *outstr)
1738 {
1739 int c, bare_lfs, netfd, filefd, rval;
1740 off_t byteswritten;
1741 char buf[BUFSIZ];
1742 #ifdef __GNUC__
1743 (void) &bare_lfs;
1744 #endif
1745
1746 bare_lfs = 0;
1747 transflag = 1;
1748 rval = -1;
1749 byteswritten = 0;
1750 if (setjmp(urgcatch))
1751 goto cleanup_recv_data;
1752
1753 #define FILESIZECHECK(x) \
1754 do { \
1755 if (curclass.maxfilesize != -1 && \
1756 (x) > curclass.maxfilesize) { \
1757 errno = EFBIG; \
1758 goto file_err; \
1759 } \
1760 } while (0)
1761
1762 switch (type) {
1763
1764 case TYPE_I:
1765 case TYPE_L:
1766 netfd = fileno(instr);
1767 filefd = fileno(outstr);
1768 (void) alarm(curclass.timeout);
1769 if (curclass.rateput) {
1770 while (1) {
1771 int d;
1772 struct timeval then, now, td;
1773 off_t bufrem;
1774
1775 (void)gettimeofday(&then, NULL);
1776 errno = c = d = 0;
1777 for (bufrem = curclass.rateput; bufrem > 0; ) {
1778 if ((c = read(netfd, buf,
1779 MIN(sizeof(buf), bufrem))) <= 0)
1780 goto recvdone;
1781 FILESIZECHECK(byte_count + c);
1782 if ((d = write(filefd, buf, c)) != c)
1783 goto file_err;
1784 (void) alarm(curclass.timeout);
1785 bufrem -= c;
1786 byte_count += c;
1787 total_data_in += c;
1788 total_data += c;
1789 total_bytes_in += c;
1790 total_bytes += c;
1791 }
1792 (void)gettimeofday(&now, NULL);
1793 timersub(&now, &then, &td);
1794 if (td.tv_sec == 0)
1795 usleep(1000000 - td.tv_usec);
1796 }
1797 } else {
1798 while ((c = read(netfd, buf, sizeof(buf))) > 0) {
1799 FILESIZECHECK(byte_count + c);
1800 if (write(filefd, buf, c) != c)
1801 goto file_err;
1802 (void) alarm(curclass.timeout);
1803 byte_count += c;
1804 total_data_in += c;
1805 total_data += c;
1806 total_bytes_in += c;
1807 total_bytes += c;
1808 }
1809 }
1810 recvdone:
1811 if (c < 0)
1812 goto data_err;
1813 rval = 0;
1814 goto cleanup_recv_data;
1815
1816 case TYPE_E:
1817 reply(553, "TYPE E not implemented.");
1818 goto cleanup_recv_data;
1819
1820 case TYPE_A:
1821 (void) alarm(curclass.timeout);
1822 /* XXXLUKEM: rate limit ascii receive (put) */
1823 while ((c = getc(instr)) != EOF) {
1824 byte_count++;
1825 total_data_in++;
1826 total_data++;
1827 total_bytes_in++;
1828 total_bytes++;
1829 if ((byte_count % 4096) == 0)
1830 (void) alarm(curclass.timeout);
1831 if (c == '\n')
1832 bare_lfs++;
1833 while (c == '\r') {
1834 if (ferror(outstr))
1835 goto data_err;
1836 if ((c = getc(instr)) != '\n') {
1837 byte_count++;
1838 total_data_in++;
1839 total_data++;
1840 total_bytes_in++;
1841 total_bytes++;
1842 if ((byte_count % 4096) == 0)
1843 (void) alarm(curclass.timeout);
1844 byteswritten++;
1845 FILESIZECHECK(byteswritten);
1846 (void) putc ('\r', outstr);
1847 if (c == '\0' || c == EOF)
1848 goto contin2;
1849 }
1850 }
1851 byteswritten++;
1852 FILESIZECHECK(byteswritten);
1853 (void) putc(c, outstr);
1854 contin2: ;
1855 }
1856 (void) alarm(0);
1857 fflush(outstr);
1858 if (ferror(instr))
1859 goto data_err;
1860 if (ferror(outstr))
1861 goto file_err;
1862 if (bare_lfs) {
1863 reply(-226,
1864 "WARNING! %d bare linefeeds received in ASCII mode",
1865 bare_lfs);
1866 reply(0, "File may not have transferred correctly.");
1867 }
1868 rval = 0;
1869 goto cleanup_recv_data;
1870
1871 default:
1872 reply(550, "Unimplemented TYPE %d in receive_data", type);
1873 goto cleanup_recv_data;
1874 }
1875 #undef FILESIZECHECK
1876
1877 data_err:
1878 (void) alarm(0);
1879 perror_reply(426, "Data Connection");
1880 goto cleanup_recv_data;
1881
1882 file_err:
1883 (void) alarm(0);
1884 perror_reply(452, "Error writing file");
1885 goto cleanup_recv_data;
1886
1887 cleanup_recv_data:
1888 (void) alarm(0);
1889 transflag = 0;
1890 total_files_in++;
1891 total_files++;
1892 total_xfers_in++;
1893 total_xfers++;
1894 return (rval);
1895 }
1896
1897 void
1898 statcmd(void)
1899 {
1900 struct sockinet *su = NULL;
1901 static char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
1902 u_char *a, *p;
1903 int ispassive, af;
1904 off_t otbi, otbo, otb;
1905
1906 a = p = (u_char *)NULL;
1907
1908 reply(-211, "%s FTP server status:", hostname);
1909 reply(0, "Version: %s", EMPTYSTR(version) ? "<suppressed>" : version);
1910 hbuf[0] = '\0';
1911 if (!getnameinfo((struct sockaddr *)&his_addr.si_su, his_addr.su_len,
1912 hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST)
1913 && strcmp(remotehost, hbuf) != 0)
1914 reply(0, "Connected to %s (%s)", remotehost, hbuf);
1915 else
1916 reply(0, "Connected to %s", remotehost);
1917
1918 if (logged_in) {
1919 if (curclass.type == CLASS_GUEST)
1920 reply(0, "Logged in anonymously");
1921 else
1922 reply(0, "Logged in as %s%s", pw->pw_name,
1923 curclass.type == CLASS_CHROOT ? " (chroot)" : "");
1924 } else if (askpasswd)
1925 reply(0, "Waiting for password");
1926 else
1927 reply(0, "Waiting for user name");
1928 cprintf(stdout, " TYPE: %s", typenames[type]);
1929 if (type == TYPE_A || type == TYPE_E)
1930 cprintf(stdout, ", FORM: %s", formnames[form]);
1931 if (type == TYPE_L) {
1932 #if NBBY == 8
1933 cprintf(stdout, " %d", NBBY);
1934 #else
1935 /* XXX: `bytesize' needs to be defined in this case */
1936 cprintf(stdout, " %d", bytesize);
1937 #endif
1938 }
1939 cprintf(stdout, "; STRUcture: %s; transfer MODE: %s\r\n",
1940 strunames[stru], modenames[mode]);
1941 ispassive = 0;
1942 if (data != -1) {
1943 reply(0, "Data connection open");
1944 su = NULL;
1945 } else if (pdata != -1) {
1946 reply(0, "in Passive mode");
1947 if (curclass.advertise.su_len != 0)
1948 su = &curclass.advertise;
1949 else
1950 su = &pasv_addr;
1951 ispassive = 1;
1952 goto printaddr;
1953 } else if (usedefault == 0) {
1954 if (epsvall) {
1955 reply(0, "EPSV only mode (EPSV ALL)");
1956 goto epsvonly;
1957 }
1958 su = (struct sockinet *)&data_dest;
1959 printaddr:
1960 /* PASV/PORT */
1961 if (su->su_family == AF_INET) {
1962 a = (u_char *) &su->su_addr;
1963 p = (u_char *) &su->su_port;
1964 #define UC(b) (((int) b) & 0xff)
1965 reply(0, "%s (%d,%d,%d,%d,%d,%d)",
1966 ispassive ? "PASV" : "PORT" ,
1967 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
1968 UC(p[0]), UC(p[1]));
1969 }
1970
1971 /* LPSV/LPRT */
1972 {
1973 int alen, i;
1974
1975 alen = 0;
1976 switch (su->su_family) {
1977 case AF_INET:
1978 a = (u_char *) &su->su_addr;
1979 p = (u_char *) &su->su_port;
1980 alen = sizeof(su->su_addr);
1981 af = 4;
1982 break;
1983 #ifdef INET6
1984 case AF_INET6:
1985 a = (u_char *) &su->su_6addr;
1986 p = (u_char *) &su->su_port;
1987 alen = sizeof(su->su_6addr);
1988 af = 6;
1989 break;
1990 #endif
1991 default:
1992 af = 0;
1993 break;
1994 }
1995 if (af) {
1996 cprintf(stdout, " %s (%d,%d",
1997 ispassive ? "LPSV" : "LPRT", af, alen);
1998 for (i = 0; i < alen; i++)
1999 cprintf(stdout, ",%d", UC(a[i]));
2000 cprintf(stdout, ",%d,%d,%d)\r\n",
2001 2, UC(p[0]), UC(p[1]));
2002 #undef UC
2003 }
2004 }
2005
2006 /* EPRT/EPSV */
2007 epsvonly:
2008 af = af2epsvproto(su->su_family);
2009 hbuf[0] = '\0';
2010 if (af > 0) {
2011 struct sockinet tmp;
2012
2013 tmp = *su;
2014 #ifdef INET6
2015 if (tmp.su_family == AF_INET6)
2016 tmp.su_scope_id = 0;
2017 #endif
2018 if (getnameinfo((struct sockaddr *)&tmp.si_su,
2019 tmp.su_len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
2020 NI_NUMERICHOST | NI_NUMERICSERV) == 0)
2021 reply(0, "%s (|%d|%s|%s|)",
2022 ispassive ? "EPSV" : "EPRT",
2023 af, hbuf, sbuf);
2024 }
2025 } else
2026 reply(0, "No data connection");
2027
2028 if (logged_in) {
2029 reply(0,
2030 "Data sent: " LLF " byte%s in " LLF " file%s",
2031 (LLT)total_data_out, PLURAL(total_data_out),
2032 (LLT)total_files_out, PLURAL(total_files_out));
2033 reply(0,
2034 "Data received: " LLF " byte%s in " LLF " file%s",
2035 (LLT)total_data_in, PLURAL(total_data_in),
2036 (LLT)total_files_in, PLURAL(total_files_in));
2037 reply(0,
2038 "Total data: " LLF " byte%s in " LLF " file%s",
2039 (LLT)total_data, PLURAL(total_data),
2040 (LLT)total_files, PLURAL(total_files));
2041 }
2042 otbi = total_bytes_in;
2043 otbo = total_bytes_out;
2044 otb = total_bytes;
2045 reply(0, "Traffic sent: " LLF " byte%s in " LLF " transfer%s",
2046 (LLT)otbo, PLURAL(otbo),
2047 (LLT)total_xfers_out, PLURAL(total_xfers_out));
2048 reply(0, "Traffic received: " LLF " byte%s in " LLF " transfer%s",
2049 (LLT)otbi, PLURAL(otbi),
2050 (LLT)total_xfers_in, PLURAL(total_xfers_in));
2051 reply(0, "Total traffic: " LLF " byte%s in " LLF " transfer%s",
2052 (LLT)otb, PLURAL(otb),
2053 (LLT)total_xfers, PLURAL(total_xfers));
2054
2055 if (logged_in && !CURCLASS_FLAGS_ISSET(private)) {
2056 struct ftpconv *cp;
2057
2058 reply(0, "%s", "");
2059 reply(0, "Class: %s, type: %s",
2060 curclass.classname, CURCLASSTYPE);
2061 reply(0, "Check PORT/LPRT commands: %sabled",
2062 CURCLASS_FLAGS_ISSET(checkportcmd) ? "en" : "dis");
2063 if (! EMPTYSTR(curclass.display))
2064 reply(0, "Display file: %s", curclass.display);
2065 if (! EMPTYSTR(curclass.notify))
2066 reply(0, "Notify fileglob: %s", curclass.notify);
2067 reply(0, "Idle timeout: %d, maximum timeout: %d",
2068 curclass.timeout, curclass.maxtimeout);
2069 reply(0, "Current connections: %d", connections);
2070 if (curclass.limit == -1)
2071 reply(0, "Maximum connections: unlimited");
2072 else
2073 reply(0, "Maximum connections: %d", curclass.limit);
2074 if (curclass.limitfile)
2075 reply(0, "Connection limit exceeded message file: %s",
2076 conffilename(curclass.limitfile));
2077 if (! EMPTYSTR(curclass.chroot))
2078 reply(0, "Chroot format: %s", curclass.chroot);
2079 reply(0, "Deny bad ftpusers(5) quickly: : %sabled",
2080 CURCLASS_FLAGS_ISSET(denyquick) ? "en" : "dis");
2081 if (! EMPTYSTR(curclass.homedir))
2082 reply(0, "Homedir format: %s", curclass.homedir);
2083 if (curclass.maxfilesize == -1)
2084 reply(0, "Maximum file size: unlimited");
2085 else
2086 reply(0, "Maximum file size: " LLF,
2087 (LLT)curclass.maxfilesize);
2088 if (! EMPTYSTR(curclass.motd))
2089 reply(0, "MotD file: %s", conffilename(curclass.motd));
2090 reply(0,
2091 "Modify commands (CHMOD, DELE, MKD, RMD, RNFR, UMASK): %sabled",
2092 CURCLASS_FLAGS_ISSET(modify) ? "en" : "dis");
2093 reply(0, "Upload commands (APPE, STOR, STOU): %sabled",
2094 CURCLASS_FLAGS_ISSET(upload) ? "en" : "dis");
2095 reply(0, "Sanitize file names: %sabled",
2096 CURCLASS_FLAGS_ISSET(sanenames) ? "en" : "dis");
2097 reply(0, "PASV/LPSV/EPSV connections: %sabled",
2098 CURCLASS_FLAGS_ISSET(passive) ? "en" : "dis");
2099 if (curclass.advertise.su_len != 0) {
2100 char buf[50]; /* big enough for IPv6 address */
2101 const char *bp;
2102
2103 bp = inet_ntop(curclass.advertise.su_family,
2104 (void *)&curclass.advertise.su_addr,
2105 buf, sizeof(buf));
2106 if (bp != NULL)
2107 reply(0, "PASV advertise address: %s", bp);
2108 }
2109 if (curclass.portmin && curclass.portmax)
2110 reply(0, "PASV port range: %d - %d",
2111 curclass.portmin, curclass.portmax);
2112 if (curclass.rateget)
2113 reply(0, "Rate get limit: " LLF " bytes/sec",
2114 (LLT)curclass.rateget);
2115 else
2116 reply(0, "Rate get limit: disabled");
2117 if (curclass.rateput)
2118 reply(0, "Rate put limit: " LLF " bytes/sec",
2119 (LLT)curclass.rateput);
2120 else
2121 reply(0, "Rate put limit: disabled");
2122 reply(0, "Umask: %.04o", curclass.umask);
2123 for (cp = curclass.conversions; cp != NULL; cp=cp->next) {
2124 if (cp->suffix == NULL || cp->types == NULL ||
2125 cp->command == NULL)
2126 continue;
2127 reply(0, "Conversion: %s [%s] disable: %s, command: %s",
2128 cp->suffix, cp->types, cp->disable, cp->command);
2129 }
2130 }
2131
2132 reply(211, "End of status");
2133 }
2134
2135 void
2136 fatal(const char *s)
2137 {
2138
2139 reply(451, "Error in server: %s\n", s);
2140 reply(221, "Closing connection due to server error.");
2141 dologout(0);
2142 /* NOTREACHED */
2143 }
2144
2145 /*
2146 * reply() --
2147 * depending on the value of n, display fmt with a trailing CRLF and
2148 * prefix of:
2149 * n < -1 prefix the message with abs(n) + "-" (initial line)
2150 * n == 0 prefix the message with 4 spaces (middle lines)
2151 * n > 0 prefix the message with n + " " (final line)
2152 */
2153 void
2154 reply(int n, const char *fmt, ...)
2155 {
2156 off_t b;
2157 va_list ap;
2158
2159 va_start(ap, fmt);
2160 b = 0;
2161 if (n == 0)
2162 cprintf(stdout, " ");
2163 else if (n < 0)
2164 cprintf(stdout, "%d-", -n);
2165 else
2166 cprintf(stdout, "%d ", n);
2167 b = vprintf(fmt, ap);
2168 va_end(ap);
2169 total_bytes += b;
2170 total_bytes_out += b;
2171 cprintf(stdout, "\r\n");
2172 (void)fflush(stdout);
2173 if (debug) {
2174 syslog(LOG_DEBUG, "<--- %d%c", abs(n), (n < 0) ? '-' : ' ');
2175 va_start(ap, fmt);
2176 vsyslog(LOG_DEBUG, fmt, ap);
2177 va_end(ap);
2178 }
2179 }
2180
2181 static void
2182 logremotehost(struct sockinet *who)
2183 {
2184
2185 if (getnameinfo((struct sockaddr *)&who->si_su,
2186 who->su_len, remotehost, sizeof(remotehost), NULL, 0, 0))
2187 strlcpy(remotehost, "?", sizeof(remotehost));
2188
2189 #if HAVE_SETPROCTITLE
2190 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
2191 setproctitle("%s", proctitle);
2192 #endif /* HAVE_SETPROCTITLE */
2193 if (logging)
2194 syslog(LOG_INFO, "connection from %s to %s",
2195 remotehost, hostname);
2196 }
2197
2198 /*
2199 * Record logout in wtmp file and exit with supplied status.
2200 */
2201 void
2202 dologout(int status)
2203 {
2204 /*
2205 * Prevent reception of SIGURG from resulting in a resumption
2206 * back to the main program loop.
2207 */
2208 transflag = 0;
2209
2210 if (logged_in) {
2211 if (dowtmp)
2212 logwtmp(ttyline, "", "");
2213 if (doutmp)
2214 logout(utmp.ut_line);
2215 #ifdef KERBEROS
2216 if (!notickets && krbtkfile_env)
2217 unlink(krbtkfile_env);
2218 #endif
2219 }
2220 /* beware of flushing buffers after a SIGPIPE */
2221 _exit(status);
2222 }
2223
2224 void
2225 abor(void)
2226 {
2227
2228 tmpline[0] = '\0';
2229 is_oob = 0;
2230 reply(426, "Transfer aborted. Data connection closed.");
2231 reply(226, "Abort successful");
2232 longjmp(urgcatch, 1);
2233 }
2234
2235 void
2236 statxfer(void)
2237 {
2238
2239 tmpline[0] = '\0';
2240 is_oob = 0;
2241 if (file_size != (off_t) -1)
2242 reply(213,
2243 "Status: " LLF " of " LLF " byte%s transferred",
2244 (LLT)byte_count, (LLT)file_size,
2245 PLURAL(byte_count));
2246 else
2247 reply(213, "Status: " LLF " byte%s transferred",
2248 (LLT)byte_count, PLURAL(byte_count));
2249 }
2250
2251 static void
2252 myoob(int signo)
2253 {
2254 char *cp;
2255
2256 /* only process if transfer occurring */
2257 if (!transflag)
2258 return;
2259 cp = tmpline;
2260 if (getline(cp, sizeof(tmpline), stdin) == NULL) {
2261 reply(221, "You could at least say goodbye.");
2262 dologout(0);
2263 }
2264 is_oob = 1;
2265 ftp_handle_line(cp);
2266 is_oob = 0;
2267 }
2268
2269 static int
2270 bind_pasv_addr(void)
2271 {
2272 static int passiveport;
2273 int port, len;
2274
2275 len = pasv_addr.su_len;
2276 if (curclass.portmin == 0 && curclass.portmax == 0) {
2277 pasv_addr.su_port = 0;
2278 return (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len));
2279 }
2280
2281 if (passiveport == 0) {
2282 srand(getpid());
2283 passiveport = rand() % (curclass.portmax - curclass.portmin)
2284 + curclass.portmin;
2285 }
2286
2287 port = passiveport;
2288 while (1) {
2289 port++;
2290 if (port > curclass.portmax)
2291 port = curclass.portmin;
2292 else if (port == passiveport) {
2293 errno = EAGAIN;
2294 return (-1);
2295 }
2296 pasv_addr.su_port = htons(port);
2297 if (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len) == 0)
2298 break;
2299 if (errno != EADDRINUSE)
2300 return (-1);
2301 }
2302 passiveport = port;
2303 return (0);
2304 }
2305
2306 /*
2307 * Note: a response of 425 is not mentioned as a possible response to
2308 * the PASV command in RFC959. However, it has been blessed as
2309 * a legitimate response by Jon Postel in a telephone conversation
2310 * with Rick Adams on 25 Jan 89.
2311 */
2312 void
2313 passive(void)
2314 {
2315 int len;
2316 char *p, *a;
2317
2318 if (pdata >= 0)
2319 close(pdata);
2320 pdata = socket(AF_INET, SOCK_STREAM, 0);
2321 if (pdata < 0 || !logged_in) {
2322 perror_reply(425, "Can't open passive connection");
2323 return;
2324 }
2325 pasv_addr = ctrl_addr;
2326
2327 if (bind_pasv_addr() < 0)
2328 goto pasv_error;
2329 len = pasv_addr.su_len;
2330 if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
2331 goto pasv_error;
2332 pasv_addr.su_len = len;
2333 if (listen(pdata, 1) < 0)
2334 goto pasv_error;
2335 if (curclass.advertise.su_len != 0)
2336 a = (char *) &curclass.advertise.su_addr;
2337 else
2338 a = (char *) &pasv_addr.su_addr;
2339 p = (char *) &pasv_addr.su_port;
2340
2341 #define UC(b) (((int) b) & 0xff)
2342
2343 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2344 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2345 return;
2346
2347 pasv_error:
2348 (void) close(pdata);
2349 pdata = -1;
2350 perror_reply(425, "Can't open passive connection");
2351 return;
2352 }
2353
2354 /*
2355 * convert protocol identifier to/from AF
2356 */
2357 int
2358 lpsvproto2af(int proto)
2359 {
2360
2361 switch (proto) {
2362 case 4:
2363 return AF_INET;
2364 #ifdef INET6
2365 case 6:
2366 return AF_INET6;
2367 #endif
2368 default:
2369 return -1;
2370 }
2371 }
2372
2373 int
2374 af2lpsvproto(int af)
2375 {
2376
2377 switch (af) {
2378 case AF_INET:
2379 return 4;
2380 #ifdef INET6
2381 case AF_INET6:
2382 return 6;
2383 #endif
2384 default:
2385 return -1;
2386 }
2387 }
2388
2389 int
2390 epsvproto2af(int proto)
2391 {
2392
2393 switch (proto) {
2394 case 1:
2395 return AF_INET;
2396 #ifdef INET6
2397 case 2:
2398 return AF_INET6;
2399 #endif
2400 default:
2401 return -1;
2402 }
2403 }
2404
2405 int
2406 af2epsvproto(int af)
2407 {
2408
2409 switch (af) {
2410 case AF_INET:
2411 return 1;
2412 #ifdef INET6
2413 case AF_INET6:
2414 return 2;
2415 #endif
2416 default:
2417 return -1;
2418 }
2419 }
2420
2421 /*
2422 * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)
2423 * 229 Entering Extended Passive Mode (|||port|)
2424 */
2425 void
2426 long_passive(char *cmd, int pf)
2427 {
2428 int len;
2429 char *p, *a;
2430
2431 if (!logged_in) {
2432 syslog(LOG_NOTICE, "long passive but not logged in");
2433 reply(503, "Login with USER first.");
2434 return;
2435 }
2436
2437 if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) {
2438 /*
2439 * XXX: only EPRT/EPSV ready clients will understand this
2440 */
2441 if (strcmp(cmd, "EPSV") != 0)
2442 reply(501, "Network protocol mismatch"); /*XXX*/
2443 else
2444 epsv_protounsupp("Network protocol mismatch");
2445
2446 return;
2447 }
2448
2449 if (pdata >= 0)
2450 close(pdata);
2451 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2452 if (pdata < 0) {
2453 perror_reply(425, "Can't open passive connection");
2454 return;
2455 }
2456 pasv_addr = ctrl_addr;
2457 if (bind_pasv_addr() < 0)
2458 goto pasv_error;
2459 len = pasv_addr.su_len;
2460 if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
2461 goto pasv_error;
2462 pasv_addr.su_len = len;
2463 if (listen(pdata, 1) < 0)
2464 goto pasv_error;
2465 p = (char *) &pasv_addr.su_port;
2466
2467 #define UC(b) (((int) b) & 0xff)
2468
2469 if (strcmp(cmd, "LPSV") == 0) {
2470 struct sockinet *advert;
2471
2472 if (curclass.advertise.su_len != 0)
2473 advert = &curclass.advertise;
2474 else
2475 advert = &pasv_addr;
2476 switch (advert->su_family) {
2477 case AF_INET:
2478 a = (char *) &advert->su_addr;
2479 reply(228,
2480 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2481 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2482 2, UC(p[0]), UC(p[1]));
2483 return;
2484 #ifdef INET6
2485 case AF_INET6:
2486 a = (char *) &advert->su_6addr;
2487 reply(228,
2488 "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)",
2489 6, 16,
2490 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2491 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2492 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2493 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2494 2, UC(p[0]), UC(p[1]));
2495 return;
2496 #endif
2497 }
2498 #undef UC
2499 } else if (strcmp(cmd, "EPSV") == 0) {
2500 switch (pasv_addr.su_family) {
2501 case AF_INET:
2502 #ifdef INET6
2503 case AF_INET6:
2504 #endif
2505 reply(229, "Entering Extended Passive Mode (|||%d|)",
2506 ntohs(pasv_addr.su_port));
2507 return;
2508 }
2509 } else {
2510 /* more proper error code? */
2511 }
2512
2513 pasv_error:
2514 (void) close(pdata);
2515 pdata = -1;
2516 perror_reply(425, "Can't open passive connection");
2517 return;
2518 }
2519
2520 int
2521 extended_port(const char *arg)
2522 {
2523 char *tmp = NULL;
2524 char *result[3];
2525 char *p, *q;
2526 char delim;
2527 struct addrinfo hints;
2528 struct addrinfo *res = NULL;
2529 int i;
2530 unsigned long proto;
2531
2532 tmp = xstrdup(arg);
2533 p = tmp;
2534 delim = p[0];
2535 p++;
2536 memset(result, 0, sizeof(result));
2537 for (i = 0; i < 3; i++) {
2538 q = strchr(p, delim);
2539 if (!q || *q != delim)
2540 goto parsefail;
2541 *q++ = '\0';
2542 result[i] = p;
2543 p = q;
2544 }
2545
2546 /* some more sanity checks */
2547 p = NULL;
2548 (void)strtoul(result[2], &p, 10);
2549 if (!*result[2] || *p)
2550 goto parsefail;
2551 p = NULL;
2552 proto = strtoul(result[0], &p, 10);
2553 if (!*result[0] || *p)
2554 goto protounsupp;
2555
2556 memset(&hints, 0, sizeof(hints));
2557 hints.ai_family = epsvproto2af((int)proto);
2558 if (hints.ai_family < 0)
2559 goto protounsupp;
2560 hints.ai_socktype = SOCK_STREAM;
2561 hints.ai_flags = AI_NUMERICHOST;
2562 if (getaddrinfo(result[1], result[2], &hints, &res))
2563 goto parsefail;
2564 if (res->ai_next)
2565 goto parsefail;
2566 if (sizeof(data_dest) < res->ai_addrlen)
2567 goto parsefail;
2568 memcpy(&data_dest.si_su, res->ai_addr, res->ai_addrlen);
2569 data_dest.su_len = res->ai_addrlen;
2570 #ifdef INET6
2571 if (his_addr.su_family == AF_INET6 &&
2572 data_dest.su_family == AF_INET6) {
2573 /* XXX: more sanity checks! */
2574 data_dest.su_scope_id = his_addr.su_scope_id;
2575 }
2576 #endif
2577
2578 if (tmp != NULL)
2579 free(tmp);
2580 if (res)
2581 freeaddrinfo(res);
2582 return 0;
2583
2584 parsefail:
2585 reply(500, "Invalid argument, rejected.");
2586 usedefault = 1;
2587 if (tmp != NULL)
2588 free(tmp);
2589 if (res)
2590 freeaddrinfo(res);
2591 return -1;
2592
2593 protounsupp:
2594 epsv_protounsupp("Protocol not supported");
2595 usedefault = 1;
2596 if (tmp != NULL)
2597 free(tmp);
2598 if (res)
2599 freeaddrinfo(res);
2600 return -1;
2601 }
2602
2603 /*
2604 * 522 Protocol not supported (proto,...)
2605 * as we assume address family for control and data connections are the same,
2606 * we do not return the list of address families we support - instead, we
2607 * return the address family of the control connection.
2608 */
2609 void
2610 epsv_protounsupp(const char *message)
2611 {
2612 int proto;
2613
2614 proto = af2epsvproto(ctrl_addr.su_family);
2615 if (proto < 0)
2616 reply(501, "%s", message); /* XXX */
2617 else
2618 reply(522, "%s, use (%d)", message, proto);
2619 }
2620
2621 /*
2622 * Generate unique name for file with basename "local".
2623 * The file named "local" is already known to exist.
2624 * Generates failure reply on error.
2625 *
2626 * XXX: this function should under go changes similar to
2627 * the mktemp(3)/mkstemp(3) changes.
2628 */
2629 static char *
2630 gunique(const char *local)
2631 {
2632 static char new[MAXPATHLEN];
2633 struct stat st;
2634 char *cp;
2635 int count;
2636
2637 cp = strrchr(local, '/');
2638 if (cp)
2639 *cp = '\0';
2640 if (stat(cp ? local : ".", &st) < 0) {
2641 perror_reply(553, cp ? local : ".");
2642 return (NULL);
2643 }
2644 if (cp)
2645 *cp = '/';
2646 for (count = 1; count < 100; count++) {
2647 (void)snprintf(new, sizeof(new) - 1, "%s.%d", local, count);
2648 if (stat(new, &st) < 0)
2649 return (new);
2650 }
2651 reply(452, "Unique file name cannot be created.");
2652 return (NULL);
2653 }
2654
2655 /*
2656 * Format and send reply containing system error number.
2657 */
2658 void
2659 perror_reply(int code, const char *string)
2660 {
2661 int save_errno;
2662
2663 save_errno = errno;
2664 reply(code, "%s: %s.", string, strerror(errno));
2665 errno = save_errno;
2666 }
2667
2668 static char *onefile[] = {
2669 "",
2670 0
2671 };
2672
2673 void
2674 send_file_list(const char *whichf)
2675 {
2676 struct stat st;
2677 DIR *dirp = NULL;
2678 struct dirent *dir;
2679 FILE *dout = NULL;
2680 char **dirlist, *dirname, *notglob, *p;
2681 int simple = 0;
2682 int freeglob = 0;
2683 glob_t gl;
2684
2685 #ifdef __GNUC__
2686 (void) &dout;
2687 (void) &dirlist;
2688 (void) &simple;
2689 (void) &freeglob;
2690 #endif
2691
2692 p = NULL;
2693 if (strpbrk(whichf, "~{[*?") != NULL) {
2694 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE|GLOB_LIMIT;
2695
2696 memset(&gl, 0, sizeof(gl));
2697 freeglob = 1;
2698 if (glob(whichf, flags, 0, &gl)) {
2699 reply(550, "not found");
2700 goto out;
2701 } else if (gl.gl_pathc == 0) {
2702 errno = ENOENT;
2703 perror_reply(550, whichf);
2704 goto out;
2705 }
2706 dirlist = gl.gl_pathv;
2707 } else {
2708 notglob = xstrdup(whichf);
2709 onefile[0] = notglob;
2710 dirlist = onefile;
2711 simple = 1;
2712 }
2713 /* XXX: } for vi sm */
2714
2715 if (setjmp(urgcatch)) {
2716 transflag = 0;
2717 goto out;
2718 }
2719 while ((dirname = *dirlist++) != NULL) {
2720 int trailingslash = 0;
2721
2722 if (stat(dirname, &st) < 0) {
2723 /*
2724 * If user typed "ls -l", etc, and the client
2725 * used NLST, do what the user meant.
2726 */
2727 /* XXX: nuke this support? */
2728 if (dirname[0] == '-' && *dirlist == NULL &&
2729 transflag == 0) {
2730 char *argv[] = { INTERNAL_LS, "", NULL };
2731
2732 argv[1] = dirname;
2733 retrieve(argv, dirname);
2734 goto out;
2735 }
2736 perror_reply(550, whichf);
2737 goto cleanup_send_file_list;
2738 }
2739
2740 if (S_ISREG(st.st_mode)) {
2741 /*
2742 * XXXRFC:
2743 * should we follow RFC959 and not work
2744 * for non directories?
2745 */
2746 if (dout == NULL) {
2747 dout = dataconn("file list", (off_t)-1, "w");
2748 if (dout == NULL)
2749 goto out;
2750 transflag++;
2751 }
2752 cprintf(dout, "%s%s\n", dirname,
2753 type == TYPE_A ? "\r" : "");
2754 continue;
2755 } else if (!S_ISDIR(st.st_mode))
2756 continue;
2757
2758 if (dirname[strlen(dirname) - 1] == '/')
2759 trailingslash++;
2760
2761 if ((dirp = opendir(dirname)) == NULL)
2762 continue;
2763
2764 while ((dir = readdir(dirp)) != NULL) {
2765 char nbuf[MAXPATHLEN];
2766
2767 if (ISDOTDIR(dir->d_name) || ISDOTDOTDIR(dir->d_name))
2768 continue;
2769
2770 (void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
2771 trailingslash ? "" : "/", dir->d_name);
2772
2773 /*
2774 * We have to do a stat to ensure it's
2775 * not a directory or special file.
2776 */
2777 /*
2778 * XXXRFC:
2779 * should we follow RFC959 and filter out
2780 * non files ? lukem - NO!, or not until
2781 * our ftp client uses MLS{T,D} for completion.
2782 */
2783 if (simple || (stat(nbuf, &st) == 0 &&
2784 S_ISREG(st.st_mode))) {
2785 if (dout == NULL) {
2786 dout = dataconn("file list", (off_t)-1,
2787 "w");
2788 if (dout == NULL)
2789 goto out;
2790 transflag++;
2791 }
2792 p = nbuf;
2793 if (nbuf[0] == '.' && nbuf[1] == '/')
2794 p = &nbuf[2];
2795 cprintf(dout, "%s%s\n", p,
2796 type == TYPE_A ? "\r" : "");
2797 }
2798 }
2799 (void) closedir(dirp);
2800 }
2801
2802 if (dout == NULL)
2803 reply(550, "No files found.");
2804 else if (ferror(dout) != 0)
2805 perror_reply(550, "Data connection");
2806 else
2807 reply(226, "Transfer complete.");
2808
2809 cleanup_send_file_list:
2810 transflag = 0;
2811 closedataconn(dout);
2812 out:
2813 total_xfers++;
2814 total_xfers_out++;
2815 if (notglob)
2816 free(notglob);
2817 if (freeglob)
2818 globfree(&gl);
2819 }
2820
2821 char *
2822 conffilename(const char *s)
2823 {
2824 static char filename[MAXPATHLEN];
2825
2826 if (*s == '/')
2827 strlcpy(filename, s, sizeof(filename));
2828 else
2829 (void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
2830 return (filename);
2831 }
2832
2833 /*
2834 * logxfer --
2835 * if logging > 1, then based on the arguments, syslog a message:
2836 * if bytes != -1 "<command> <file1> = <bytes> bytes"
2837 * else if file2 != NULL "<command> <file1> <file2>"
2838 * else "<command> <file1>"
2839 * if elapsed != NULL, append "in xxx.yyy seconds"
2840 * if error != NULL, append ": " + error
2841 *
2842 * if doxferlog != 0, syslog a wu-ftpd style xferlog entry
2843 */
2844 void
2845 logxfer(const char *command, off_t bytes, const char *file1, const char *file2,
2846 const struct timeval *elapsed, const char *error)
2847 {
2848 char buf[MAXPATHLEN * 2 + 100], realfile[MAXPATHLEN];
2849 const char *r1, *r2;
2850 char direction;
2851 size_t len;
2852 time_t now;
2853
2854 if (logging <=1 && !doxferlog)
2855 return;
2856
2857 r1 = r2 = NULL;
2858 if ((r1 = realpath(file1, realfile)) == NULL)
2859 r1 = file1;
2860 if (file2 != NULL)
2861 if ((r2 = realpath(file2, realfile)) == NULL)
2862 r2 = file2;
2863
2864 /*
2865 * syslog command
2866 */
2867 if (logging > 1) {
2868 len = snprintf(buf, sizeof(buf), "%s %s", command, r1);
2869 if (bytes != (off_t)-1)
2870 len += snprintf(buf + len, sizeof(buf) - len,
2871 " = " LLF " byte%s", (LLT) bytes, PLURAL(bytes));
2872 else if (r2 != NULL)
2873 len += snprintf(buf + len, sizeof(buf) - len,
2874 " %s", r2);
2875 if (elapsed != NULL)
2876 len += snprintf(buf + len, sizeof(buf) - len,
2877 " in %ld.%.03d seconds", elapsed->tv_sec,
2878 (int)(elapsed->tv_usec / 1000));
2879 if (error != NULL)
2880 len += snprintf(buf + len, sizeof(buf) - len,
2881 ": %s", error);
2882 syslog(LOG_INFO, "%s", buf);
2883 }
2884
2885
2886 /*
2887 * syslog wu-ftpd style log entry, prefixed with "xferlog: "
2888 */
2889 if (!doxferlog)
2890 return;
2891
2892 if (strcmp(command, "get") == 0)
2893 direction = 'o';
2894 else if (strcmp(command, "put") == 0 || strcmp(command, "append") == 0)
2895 direction = 'i';
2896 else
2897 return;
2898
2899 time(&now);
2900 syslog(LOG_INFO,
2901 "xferlog%s: %.24s %ld %s " LLF " %s %c %s %c %c %s FTP 0 * %c",
2902
2903 /*
2904 * XXX: wu-ftpd puts (send) or (recv) in the syslog message, and removes
2905 * the full date. This may be problematic for accurate log parsing,
2906 * given that syslog messages don't contain the full date.
2907 */
2908 #if 1 /* lukem's method; easier to convert to actual xferlog file */
2909 "",
2910 ctime(&now),
2911 #else /* wu-ftpd's syslog method, with an extra unneeded space */
2912 (direction == 'i') ? " (recv)" : " (send)",
2913 "",
2914 #endif
2915 elapsed == NULL ? 0 : elapsed->tv_sec + (elapsed->tv_usec > 0),
2916 remotehost,
2917 bytes == (off_t)-1 ? 0 : (LLT) bytes,
2918 r1,
2919 type == TYPE_A ? 'a' : 'b',
2920 "_", /* XXX: take conversions into account? */
2921 direction,
2922
2923 curclass.type == CLASS_GUEST ? 'a' :
2924 curclass.type == CLASS_CHROOT ? 'g' :
2925 curclass.type == CLASS_REAL ? 'r' : '?',
2926
2927 curclass.type == CLASS_GUEST ? pw->pw_passwd : pw->pw_name,
2928 error != NULL ? 'i' : 'c'
2929 );
2930 }
2931
2932 /*
2933 * Determine if `password' is valid for user given in `pw'.
2934 * Returns 2 if password expired, 1 if otherwise failed, 0 if ok
2935 */
2936 int
2937 checkpassword(const struct passwd *pwent, const char *password)
2938 {
2939 char *orig, *new;
2940 time_t expire;
2941
2942 expire = 0;
2943 if (pwent == NULL)
2944 return 1;
2945
2946 orig = pwent->pw_passwd; /* save existing password */
2947 expire = pwent->pw_expire;
2948
2949 if (orig[0] == '\0') /* don't allow empty passwords */
2950 return 1;
2951
2952 new = crypt(password, orig); /* encrypt given password */
2953 if (strcmp(new, orig) != 0) /* compare */
2954 return 1;
2955
2956 if (expire && time(NULL) >= expire)
2957 return 2; /* check if expired */
2958
2959 return 0; /* OK! */
2960 }
2961
2962 char *
2963 xstrdup(const char *s)
2964 {
2965 char *new = strdup(s);
2966
2967 if (new == NULL)
2968 fatal("Local resource failure: malloc");
2969 /* NOTREACHED */
2970 return (new);
2971 }
2972
2973 /*
2974 * As per fprintf(), but increment total_bytes and total_bytes_out,
2975 * by the appropriate amount.
2976 */
2977 void
2978 cprintf(FILE *fd, const char *fmt, ...)
2979 {
2980 off_t b;
2981 va_list ap;
2982
2983 va_start(ap, fmt);
2984 b = vfprintf(fd, fmt, ap);
2985 va_end(ap);
2986 total_bytes += b;
2987 total_bytes_out += b;
2988 }
2989