ftpd.c revision 1.111 1 /* $NetBSD: ftpd.c,v 1.111 2000/11/16 13:15:14 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.111 2000/11/16 13:15:14 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 sockaddr *);
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 struct passwd *sgetpwnam(const char *);
222
223 int main(int, char *[]);
224
225 #if defined(KERBEROS)
226 int klogin(struct passwd *, char *, char *, char *);
227 void kdestroy(void);
228 #endif
229 #if defined(KERBEROS5)
230 int k5login(struct passwd *, char *, char *, char *);
231 void k5destroy(void);
232 #endif
233
234 int
235 main(int argc, char *argv[])
236 {
237 int addrlen, ch, on = 1, tos, keepalive;
238 #ifdef KERBEROS5
239 krb5_error_code kerror;
240 #endif
241 char *p;
242
243 connections = 1;
244 debug = 0;
245 logging = 0;
246 pdata = -1;
247 sflag = 0;
248 dataport = 0;
249 dopidfile = 1; /* default: DO use a pid file to count users */
250 doutmp = 0; /* default: don't log to utmp */
251 dowtmp = 1; /* default: DO log to wtmp */
252 dropprivs = 0;
253 mapped = 0;
254 usedefault = 1;
255 emailaddr = NULL;
256 hostname[0] = '\0';
257 homedir[0] = '\0';
258 gidcount = 0;
259 version = FTPD_VERSION;
260
261 /*
262 * LOG_NDELAY sets up the logging connection immediately,
263 * necessary for anonymous ftp's that chroot and can't do it later.
264 */
265 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
266
267 while ((ch = getopt(argc, argv, "a:c:C:de:h:HlP:qQrst:T:uUvV:wW"))
268 != -1) {
269 switch (ch) {
270 case 'a':
271 anondir = optarg;
272 break;
273
274 case 'c':
275 confdir = optarg;
276 break;
277
278 case 'C':
279 pw = sgetpwnam(optarg);
280 exit(checkaccess(optarg) ? 0 : 1);
281 /* NOTREACHED */
282
283 case 'd':
284 case 'v': /* deprecated */
285 debug = 1;
286 break;
287
288 case 'e':
289 emailaddr = optarg;
290 break;
291
292 case 'h':
293 strlcpy(hostname, optarg, sizeof(hostname));
294 break;
295
296 case 'H':
297 if (gethostname(hostname, sizeof(hostname)) == -1)
298 hostname[0] = '\0';
299 hostname[sizeof(hostname) - 1] = '\0';
300 break;
301
302 case 'l':
303 logging++; /* > 1 == extra logging */
304 break;
305
306 case 'P':
307 dataport = (int)strtol(optarg, &p, 10);
308 if (*p != '\0' || dataport < IPPORT_RESERVED ||
309 dataport > IPPORT_ANONMAX) {
310 syslog(LOG_WARNING, "Invalid dataport %s",
311 optarg);
312 dataport = 0;
313 }
314 break;
315
316 case 'q':
317 dopidfile = 1;
318 break;
319
320 case 'Q':
321 dopidfile = 0;
322 break;
323
324 case 'r':
325 dropprivs = 1;
326 break;
327
328 case 's':
329 sflag = 1;
330 break;
331
332 case 't':
333 case 'T':
334 syslog(LOG_ERR,
335 "-%c has been deprecated in favour of ftpd.conf",
336 ch);
337 break;
338
339 case 'u':
340 doutmp = 1;
341 break;
342
343 case 'U':
344 doutmp = 0;
345 break;
346
347 case 'V':
348 if (EMPTYSTR(optarg) || strcmp(optarg, "-") == 0)
349 version = NULL;
350 else
351 version = xstrdup(optarg);
352 break;
353
354 case 'w':
355 dowtmp = 1;
356 break;
357
358 case 'W':
359 dowtmp = 0;
360 break;
361
362 default:
363 if (optopt == 'a' || optopt == 'C')
364 exit(1);
365 syslog(LOG_ERR, "unknown flag -%c ignored", optopt);
366 break;
367 }
368 }
369 if (EMPTYSTR(confdir))
370 confdir = _DEFAULT_CONFDIR;
371
372 memset((char *)&his_addr, 0, sizeof (his_addr));
373 addrlen = sizeof(his_addr.si_su);
374 if (getpeername(0, (struct sockaddr *)&his_addr.si_su, &addrlen) < 0) {
375 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
376 exit(1);
377 }
378 his_addr.su_len = addrlen;
379 memset((char *)&ctrl_addr, 0, sizeof (ctrl_addr));
380 addrlen = sizeof(ctrl_addr.si_su);
381 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
382 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
383 exit(1);
384 }
385 ctrl_addr.su_len = addrlen;
386 #ifdef INET6
387 if (his_addr.su_family == AF_INET6
388 && IN6_IS_ADDR_V4MAPPED(&his_addr.su_6addr)) {
389 #if 1
390 /*
391 * IPv4 control connection arrived to AF_INET6 socket.
392 * I hate to do this, but this is the easiest solution.
393 *
394 * The assumption is untrue on SIIT environment.
395 */
396 struct sockinet tmp_addr;
397 const int off = sizeof(struct in6_addr) - sizeof(struct in_addr);
398
399 tmp_addr = his_addr;
400 memset(&his_addr, 0, sizeof(his_addr));
401 his_addr.su_family = AF_INET;
402 his_addr.su_len = sizeof(his_addr.si_su.su_sin);
403 memcpy(&his_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off],
404 sizeof(his_addr.su_addr));
405 his_addr.su_port = tmp_addr.su_port;
406
407 tmp_addr = ctrl_addr;
408 memset(&ctrl_addr, 0, sizeof(ctrl_addr));
409 ctrl_addr.su_family = AF_INET;
410 ctrl_addr.su_len = sizeof(ctrl_addr.si_su.su_sin);
411 memcpy(&ctrl_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off],
412 sizeof(ctrl_addr.su_addr));
413 ctrl_addr.su_port = tmp_addr.su_port;
414 #else
415 while (fgets(line, sizeof(line), fd) != NULL) {
416 if ((cp = strchr(line, '\n')) != NULL)
417 *cp = '\0';
418 reply(-530, "%s", line);
419 }
420 (void) fflush(stdout);
421 (void) fclose(fd);
422 reply(530,
423 "Connection from IPv4 mapped address is not supported.");
424 exit(0);
425 #endif
426
427 mapped = 1;
428 } else
429 #endif /* INET6 */
430 mapped = 0;
431 #ifdef IP_TOS
432 if (!mapped && his_addr.su_family == AF_INET) {
433 tos = IPTOS_LOWDELAY;
434 if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos,
435 sizeof(int)) < 0)
436 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
437 }
438 #endif
439 /* if the hostname hasn't been given, attempt to determine it */
440 if (hostname[0] == '\0') {
441 if (getnameinfo((struct sockaddr *)&ctrl_addr.si_su,
442 ctrl_addr.su_len, hostname, sizeof(hostname), NULL, 0, 0)
443 != 0)
444 (void)gethostname(hostname, sizeof(hostname));
445 hostname[sizeof(hostname) - 1] = '\0';
446 }
447
448 /* set this here so klogin can use it... */
449 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
450
451 (void) freopen(_PATH_DEVNULL, "w", stderr);
452 (void) signal(SIGPIPE, lostconn);
453 (void) signal(SIGCHLD, SIG_IGN);
454 if (signal(SIGURG, myoob) == SIG_ERR)
455 syslog(LOG_ERR, "signal: %m");
456
457 /* Try to handle urgent data inline */
458 #ifdef SO_OOBINLINE
459 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
460 syslog(LOG_ERR, "setsockopt: %m");
461 #endif
462 /* Set keepalives on the socket to detect dropped connections. */
463 #ifdef SO_KEEPALIVE
464 keepalive = 1;
465 if (setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepalive,
466 sizeof(int)) < 0)
467 syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
468 #endif
469
470 #ifdef F_SETOWN
471 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
472 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
473 #endif
474 dolog((struct sockaddr *)&his_addr);
475 /*
476 * Set up default state
477 */
478 data = -1;
479 type = TYPE_A;
480 form = FORM_N;
481 stru = STRU_F;
482 mode = MODE_S;
483 tmpline[0] = '\0';
484 hasyyerrored = 0;
485
486 #ifdef KERBEROS5
487 kerror = krb5_init_context(&kcontext);
488 if (kerror) {
489 syslog(LOG_NOTICE, "%s when initializing Kerberos context",
490 error_message(kerror));
491 exit(0);
492 }
493 #endif /* KERBEROS5 */
494
495 init_curclass();
496 curclass.timeout = 300; /* 5 minutes, as per login(1) */
497 curclass.type = CLASS_REAL;
498
499 /* If logins are disabled, print out the message. */
500 if (display_file(_PATH_NOLOGIN, 530)) {
501 reply(530, "System not available.");
502 exit(0);
503 }
504 (void)display_file(conffilename(_PATH_FTPWELCOME), 220);
505 /* reply(220,) must follow */
506 if (EMPTYSTR(version))
507 reply(220, "%s FTP server ready.", hostname);
508 else
509 reply(220, "%s FTP server (%s) ready.", hostname, version);
510
511 (void) setjmp(errcatch);
512 for (;;)
513 (void) yyparse();
514 /* NOTREACHED */
515 }
516
517 static void
518 lostconn(int signo)
519 {
520
521 if (debug)
522 syslog(LOG_DEBUG, "lost connection");
523 dologout(1);
524 }
525
526 /*
527 * Save the result of a getpwnam. Used for USER command, since
528 * the data returned must not be clobbered by any other command
529 * (e.g., globbing).
530 */
531 static struct passwd *
532 sgetpwnam(const char *name)
533 {
534 static struct passwd save;
535 struct passwd *p;
536
537 if ((p = getpwnam(name)) == NULL)
538 return (p);
539 if (save.pw_name) {
540 free((char *)save.pw_name);
541 memset(save.pw_passwd, 0, strlen(save.pw_passwd));
542 free((char *)save.pw_passwd);
543 free((char *)save.pw_gecos);
544 free((char *)save.pw_dir);
545 free((char *)save.pw_shell);
546 }
547 save = *p;
548 save.pw_name = xstrdup(p->pw_name);
549 save.pw_passwd = xstrdup(p->pw_passwd);
550 save.pw_gecos = xstrdup(p->pw_gecos);
551 save.pw_dir = xstrdup(p->pw_dir);
552 save.pw_shell = xstrdup(p->pw_shell);
553 return (&save);
554 }
555
556 static int login_attempts; /* number of failed login attempts */
557 static int askpasswd; /* had user command, ask for passwd */
558 static char curname[10]; /* current USER name */
559
560 /*
561 * USER command.
562 * Sets global passwd pointer pw if named account exists and is acceptable;
563 * sets askpasswd if a PASS command is expected. If logged in previously,
564 * need to reset state. If name is "ftp" or "anonymous", the name is not in
565 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
566 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
567 * requesting login privileges. Disallow anyone who does not have a standard
568 * shell as returned by getusershell(). Disallow anyone mentioned in the file
569 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
570 */
571 void
572 user(const char *name)
573 {
574 if (logged_in) {
575 switch (curclass.type) {
576 case CLASS_GUEST:
577 reply(530, "Can't change user from guest login.");
578 return;
579 case CLASS_CHROOT:
580 reply(530, "Can't change user from chroot user.");
581 return;
582 case CLASS_REAL:
583 if (dropprivs) {
584 reply(530, "Can't change user.");
585 return;
586 }
587 end_login();
588 break;
589 default:
590 abort();
591 }
592 }
593
594 #if defined(KERBEROS)
595 kdestroy();
596 #endif
597 #if defined(KERBEROS5)
598 k5destroy();
599 #endif
600
601 curclass.type = CLASS_REAL;
602 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
603 /* need `pw' setup for checkaccess() and checkuser () */
604 if ((pw = sgetpwnam("ftp")) == NULL)
605 reply(530, "User %s unknown.", name);
606 else if (! checkaccess("ftp") || ! checkaccess("anonymous"))
607 reply(530, "User %s access denied.", name);
608 else {
609 curclass.type = CLASS_GUEST;
610 askpasswd = 1;
611 reply(331,
612 "Guest login ok, type your name as password.");
613 }
614 if (!askpasswd && logging)
615 syslog(LOG_NOTICE,
616 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
617 return;
618 }
619
620 pw = sgetpwnam(name);
621 if (logging)
622 strlcpy(curname, name, sizeof(curname));
623
624 #ifdef SKEY
625 if (skey_haskey(name) == 0) {
626 const char *myskey;
627
628 myskey = skey_keyinfo(name);
629 reply(331, "Password [%s] required for %s.",
630 myskey ? myskey : "error getting challenge", name);
631 } else
632 #endif
633 reply(331, "Password required for %s.", name);
634
635 askpasswd = 1;
636 /*
637 * Delay before reading passwd after first failed
638 * attempt to slow down passwd-guessing programs.
639 */
640 if (login_attempts)
641 sleep((unsigned) login_attempts);
642 }
643
644 /*
645 * Determine whether something is to happen (allow access, chroot)
646 * for a user. Each line is a shell-style glob followed by
647 * `yes' or `no'.
648 *
649 * For backward compatability, `allow' and `deny' are synonymns
650 * for `yes' and `no', respectively.
651 *
652 * Each glob is matched against the username in turn, and the first
653 * match found is used. If no match is found, the result is the
654 * argument `def'. If a match is found but without and explicit
655 * `yes'/`no', the result is the opposite of def.
656 *
657 * If the file doesn't exist at all, the result is the argument
658 * `nofile'
659 *
660 * Any line starting with `#' is considered a comment and ignored.
661 *
662 * Returns 0 if the user is denied, or 1 if they are allowed.
663 *
664 * NOTE: needs struct passwd *pw setup before use.
665 */
666 int
667 checkuser(const char *fname, const char *name, int def, int nofile,
668 char **retclass)
669 {
670 FILE *fd;
671 int retval;
672 char *glob, *perm, *class, *buf, *p;
673 size_t len, line;
674
675 retval = def;
676 if (retclass != NULL)
677 *retclass = NULL;
678 if ((fd = fopen(conffilename(fname), "r")) == NULL)
679 return nofile;
680
681 line = 0;
682 for (;
683 (buf = fparseln(fd, &len, &line, NULL, FPARSELN_UNESCCOMM |
684 FPARSELN_UNESCCONT | FPARSELN_UNESCESC)) != NULL;
685 free(buf), buf = NULL) {
686 glob = perm = class = NULL;
687 p = buf;
688 if (len < 1)
689 continue;
690 if (p[len - 1] == '\n')
691 p[--len] = '\0';
692 if (EMPTYSTR(p))
693 continue;
694
695 NEXTWORD(p, glob);
696 NEXTWORD(p, perm);
697 NEXTWORD(p, class);
698 if (EMPTYSTR(glob))
699 continue;
700 if (!EMPTYSTR(class)) {
701 if (strcasecmp(class, "all") == 0 ||
702 strcasecmp(class, "none") == 0) {
703 syslog(LOG_WARNING,
704 "%s line %d: illegal user-defined class `%s' - skipping entry",
705 fname, (int)line, class);
706 continue;
707 }
708 }
709
710 /* have a host specifier */
711 if ((p = strchr(glob, '@')) != NULL) {
712 unsigned long net, mask, addr;
713 int bits;
714
715 *p++ = '\0';
716 /* check against network or CIDR */
717 if (isdigit(*p) &&
718 (bits = inet_net_pton(AF_INET, p,
719 &net, sizeof(net))) != -1) {
720 net = ntohl(net);
721 mask = 0xffffffffU << (32 - bits);
722 addr = ntohl(his_addr.su_addr.s_addr);
723 if ((addr & mask) != net)
724 continue;
725
726 /* check against hostname glob */
727 } else if (fnmatch(p, remotehost, 0) != 0)
728 continue;
729 }
730
731 /* have a group specifier */
732 if ((p = strchr(glob, ':')) != NULL) {
733 gid_t *groups, *ng;
734 int gsize, i, found;
735
736 *p++ = '\0';
737 groups = NULL;
738 gsize = 16;
739 do {
740 ng = realloc(groups, gsize * sizeof(gid_t));
741 if (ng == NULL)
742 fatal(
743 "Local resource failure: realloc");
744 groups = ng;
745 } while (getgrouplist(pw->pw_name, pw->pw_gid,
746 groups, &gsize) == -1);
747 found = 0;
748 for (i = 0; i < gsize; i++) {
749 struct group *g;
750
751 if ((g = getgrgid(groups[i])) == NULL)
752 continue;
753 if (fnmatch(p, g->gr_name, 0) == 0) {
754 found = 1;
755 break;
756 }
757 }
758 free(groups);
759 if (!found)
760 continue;
761 }
762
763 /* check against username glob */
764 if (fnmatch(glob, name, 0) != 0)
765 continue;
766
767 if (perm != NULL &&
768 ((strcasecmp(perm, "allow") == 0) ||
769 (strcasecmp(perm, "yes") == 0)))
770 retval = 1;
771 else if (perm != NULL &&
772 ((strcasecmp(perm, "deny") == 0) ||
773 (strcasecmp(perm, "no") == 0)))
774 retval = 0;
775 else
776 retval = !def;
777 if (!EMPTYSTR(class) && retclass != NULL)
778 *retclass = xstrdup(class);
779 free(buf);
780 break;
781 }
782 (void) fclose(fd);
783 return (retval);
784 }
785
786 /*
787 * Check if user is allowed by /etc/ftpusers
788 * returns 1 for yes, 0 for no
789 *
790 * NOTE: needs struct passwd *pw setup (for checkuser())
791 */
792 int
793 checkaccess(const char *name)
794 {
795
796 return (checkuser(_PATH_FTPUSERS, name, 1, 0, NULL));
797 }
798
799 /*
800 * Terminate login as previous user, if any, resetting state;
801 * used when USER command is given or login fails.
802 */
803 static void
804 end_login(void)
805 {
806
807 if (logged_in) {
808 if (dowtmp)
809 logwtmp(ttyline, "", "");
810 if (doutmp)
811 logout(utmp.ut_line);
812 }
813 /* reset login state */
814 (void) seteuid((uid_t)0);
815 pw = NULL;
816 logged_in = 0;
817 quietmessages = 0;
818 gidcount = 0;
819 curclass.type = CLASS_REAL;
820 }
821
822 void
823 pass(const char *passwd)
824 {
825 int rval;
826 const char *cp, *shell;
827 char *class, root[MAXPATHLEN];
828
829 class = NULL;
830 if (logged_in || askpasswd == 0) {
831 reply(503, "Login with USER first.");
832 return;
833 }
834 askpasswd = 0;
835 if (curclass.type != CLASS_GUEST) {
836 /* "ftp" is the only account allowed with no password */
837 if (pw == NULL) {
838 rval = 1; /* failure below */
839 goto skip;
840 }
841 #if defined(KERBEROS)
842 if (klogin(pw, "", hostname, (char *)passwd) == 0) {
843 rval = 0;
844 goto skip;
845 }
846 #endif
847 #if defined(KERBEROS5)
848 if (k5login(pw, "", hostname, (char *)passwd) == 0) {
849 rval = 0;
850 goto skip;
851 }
852 #endif
853 #ifdef SKEY
854 if (skey_haskey(pw->pw_name) == 0) {
855 char *p;
856 int r;
857
858 p = xstrdup(passwd);
859 r = skey_passcheck(pw->pw_name, p);
860 free(p);
861 if (r != -1) {
862 rval = 0;
863 goto skip;
864 }
865 }
866 #endif
867 if (!sflag && *pw->pw_passwd != '\0' &&
868 !strcmp(crypt(passwd, pw->pw_passwd), pw->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 #ifdef HASSETPROCTITLE
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 /* HASSETPROCTITLE */
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 #ifdef HASSETPROCTITLE
1122 snprintf(proctitle, sizeof(proctitle),
1123 "%s: %s", remotehost, pw->pw_name);
1124 setproctitle("%s", proctitle);
1125 #endif /* HASSETPROCTITLE */
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[10];
1484
1485 getnameinfo((struct sockaddr *)&data_source.si_su,
1486 data_source.su_len, hbuf, sizeof(hbuf), pbuf, sizeof(pbuf),
1487 NI_NUMERICHOST | NI_NUMERICSERV);
1488 reply(425, "Can't create data socket (%s,%s): %s.",
1489 hbuf, pbuf, strerror(errno));
1490 return (NULL);
1491 }
1492 data = fileno(file);
1493 while (connect(data, (struct sockaddr *)&data_dest.si_su,
1494 data_dest.su_len) < 0) {
1495 if (errno == EADDRINUSE && retry < swaitmax) {
1496 sleep((unsigned) swaitint);
1497 retry += swaitint;
1498 continue;
1499 }
1500 perror_reply(425, "Can't build data connection");
1501 (void) fclose(file);
1502 data = -1;
1503 return (NULL);
1504 }
1505 reply(150, "Opening %s mode data connection for '%s'%s.",
1506 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1507 return (file);
1508 }
1509
1510 void
1511 closedataconn(FILE *fd)
1512 {
1513
1514 if (fd != NULL)
1515 (void)fclose(fd);
1516 data = -1;
1517 if (pdata >= 0)
1518 (void)close(pdata);
1519 pdata = -1;
1520 }
1521
1522 /*
1523 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1524 * encapsulation of the data subject * to Mode, Structure, and Type.
1525 *
1526 * NB: Form isn't handled.
1527 */
1528 static int
1529 send_data(FILE *instr, FILE *outstr, off_t blksize, int isdata)
1530 {
1531 int c, filefd, netfd, rval;
1532 char *buf;
1533
1534 transflag = 1;
1535 rval = -1;
1536 buf = NULL;
1537 if (setjmp(urgcatch))
1538 goto cleanup_send_data;
1539
1540 switch (type) {
1541
1542 case TYPE_A:
1543 /* XXXLUKEM: rate limit ascii send (get) */
1544 (void) alarm(curclass.timeout);
1545 while ((c = getc(instr)) != EOF) {
1546 byte_count++;
1547 if (c == '\n') {
1548 if (ferror(outstr))
1549 goto data_err;
1550 (void) putc('\r', outstr);
1551 if (isdata) {
1552 total_data_out++;
1553 total_data++;
1554 }
1555 total_bytes_out++;
1556 total_bytes++;
1557 }
1558 (void) putc(c, outstr);
1559 if (isdata) {
1560 total_data_out++;
1561 total_data++;
1562 }
1563 total_bytes_out++;
1564 total_bytes++;
1565 if ((byte_count % 4096) == 0)
1566 (void) alarm(curclass.timeout);
1567 }
1568 (void) alarm(0);
1569 fflush(outstr);
1570 if (ferror(instr))
1571 goto file_err;
1572 if (ferror(outstr))
1573 goto data_err;
1574 rval = 0;
1575 goto cleanup_send_data;
1576
1577 case TYPE_I:
1578 case TYPE_L:
1579 if ((buf = malloc((size_t)blksize)) == NULL) {
1580 perror_reply(451, "Local resource failure: malloc");
1581 goto cleanup_send_data;
1582 }
1583 filefd = fileno(instr);
1584 netfd = fileno(outstr);
1585 (void) alarm(curclass.timeout);
1586 if (curclass.rateget) {
1587 while (1) {
1588 int d;
1589 struct timeval then, now, td;
1590 off_t bufrem;
1591 char *bufp;
1592
1593 (void)gettimeofday(&then, NULL);
1594 errno = c = d = 0;
1595 bufrem = curclass.rateget;
1596 while (bufrem > 0) {
1597 if ((c = read(filefd, buf,
1598 MIN(blksize, bufrem))) <= 0)
1599 goto senddone;
1600 (void) alarm(curclass.timeout);
1601 bufrem -= c;
1602 byte_count += c;
1603 if (isdata) {
1604 total_data_out += c;
1605 total_data += c;
1606 }
1607 total_bytes_out += c;
1608 total_bytes += c;
1609 for (bufp = buf; c > 0;
1610 c -= d, bufp += d)
1611 if ((d =
1612 write(netfd, bufp, c)) <= 0)
1613 break;
1614 if (d < 0)
1615 goto data_err;
1616 }
1617 (void)gettimeofday(&now, NULL);
1618 timersub(&now, &then, &td);
1619 if (td.tv_sec == 0)
1620 usleep(1000000 - td.tv_usec);
1621 }
1622 } else {
1623 while ((c = read(filefd, buf, (size_t)blksize)) > 0) {
1624 if (write(netfd, buf, c) != c)
1625 goto data_err;
1626 (void) alarm(curclass.timeout);
1627 byte_count += c;
1628 if (isdata) {
1629 total_data_out += c;
1630 total_data += c;
1631 }
1632 total_bytes_out += c;
1633 total_bytes += c;
1634 }
1635 }
1636 senddone:
1637 if (c < 0)
1638 goto file_err;
1639 rval = 0;
1640 goto cleanup_send_data;
1641
1642 default:
1643 reply(550, "Unimplemented TYPE %d in send_data", type);
1644 goto cleanup_send_data;
1645 }
1646
1647 data_err:
1648 (void) alarm(0);
1649 perror_reply(426, "Data connection");
1650 goto cleanup_send_data;
1651
1652 file_err:
1653 (void) alarm(0);
1654 perror_reply(551, "Error on input file");
1655 /* FALLTHROUGH */
1656
1657 cleanup_send_data:
1658 (void) alarm(0);
1659 transflag = 0;
1660 if (buf)
1661 free(buf);
1662 if (isdata) {
1663 total_files_out++;
1664 total_files++;
1665 }
1666 total_xfers_out++;
1667 total_xfers++;
1668 return (rval);
1669 }
1670
1671 /*
1672 * Transfer data from peer to "outstr" using the appropriate encapulation of
1673 * the data subject to Mode, Structure, and Type.
1674 *
1675 * N.B.: Form isn't handled.
1676 */
1677 static int
1678 receive_data(FILE *instr, FILE *outstr)
1679 {
1680 int c, bare_lfs, netfd, filefd, rval;
1681 off_t byteswritten;
1682 char buf[BUFSIZ];
1683 #ifdef __GNUC__
1684 (void) &bare_lfs;
1685 #endif
1686
1687 bare_lfs = 0;
1688 transflag = 1;
1689 rval = -1;
1690 byteswritten = 0;
1691 if (setjmp(urgcatch))
1692 goto cleanup_recv_data;
1693
1694 #define FILESIZECHECK(x) \
1695 do { \
1696 if (curclass.maxfilesize != -1 && \
1697 (x) > curclass.maxfilesize) { \
1698 errno = EFBIG; \
1699 goto file_err; \
1700 } \
1701 } while (0)
1702
1703 switch (type) {
1704
1705 case TYPE_I:
1706 case TYPE_L:
1707 netfd = fileno(instr);
1708 filefd = fileno(outstr);
1709 (void) alarm(curclass.timeout);
1710 if (curclass.rateput) {
1711 while (1) {
1712 int d;
1713 struct timeval then, now, td;
1714 off_t bufrem;
1715
1716 (void)gettimeofday(&then, NULL);
1717 errno = c = d = 0;
1718 for (bufrem = curclass.rateput; bufrem > 0; ) {
1719 if ((c = read(netfd, buf,
1720 MIN(sizeof(buf), bufrem))) <= 0)
1721 goto recvdone;
1722 FILESIZECHECK(byte_count + c);
1723 if ((d = write(filefd, buf, c)) != c)
1724 goto file_err;
1725 (void) alarm(curclass.timeout);
1726 bufrem -= c;
1727 byte_count += c;
1728 total_data_in += c;
1729 total_data += c;
1730 total_bytes_in += c;
1731 total_bytes += c;
1732 }
1733 (void)gettimeofday(&now, NULL);
1734 timersub(&now, &then, &td);
1735 if (td.tv_sec == 0)
1736 usleep(1000000 - td.tv_usec);
1737 }
1738 } else {
1739 while ((c = read(netfd, buf, sizeof(buf))) > 0) {
1740 FILESIZECHECK(byte_count + c);
1741 if (write(filefd, buf, c) != c)
1742 goto file_err;
1743 (void) alarm(curclass.timeout);
1744 byte_count += c;
1745 total_data_in += c;
1746 total_data += c;
1747 total_bytes_in += c;
1748 total_bytes += c;
1749 }
1750 }
1751 recvdone:
1752 if (c < 0)
1753 goto data_err;
1754 rval = 0;
1755 goto cleanup_recv_data;
1756
1757 case TYPE_E:
1758 reply(553, "TYPE E not implemented.");
1759 goto cleanup_recv_data;
1760
1761 case TYPE_A:
1762 (void) alarm(curclass.timeout);
1763 /* XXXLUKEM: rate limit ascii receive (put) */
1764 while ((c = getc(instr)) != EOF) {
1765 byte_count++;
1766 total_data_in++;
1767 total_data++;
1768 total_bytes_in++;
1769 total_bytes++;
1770 if ((byte_count % 4096) == 0)
1771 (void) alarm(curclass.timeout);
1772 if (c == '\n')
1773 bare_lfs++;
1774 while (c == '\r') {
1775 if (ferror(outstr))
1776 goto data_err;
1777 if ((c = getc(instr)) != '\n') {
1778 byte_count++;
1779 total_data_in++;
1780 total_data++;
1781 total_bytes_in++;
1782 total_bytes++;
1783 if ((byte_count % 4096) == 0)
1784 (void) alarm(curclass.timeout);
1785 byteswritten++;
1786 FILESIZECHECK(byteswritten);
1787 (void) putc ('\r', outstr);
1788 if (c == '\0' || c == EOF)
1789 goto contin2;
1790 }
1791 }
1792 byteswritten++;
1793 FILESIZECHECK(byteswritten);
1794 (void) putc(c, outstr);
1795 contin2: ;
1796 }
1797 (void) alarm(0);
1798 fflush(outstr);
1799 if (ferror(instr))
1800 goto data_err;
1801 if (ferror(outstr))
1802 goto file_err;
1803 if (bare_lfs) {
1804 reply(-226,
1805 "WARNING! %d bare linefeeds received in ASCII mode",
1806 bare_lfs);
1807 reply(0, "File may not have transferred correctly.");
1808 }
1809 rval = 0;
1810 goto cleanup_recv_data;
1811
1812 default:
1813 reply(550, "Unimplemented TYPE %d in receive_data", type);
1814 goto cleanup_recv_data;
1815 }
1816 #undef FILESIZECHECK(x)
1817
1818 data_err:
1819 (void) alarm(0);
1820 perror_reply(426, "Data Connection");
1821 goto cleanup_recv_data;
1822
1823 file_err:
1824 (void) alarm(0);
1825 perror_reply(452, "Error writing file");
1826 goto cleanup_recv_data;
1827
1828 cleanup_recv_data:
1829 (void) alarm(0);
1830 transflag = 0;
1831 total_files_in++;
1832 total_files++;
1833 total_xfers_in++;
1834 total_xfers++;
1835 return (rval);
1836 }
1837
1838 void
1839 statcmd(void)
1840 {
1841 struct sockinet *su = NULL;
1842 static char ntop_buf[NI_MAXHOST];
1843 u_char *a, *p;
1844 int ispassive, af;
1845 off_t otbi, otbo, otb;
1846
1847 a = p = (u_char *)NULL;
1848
1849 reply(-211, "%s FTP server status:", hostname);
1850 reply(0, "Version: %s", EMPTYSTR(version) ? "<suppressed>" : version);
1851 ntop_buf[0] = '\0';
1852 if (!getnameinfo((struct sockaddr *)&his_addr.si_su, his_addr.su_len,
1853 ntop_buf, sizeof(ntop_buf), NULL, 0, NI_NUMERICHOST)
1854 && strcmp(remotehost, ntop_buf) != 0)
1855 reply(0, "Connected to %s (%s)", remotehost, ntop_buf);
1856 else
1857 reply(0, "Connected to %s", remotehost);
1858
1859 if (logged_in) {
1860 if (curclass.type == CLASS_GUEST)
1861 reply(0, "Logged in anonymously");
1862 else
1863 reply(0, "Logged in as %s%s", pw->pw_name,
1864 curclass.type == CLASS_CHROOT ? " (chroot)" : "");
1865 } else if (askpasswd)
1866 reply(0, "Waiting for password");
1867 else
1868 reply(0, "Waiting for user name");
1869 cprintf(stdout, " TYPE: %s", typenames[type]);
1870 if (type == TYPE_A || type == TYPE_E)
1871 cprintf(stdout, ", FORM: %s", formnames[form]);
1872 if (type == TYPE_L) {
1873 #if NBBY == 8
1874 cprintf(stdout, " %d", NBBY);
1875 #else
1876 /* XXX: `bytesize' needs to be defined in this case */
1877 cprintf(stdout, " %d", bytesize);
1878 #endif
1879 }
1880 cprintf(stdout, "; STRUcture: %s; transfer MODE: %s\r\n",
1881 strunames[stru], modenames[mode]);
1882 ispassive = 0;
1883 if (data != -1) {
1884 reply(0, "Data connection open");
1885 su = NULL;
1886 } else if (pdata != -1) {
1887 reply(0, "in Passive mode");
1888 su = (struct sockinet *)&pasv_addr;
1889 ispassive = 1;
1890 goto printaddr;
1891 } else if (usedefault == 0) {
1892 if (epsvall) {
1893 reply(0, "EPSV only mode (EPSV ALL)");
1894 goto epsvonly;
1895 }
1896 su = (struct sockinet *)&data_dest;
1897 printaddr:
1898 /* PASV/PORT */
1899 if (su->su_family == AF_INET) {
1900 a = (u_char *) &su->su_addr;
1901 p = (u_char *) &su->su_port;
1902 #define UC(b) (((int) b) & 0xff)
1903 reply(0, "%s (%d,%d,%d,%d,%d,%d)",
1904 ispassive ? "PASV" : "PORT" ,
1905 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
1906 UC(p[0]), UC(p[1]));
1907 }
1908
1909 /* LPSV/LPRT */
1910 {
1911 int alen, af, i;
1912
1913 alen = 0;
1914 switch (su->su_family) {
1915 case AF_INET:
1916 a = (u_char *) &su->su_addr;
1917 p = (u_char *) &su->su_port;
1918 alen = sizeof(su->su_addr);
1919 af = 4;
1920 break;
1921 #ifdef INET6
1922 case AF_INET6:
1923 a = (u_char *) &su->su_6addr;
1924 p = (u_char *) &su->su_port;
1925 alen = sizeof(su->su_6addr);
1926 af = 6;
1927 break;
1928 #endif
1929 default:
1930 af = 0;
1931 break;
1932 }
1933 if (af) {
1934 cprintf(stdout, " %s (%d,%d",
1935 ispassive ? "LPSV" : "LPRT", af, alen);
1936 for (i = 0; i < alen; i++)
1937 cprintf(stdout, ",%d", UC(a[i]));
1938 cprintf(stdout, ",%d,%d,%d)", 2, UC(p[0]), UC(p[1]));
1939 #undef UC
1940 }
1941 }
1942
1943 /* EPRT/EPSV */
1944 epsvonly:
1945 af = af2epsvproto(su->su_family);
1946 ntop_buf[0] = '\0';
1947 if (af > 0) {
1948 if (getnameinfo((struct sockaddr *)&su->si_su,
1949 su->su_len, ntop_buf, sizeof(ntop_buf), NULL, 0,
1950 NI_NUMERICHOST) == 0)
1951 reply(0, "%s (|%d|%s|%d|)",
1952 ispassive ? "EPSV" : "EPRT",
1953 af, ntop_buf, ntohs(su->su_port));
1954 }
1955 } else
1956 reply(0, "No data connection");
1957
1958 if (logged_in) {
1959 reply(0,
1960 "Data sent: " LLF " byte%s in " LLF " file%s",
1961 (LLT)total_data_out, PLURAL(total_data_out),
1962 (LLT)total_files_out, PLURAL(total_files_out));
1963 reply(0,
1964 "Data received: " LLF " byte%s in " LLF " file%s",
1965 (LLT)total_data_in, PLURAL(total_data_in),
1966 (LLT)total_files_in, PLURAL(total_files_in));
1967 reply(0,
1968 "Total data: " LLF " byte%s in " LLF " file%s",
1969 (LLT)total_data, PLURAL(total_data),
1970 (LLT)total_files, PLURAL(total_files));
1971 }
1972 otbi = total_bytes_in;
1973 otbo = total_bytes_out;
1974 otb = total_bytes;
1975 reply(0, "Traffic sent: " LLF " byte%s in " LLF " transfer%s",
1976 (LLT)otbo, PLURAL(otbo),
1977 (LLT)total_xfers_out, PLURAL(total_xfers_out));
1978 reply(0, "Traffic received: " LLF " byte%s in " LLF " transfer%s",
1979 (LLT)otbi, PLURAL(otbi),
1980 (LLT)total_xfers_in, PLURAL(total_xfers_in));
1981 reply(0, "Total traffic: " LLF " byte%s in " LLF " transfer%s",
1982 (LLT)otb, PLURAL(otb),
1983 (LLT)total_xfers, PLURAL(total_xfers));
1984
1985 if (logged_in) {
1986 struct ftpconv *cp;
1987
1988 reply(0, "%s", "");
1989 reply(0, "Class: %s, type: %s",
1990 curclass.classname, CURCLASSTYPE);
1991 reply(0, "Check PORT/LPRT commands: %sabled",
1992 CURCLASS_FLAGS_ISSET(checkportcmd) ? "en" : "dis");
1993 if (! EMPTYSTR(curclass.display))
1994 reply(0, "Display file: %s", curclass.display);
1995 if (! EMPTYSTR(curclass.notify))
1996 reply(0, "Notify fileglob: %s", curclass.notify);
1997 reply(0, "Idle timeout: %d, maximum timeout: %d",
1998 curclass.timeout, curclass.maxtimeout);
1999 reply(0, "Current connections: %d", connections);
2000 if (curclass.limit == -1)
2001 reply(0, "Maximum connections: unlimited");
2002 else
2003 reply(0, "Maximum connections: %d", curclass.limit);
2004 if (curclass.limitfile)
2005 reply(0, "Connection limit exceeded message file: %s",
2006 curclass.limitfile);
2007 if (! EMPTYSTR(curclass.chroot))
2008 reply(0, "Chroot format: %s", curclass.chroot);
2009 if (! EMPTYSTR(curclass.homedir))
2010 reply(0, "Homedir format: %s", curclass.homedir);
2011 if (curclass.maxfilesize == -1)
2012 reply(0, "Maximum file size: unlimited");
2013 else
2014 reply(0, "Maximum file size: " LLF,
2015 (LLT)curclass.maxfilesize);
2016 if (! EMPTYSTR(curclass.motd))
2017 reply(0, "MotD file: %s", curclass.motd);
2018 reply(0,
2019 "Modify commands (CHMOD, DELE, MKD, RMD, RNFR, UMASK): %sabled",
2020 CURCLASS_FLAGS_ISSET(modify) ? "en" : "dis");
2021 reply(0, "Upload commands (APPE, STOR, STOU): %sabled",
2022 CURCLASS_FLAGS_ISSET(upload) ? "en" : "dis");
2023 reply(0, "Sanitize file names: %sabled",
2024 CURCLASS_FLAGS_ISSET(sanenames) ? "en" : "dis");
2025 reply(0, "PASV/LPSV/EPSV connections: %sabled",
2026 CURCLASS_FLAGS_ISSET(passive) ? "en" : "dis");
2027 if (curclass.portmin && curclass.portmax)
2028 reply(0, "PASV port range: %d - %d",
2029 curclass.portmin, curclass.portmax);
2030 if (curclass.rateget)
2031 reply(0, "Rate get limit: " LLF " bytes/sec",
2032 (LLT)curclass.rateget);
2033 else
2034 reply(0, "Rate get limit: disabled");
2035 if (curclass.rateput)
2036 reply(0, "Rate put limit: " LLF " bytes/sec",
2037 (LLT)curclass.rateput);
2038 else
2039 reply(0, "Rate put limit: disabled");
2040 reply(0, "Umask: %.04o", curclass.umask);
2041 for (cp = curclass.conversions; cp != NULL; cp=cp->next) {
2042 if (cp->suffix == NULL || cp->types == NULL ||
2043 cp->command == NULL)
2044 continue;
2045 reply(0, "Conversion: %s [%s] disable: %s, command: %s",
2046 cp->suffix, cp->types, cp->disable, cp->command);
2047 }
2048 }
2049
2050 reply(211, "End of status");
2051 }
2052
2053 void
2054 fatal(const char *s)
2055 {
2056
2057 reply(451, "Error in server: %s\n", s);
2058 reply(221, "Closing connection due to server error.");
2059 dologout(0);
2060 /* NOTREACHED */
2061 }
2062
2063 /*
2064 * reply() --
2065 * depending on the value of n, display fmt with a trailing CRLF and
2066 * prefix of:
2067 * n < -1 prefix the message with abs(n) + "-" (initial line)
2068 * n == 0 prefix the message with 4 spaces (middle lines)
2069 * n > 0 prefix the message with n + " " (final line)
2070 */
2071 void
2072 reply(int n, const char *fmt, ...)
2073 {
2074 off_t b;
2075 va_list ap;
2076
2077 va_start(ap, fmt);
2078 b = 0;
2079 if (n == 0)
2080 cprintf(stdout, " ");
2081 else if (n < 0)
2082 cprintf(stdout, "%d-", -n);
2083 else
2084 cprintf(stdout, "%d ", n);
2085 b = vprintf(fmt, ap);
2086 total_bytes += b;
2087 total_bytes_out += b;
2088 cprintf(stdout, "\r\n");
2089 (void)fflush(stdout);
2090 if (debug) {
2091 syslog(LOG_DEBUG, "<--- %d%c", abs(n), (n < 0) ? '-' : ' ');
2092 vsyslog(LOG_DEBUG, fmt, ap);
2093 }
2094 }
2095
2096 static void
2097 dolog(struct sockaddr *who)
2098 {
2099
2100 (void)getnameinfo(who, who->sa_len, remotehost, sizeof(remotehost),
2101 NULL, 0, 0);
2102
2103 #ifdef HASSETPROCTITLE
2104 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
2105 setproctitle("%s", proctitle);
2106 #endif /* HASSETPROCTITLE */
2107 if (logging)
2108 syslog(LOG_INFO, "connection from %s to %s",
2109 remotehost, hostname);
2110 }
2111
2112 /*
2113 * Record logout in wtmp file
2114 * and exit with supplied status.
2115 */
2116 void
2117 dologout(int status)
2118 {
2119 /*
2120 * Prevent reception of SIGURG from resulting in a resumption
2121 * back to the main program loop.
2122 */
2123 transflag = 0;
2124
2125 if (logged_in) {
2126 if (dowtmp)
2127 logwtmp(ttyline, "", "");
2128 if (doutmp)
2129 logout(utmp.ut_line);
2130 #ifdef KERBEROS
2131 if (!notickets && krbtkfile_env)
2132 unlink(krbtkfile_env);
2133 #endif
2134 }
2135 /* beware of flushing buffers after a SIGPIPE */
2136 _exit(status);
2137 }
2138
2139 static void
2140 myoob(int signo)
2141 {
2142 char *cp;
2143
2144 /* only process if transfer occurring */
2145 if (!transflag)
2146 return;
2147 cp = tmpline;
2148 if (getline(cp, 7, stdin) == NULL) {
2149 reply(221, "You could at least say goodbye.");
2150 dologout(0);
2151 }
2152 if (strcasecmp(cp, "ABOR\r\n") == 0) {
2153 tmpline[0] = '\0';
2154 reply(426, "Transfer aborted. Data connection closed.");
2155 reply(226, "Abort successful");
2156 longjmp(urgcatch, 1);
2157 }
2158 if (strcasecmp(cp, "STAT\r\n") == 0) {
2159 tmpline[0] = '\0';
2160 if (file_size != (off_t) -1)
2161 reply(213,
2162 "Status: " LLF " of " LLF " byte%s transferred",
2163 (LLT)byte_count, (LLT)file_size,
2164 PLURAL(byte_count));
2165 else
2166 reply(213, "Status: " LLF " byte%s transferred",
2167 (LLT)byte_count, PLURAL(byte_count));
2168 }
2169 }
2170
2171 static int
2172 bind_pasv_addr(void)
2173 {
2174 static int passiveport;
2175 int port, len;
2176
2177 len = pasv_addr.su_len;
2178 if (curclass.portmin == 0 && curclass.portmax == 0) {
2179 pasv_addr.su_port = 0;
2180 return (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len));
2181 }
2182
2183 if (passiveport == 0) {
2184 srand(getpid());
2185 passiveport = rand() % (curclass.portmax - curclass.portmin)
2186 + curclass.portmin;
2187 }
2188
2189 port = passiveport;
2190 while (1) {
2191 port++;
2192 if (port > curclass.portmax)
2193 port = curclass.portmin;
2194 else if (port == passiveport) {
2195 errno = EAGAIN;
2196 return (-1);
2197 }
2198 pasv_addr.su_port = htons(port);
2199 if (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len) == 0)
2200 break;
2201 if (errno != EADDRINUSE)
2202 return (-1);
2203 }
2204 passiveport = port;
2205 return (0);
2206 }
2207
2208 /*
2209 * Note: a response of 425 is not mentioned as a possible response to
2210 * the PASV command in RFC959. However, it has been blessed as
2211 * a legitimate response by Jon Postel in a telephone conversation
2212 * with Rick Adams on 25 Jan 89.
2213 */
2214 void
2215 passive(void)
2216 {
2217 int len;
2218 char *p, *a;
2219
2220 if (pdata >= 0)
2221 close(pdata);
2222 pdata = socket(AF_INET, SOCK_STREAM, 0);
2223 if (pdata < 0 || !logged_in) {
2224 perror_reply(425, "Can't open passive connection");
2225 return;
2226 }
2227 pasv_addr = ctrl_addr;
2228
2229 if (bind_pasv_addr() < 0)
2230 goto pasv_error;
2231 len = pasv_addr.su_len;
2232 if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
2233 goto pasv_error;
2234 pasv_addr.su_len = len;
2235 if (listen(pdata, 1) < 0)
2236 goto pasv_error;
2237 a = (char *) &pasv_addr.su_addr;
2238 p = (char *) &pasv_addr.su_port;
2239
2240 #define UC(b) (((int) b) & 0xff)
2241
2242 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2243 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2244 return;
2245
2246 pasv_error:
2247 (void) close(pdata);
2248 pdata = -1;
2249 perror_reply(425, "Can't open passive connection");
2250 return;
2251 }
2252
2253 /*
2254 * convert protocol identifier to/from AF
2255 */
2256 int
2257 lpsvproto2af(int proto)
2258 {
2259
2260 switch (proto) {
2261 case 4:
2262 return AF_INET;
2263 #ifdef INET6
2264 case 6:
2265 return AF_INET6;
2266 #endif
2267 default:
2268 return -1;
2269 }
2270 }
2271
2272 int
2273 af2lpsvproto(int af)
2274 {
2275
2276 switch (af) {
2277 case AF_INET:
2278 return 4;
2279 #ifdef INET6
2280 case AF_INET6:
2281 return 6;
2282 #endif
2283 default:
2284 return -1;
2285 }
2286 }
2287
2288 int
2289 epsvproto2af(int proto)
2290 {
2291
2292 switch (proto) {
2293 case 1:
2294 return AF_INET;
2295 #ifdef INET6
2296 case 2:
2297 return AF_INET6;
2298 #endif
2299 default:
2300 return -1;
2301 }
2302 }
2303
2304 int
2305 af2epsvproto(int af)
2306 {
2307
2308 switch (af) {
2309 case AF_INET:
2310 return 1;
2311 #ifdef INET6
2312 case AF_INET6:
2313 return 2;
2314 #endif
2315 default:
2316 return -1;
2317 }
2318 }
2319
2320 /*
2321 * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)
2322 * 229 Entering Extended Passive Mode (|||port|)
2323 */
2324 void
2325 long_passive(char *cmd, int pf)
2326 {
2327 int len;
2328 char *p, *a;
2329
2330 if (!logged_in) {
2331 syslog(LOG_NOTICE, "long passive but not logged in");
2332 reply(503, "Login with USER first.");
2333 return;
2334 }
2335
2336 if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) {
2337 /*
2338 * XXX: only EPRT/EPSV ready clients will understand this
2339 */
2340 if (strcmp(cmd, "EPSV") != 0)
2341 reply(501, "Network protocol mismatch"); /*XXX*/
2342 else
2343 epsv_protounsupp("Network protocol mismatch");
2344
2345 return;
2346 }
2347
2348 if (pdata >= 0)
2349 close(pdata);
2350 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2351 if (pdata < 0) {
2352 perror_reply(425, "Can't open passive connection");
2353 return;
2354 }
2355 pasv_addr = ctrl_addr;
2356 if (bind_pasv_addr() < 0)
2357 goto pasv_error;
2358 len = pasv_addr.su_len;
2359 if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
2360 goto pasv_error;
2361 pasv_addr.su_len = len;
2362 if (listen(pdata, 1) < 0)
2363 goto pasv_error;
2364 p = (char *) &pasv_addr.su_port;
2365
2366 #define UC(b) (((int) b) & 0xff)
2367
2368 if (strcmp(cmd, "LPSV") == 0) {
2369 switch (pasv_addr.su_family) {
2370 case AF_INET:
2371 a = (char *) &pasv_addr.su_addr;
2372 reply(228,
2373 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2374 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2375 2, UC(p[0]), UC(p[1]));
2376 return;
2377 #ifdef INET6
2378 case AF_INET6:
2379 a = (char *) &pasv_addr.su_6addr;
2380 reply(228,
2381 "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)",
2382 6, 16,
2383 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2384 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2385 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2386 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2387 2, UC(p[0]), UC(p[1]));
2388 return;
2389 #endif
2390 }
2391 #undef UC
2392 } else if (strcmp(cmd, "EPSV") == 0) {
2393 switch (pasv_addr.su_family) {
2394 case AF_INET:
2395 #ifdef INET6
2396 case AF_INET6:
2397 #endif
2398 reply(229, "Entering Extended Passive Mode (|||%d|)",
2399 ntohs(pasv_addr.su_port));
2400 return;
2401 }
2402 } else {
2403 /* more proper error code? */
2404 }
2405
2406 pasv_error:
2407 (void) close(pdata);
2408 pdata = -1;
2409 perror_reply(425, "Can't open passive connection");
2410 return;
2411 }
2412
2413 int
2414 extended_port(const char *arg)
2415 {
2416 char *tmp = NULL;
2417 char *result[3];
2418 char *p, *q;
2419 char delim;
2420 struct addrinfo hints;
2421 struct addrinfo *res = NULL;
2422 int i;
2423 unsigned long proto;
2424
2425 tmp = xstrdup(arg);
2426 p = tmp;
2427 delim = p[0];
2428 p++;
2429 memset(result, 0, sizeof(result));
2430 for (i = 0; i < 3; i++) {
2431 q = strchr(p, delim);
2432 if (!q || *q != delim)
2433 goto parsefail;
2434 *q++ = '\0';
2435 result[i] = p;
2436 p = q;
2437 }
2438
2439 /* some more sanity checks */
2440 p = NULL;
2441 (void)strtoul(result[2], &p, 10);
2442 if (!*result[2] || *p)
2443 goto parsefail;
2444 p = NULL;
2445 proto = strtoul(result[0], &p, 10);
2446 if (!*result[0] || *p)
2447 goto protounsupp;
2448
2449 memset(&hints, 0, sizeof(hints));
2450 hints.ai_family = epsvproto2af((int)proto);
2451 if (hints.ai_family < 0)
2452 goto protounsupp;
2453 hints.ai_socktype = SOCK_STREAM;
2454 hints.ai_flags = AI_NUMERICHOST;
2455 if (getaddrinfo(result[1], result[2], &hints, &res))
2456 goto parsefail;
2457 if (res->ai_next)
2458 goto parsefail;
2459 if (sizeof(data_dest) < res->ai_addrlen)
2460 goto parsefail;
2461 memcpy(&data_dest, res->ai_addr, res->ai_addrlen);
2462 if (his_addr.su_family == AF_INET6 &&
2463 data_dest.su_family == AF_INET6) {
2464 /* XXX: more sanity checks! */
2465 data_dest.su_scope_id = his_addr.su_scope_id;
2466 }
2467
2468 if (tmp != NULL)
2469 free(tmp);
2470 if (res)
2471 freeaddrinfo(res);
2472 return 0;
2473
2474 parsefail:
2475 reply(500, "Invalid argument, rejected.");
2476 usedefault = 1;
2477 if (tmp != NULL)
2478 free(tmp);
2479 if (res)
2480 freeaddrinfo(res);
2481 return -1;
2482
2483 protounsupp:
2484 epsv_protounsupp("Protocol not supported");
2485 usedefault = 1;
2486 if (tmp != NULL)
2487 free(tmp);
2488 if (res)
2489 freeaddrinfo(res);
2490 return -1;
2491 }
2492
2493 /*
2494 * 522 Protocol not supported (proto,...)
2495 * as we assume address family for control and data connections are the same,
2496 * we do not return the list of address families we support - instead, we
2497 * return the address family of the control connection.
2498 */
2499 void
2500 epsv_protounsupp(const char *message)
2501 {
2502 int proto;
2503
2504 proto = af2epsvproto(ctrl_addr.su_family);
2505 if (proto < 0)
2506 reply(501, "%s", message); /* XXX */
2507 else
2508 reply(522, "%s, use (%d)", message, proto);
2509 }
2510
2511 /*
2512 * Generate unique name for file with basename "local".
2513 * The file named "local" is already known to exist.
2514 * Generates failure reply on error.
2515 *
2516 * XXX: this function should under go changes similar to
2517 * the mktemp(3)/mkstemp(3) changes.
2518 */
2519 static char *
2520 gunique(const char *local)
2521 {
2522 static char new[MAXPATHLEN];
2523 struct stat st;
2524 char *cp;
2525 int count;
2526
2527 cp = strrchr(local, '/');
2528 if (cp)
2529 *cp = '\0';
2530 if (stat(cp ? local : ".", &st) < 0) {
2531 perror_reply(553, cp ? local : ".");
2532 return (NULL);
2533 }
2534 if (cp)
2535 *cp = '/';
2536 for (count = 1; count < 100; count++) {
2537 (void)snprintf(new, sizeof(new) - 1, "%s.%d", local, count);
2538 if (stat(new, &st) < 0)
2539 return (new);
2540 }
2541 reply(452, "Unique file name cannot be created.");
2542 return (NULL);
2543 }
2544
2545 /*
2546 * Format and send reply containing system error number.
2547 */
2548 void
2549 perror_reply(int code, const char *string)
2550 {
2551 int save_errno;
2552
2553 save_errno = errno;
2554 reply(code, "%s: %s.", string, strerror(errno));
2555 errno = save_errno;
2556 }
2557
2558 static char *onefile[] = {
2559 "",
2560 0
2561 };
2562
2563 void
2564 send_file_list(const char *whichf)
2565 {
2566 struct stat st;
2567 DIR *dirp = NULL;
2568 struct dirent *dir;
2569 FILE *dout = NULL;
2570 char **dirlist, *dirname, *p;
2571 int simple = 0;
2572 int freeglob = 0;
2573 glob_t gl;
2574 off_t b;
2575
2576 #ifdef __GNUC__
2577 (void) &dout;
2578 (void) &dirlist;
2579 (void) &simple;
2580 (void) &freeglob;
2581 #endif
2582
2583 p = NULL;
2584 if (strpbrk(whichf, "~{[*?") != NULL) {
2585 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
2586
2587 memset(&gl, 0, sizeof(gl));
2588 freeglob = 1;
2589 if (glob(whichf, flags, 0, &gl)) {
2590 reply(550, "not found");
2591 goto out;
2592 } else if (gl.gl_pathc == 0) {
2593 errno = ENOENT;
2594 perror_reply(550, whichf);
2595 goto out;
2596 }
2597 dirlist = gl.gl_pathv;
2598 } else {
2599 p = xstrdup(whichf);
2600 onefile[0] = p;
2601 dirlist = onefile;
2602 simple = 1;
2603 }
2604 /* XXX: } for vi sm */
2605
2606 if (setjmp(urgcatch)) {
2607 transflag = 0;
2608 goto out;
2609 }
2610 while ((dirname = *dirlist++) != NULL) {
2611 int trailingslash = 0;
2612
2613 if (stat(dirname, &st) < 0) {
2614 /*
2615 * If user typed "ls -l", etc, and the client
2616 * used NLST, do what the user meant.
2617 */
2618 /* XXX: nuke this support? */
2619 if (dirname[0] == '-' && *dirlist == NULL &&
2620 transflag == 0) {
2621 char *argv[] = { INTERNAL_LS, "", NULL };
2622
2623 argv[1] = dirname;
2624 retrieve(argv, dirname);
2625 goto out;
2626 }
2627 perror_reply(550, whichf);
2628 goto cleanup_send_file_list;
2629 }
2630
2631 if (S_ISREG(st.st_mode)) {
2632 if (dout == NULL) {
2633 dout = dataconn("file list", (off_t)-1, "w");
2634 if (dout == NULL)
2635 goto out;
2636 transflag++;
2637 }
2638 b = fprintf(dout, "%s%s\n", dirname,
2639 type == TYPE_A ? "\r" : "");
2640 total_bytes += b;
2641 total_bytes_out += b;
2642 byte_count += strlen(dirname) + 1;
2643 continue;
2644 } else if (!S_ISDIR(st.st_mode))
2645 continue;
2646
2647 if (dirname[strlen(dirname) - 1] == '/')
2648 trailingslash++;
2649
2650 if ((dirp = opendir(dirname)) == NULL)
2651 continue;
2652
2653 while ((dir = readdir(dirp)) != NULL) {
2654 char nbuf[MAXPATHLEN];
2655
2656 if (ISDOTDIR(dir->d_name) || ISDOTDOTDIR(dir->d_name))
2657 continue;
2658
2659 (void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
2660 trailingslash ? "" : "/", dir->d_name);
2661
2662 /*
2663 * We have to do a stat to ensure it's
2664 * not a directory or special file.
2665 */
2666 /* XXX: follow RFC959 and filter out non files ? */
2667 if (simple || (stat(nbuf, &st) == 0 &&
2668 S_ISREG(st.st_mode))) {
2669 char *p;
2670
2671 if (dout == NULL) {
2672 dout = dataconn("file list", (off_t)-1,
2673 "w");
2674 if (dout == NULL)
2675 goto out;
2676 transflag++;
2677 }
2678 p = nbuf;
2679 if (nbuf[0] == '.' && nbuf[1] == '/')
2680 p = &nbuf[2];
2681 b = fprintf(dout, "%s%s\n", p,
2682 type == TYPE_A ? "\r" : "");
2683 total_bytes += b;
2684 total_bytes_out += b;
2685 byte_count += strlen(nbuf) + 1;
2686 }
2687 }
2688 (void) closedir(dirp);
2689 }
2690
2691 if (dout == NULL)
2692 reply(550, "No files found.");
2693 else if (ferror(dout) != 0)
2694 perror_reply(550, "Data connection");
2695 else
2696 reply(226, "Transfer complete.");
2697
2698 cleanup_send_file_list:
2699 transflag = 0;
2700 closedataconn(dout);
2701 out:
2702 total_xfers++;
2703 total_xfers_out++;
2704 if (p)
2705 free(p);
2706 if (freeglob)
2707 globfree(&gl);
2708 }
2709
2710 char *
2711 conffilename(const char *s)
2712 {
2713 static char filename[MAXPATHLEN];
2714
2715 if (*s == '/')
2716 strlcpy(filename, s, sizeof(filename));
2717 else
2718 (void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
2719 return (filename);
2720 }
2721
2722 /*
2723 * logcmd --
2724 * based on the arguments, syslog a message:
2725 * if bytes != -1 "<command> <file1> = <bytes> bytes"
2726 * else if file2 != NULL "<command> <file1> <file2>"
2727 * else "<command> <file1>"
2728 * if elapsed != NULL, append "in xxx.yyy seconds"
2729 * if error != NULL, append ": " + error
2730 */
2731 void
2732 logcmd(const char *command, off_t bytes, const char *file1, const char *file2,
2733 const struct timeval *elapsed, const char *error)
2734 {
2735 char buf[MAXPATHLEN * 2 + 100], realfile[MAXPATHLEN];
2736 const char *p;
2737 size_t len;
2738
2739 if (logging <=1)
2740 return;
2741
2742 if ((p = realpath(file1, realfile)) == NULL)
2743 p = file1;
2744 len = snprintf(buf, sizeof(buf), "%s %s", command, p);
2745
2746 if (bytes != (off_t)-1) {
2747 len += snprintf(buf + len, sizeof(buf) - len,
2748 " = " LLF " byte%s", (LLT) bytes, PLURAL(bytes));
2749 } else if (file2 != NULL) {
2750 if ((p = realpath(file2, realfile)) == NULL)
2751 p = file2;
2752 len += snprintf(buf + len, sizeof(buf) - len, " %s", p);
2753 }
2754
2755 if (elapsed != NULL) {
2756 len += snprintf(buf + len, sizeof(buf) - len,
2757 " in %ld.%.03d seconds", elapsed->tv_sec,
2758 (int)(elapsed->tv_usec / 1000));
2759 }
2760
2761 if (error != NULL)
2762 len += snprintf(buf + len, sizeof(buf) - len, ": %s", error);
2763
2764 syslog(LOG_INFO, "%s", buf);
2765 }
2766
2767 char *
2768 xstrdup(const char *s)
2769 {
2770 char *new = strdup(s);
2771
2772 if (new == NULL)
2773 fatal("Local resource failure: malloc");
2774 /* NOTREACHED */
2775 return (new);
2776 }
2777
2778 /*
2779 * As per fprintf(), but increment total_bytes and total_bytes_out,
2780 * by the appropriate amount.
2781 */
2782 void
2783 cprintf(FILE *fd, const char *fmt, ...)
2784 {
2785 off_t b;
2786 va_list ap;
2787
2788 va_start(ap, fmt);
2789 b = vfprintf(fd, fmt, ap);
2790 total_bytes += b;
2791 total_bytes_out += b;
2792 }
2793