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