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