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