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