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