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