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