ftpd.c revision 1.95 1 /* $NetBSD: ftpd.c,v 1.95 2000/06/19 15:15:04 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.95 2000/06/19 15:15:04 lukem Exp $");
113 #endif
114 #endif /* not lint */
115
116 /*
117 * FTP server.
118 */
119 #include <sys/param.h>
120 #include <sys/stat.h>
121 #include <sys/ioctl.h>
122 #include <sys/socket.h>
123 #include <sys/wait.h>
124
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 break;
1453 usleep(1000000 - td.tv_usec);
1454 }
1455 } else {
1456 while ((c = read(filefd, buf, (size_t)blksize)) > 0) {
1457 if (write(netfd, buf, c) != c)
1458 goto data_err;
1459 (void) alarm(curclass.timeout);
1460 byte_count += c;
1461 if (isdata) {
1462 total_data_out += c;
1463 total_data += c;
1464 }
1465 total_bytes_out += c;
1466 total_bytes += c;
1467 }
1468 }
1469 senddone:
1470 if (c < 0)
1471 goto file_err;
1472 rval = 0;
1473 goto cleanup_send_data;
1474
1475 default:
1476 reply(550, "Unimplemented TYPE %d in send_data", type);
1477 goto cleanup_send_data;
1478 }
1479
1480 data_err:
1481 (void) alarm(0);
1482 perror_reply(426, "Data connection");
1483 goto cleanup_send_data;
1484
1485 file_err:
1486 (void) alarm(0);
1487 perror_reply(551, "Error on input file");
1488 /* FALLTHROUGH */
1489
1490 cleanup_send_data:
1491 (void) alarm(0);
1492 transflag = 0;
1493 if (buf)
1494 free(buf);
1495 if (isdata) {
1496 total_files_out++;
1497 total_files++;
1498 }
1499 total_xfers_out++;
1500 total_xfers++;
1501 return (rval);
1502 }
1503
1504 /*
1505 * Transfer data from peer to "outstr" using the appropriate encapulation of
1506 * the data subject to Mode, Structure, and Type.
1507 *
1508 * N.B.: Form isn't handled.
1509 */
1510 static int
1511 receive_data(FILE *instr, FILE *outstr)
1512 {
1513 int c, bare_lfs, netfd, filefd, rval;
1514 char buf[BUFSIZ];
1515 #ifdef __GNUC__
1516 (void) &bare_lfs;
1517 #endif
1518
1519 bare_lfs = 0;
1520 transflag = 1;
1521 rval = -1;
1522 if (setjmp(urgcatch))
1523 goto cleanup_recv_data;
1524
1525 switch (type) {
1526
1527 case TYPE_I:
1528 case TYPE_L:
1529 netfd = fileno(instr);
1530 filefd = fileno(outstr);
1531 (void) alarm(curclass.timeout);
1532 if (curclass.rateput) {
1533 while (1) {
1534 int d;
1535 struct timeval then, now, td;
1536 off_t bufrem;
1537
1538 (void)gettimeofday(&then, NULL);
1539 errno = c = d = 0;
1540 for (bufrem = curclass.rateput; bufrem > 0; ) {
1541 if ((c = read(netfd, buf,
1542 MIN(sizeof(buf), bufrem))) <= 0)
1543 goto recvdone;
1544 if ((d = write(filefd, buf, c)) != c)
1545 goto recvdone;
1546 (void) alarm(curclass.timeout);
1547 bufrem -= c;
1548 byte_count += c;
1549 total_data_in += c;
1550 total_data += c;
1551 total_bytes_in += c;
1552 total_bytes += c;
1553 }
1554 (void)gettimeofday(&now, NULL);
1555 timersub(&now, &then, &td);
1556 if (td.tv_sec > 0)
1557 break;
1558 usleep(1000000 - td.tv_usec);
1559 }
1560 } else {
1561 while ((c = read(netfd, buf, sizeof(buf))) > 0) {
1562 if (write(filefd, buf, c) != c)
1563 goto file_err;
1564 (void) alarm(curclass.timeout);
1565 byte_count += c;
1566 total_data_in += c;
1567 total_data += c;
1568 total_bytes_in += c;
1569 total_bytes += c;
1570 }
1571 }
1572 recvdone:
1573 if (c < 0)
1574 goto data_err;
1575 rval = 0;
1576 goto cleanup_recv_data;
1577
1578 case TYPE_E:
1579 reply(553, "TYPE E not implemented.");
1580 goto cleanup_recv_data;
1581
1582 case TYPE_A:
1583 (void) alarm(curclass.timeout);
1584 /* XXXX: rate limit ascii receive (put) */
1585 while ((c = getc(instr)) != EOF) {
1586 byte_count++;
1587 total_data_in++;
1588 total_data++;
1589 total_bytes_in++;
1590 total_bytes++;
1591 if ((byte_count % 4096) == 0)
1592 (void) alarm(curclass.timeout);
1593 if (c == '\n')
1594 bare_lfs++;
1595 while (c == '\r') {
1596 if (ferror(outstr))
1597 goto data_err;
1598 if ((c = getc(instr)) != '\n') {
1599 byte_count++;
1600 total_data_in++;
1601 total_data++;
1602 total_bytes_in++;
1603 total_bytes++;
1604 if ((byte_count % 4096) == 0)
1605 (void) alarm(curclass.timeout);
1606 (void) putc ('\r', outstr);
1607 if (c == '\0' || c == EOF)
1608 goto contin2;
1609 }
1610 }
1611 (void) putc(c, outstr);
1612 contin2: ;
1613 }
1614 (void) alarm(0);
1615 fflush(outstr);
1616 if (ferror(instr))
1617 goto data_err;
1618 if (ferror(outstr))
1619 goto file_err;
1620 if (bare_lfs) {
1621 reply(-226,
1622 "WARNING! %d bare linefeeds received in ASCII mode",
1623 bare_lfs);
1624 reply(0, "File may not have transferred correctly.");
1625 }
1626 rval = 0;
1627 goto cleanup_recv_data;
1628
1629 default:
1630 reply(550, "Unimplemented TYPE %d in receive_data", type);
1631 goto cleanup_recv_data;
1632 }
1633
1634 data_err:
1635 (void) alarm(0);
1636 perror_reply(426, "Data Connection");
1637 goto cleanup_recv_data;
1638
1639 file_err:
1640 (void) alarm(0);
1641 perror_reply(452, "Error writing file");
1642 goto cleanup_recv_data;
1643
1644 cleanup_recv_data:
1645 (void) alarm(0);
1646 transflag = 0;
1647 total_files_in++;
1648 total_files++;
1649 total_xfers_in++;
1650 total_xfers++;
1651 return (rval);
1652 }
1653
1654 void
1655 statcmd(void)
1656 {
1657 union sockunion *su = NULL;
1658 static char ntop_buf[INET6_ADDRSTRLEN];
1659 u_char *a, *p;
1660 int ispassive, af;
1661 off_t otbi, otbo, otb;
1662
1663 a = p = (u_char *)NULL;
1664
1665 reply(-211, "%s FTP server status:", hostname);
1666 reply(0, "Version: %s", FTPD_VERSION);
1667 ntop_buf[0] = '\0';
1668 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1669 ntop_buf, sizeof(ntop_buf), NULL, 0, NI_NUMERICHOST)
1670 && strcmp(remotehost, ntop_buf) != 0) {
1671 reply(0, "Connected to %s (%s)", remotehost, ntop_buf);
1672 } else
1673 reply(0, "Connected to %s", remotehost);
1674 if (logged_in) {
1675 if (curclass.type == CLASS_GUEST)
1676 reply(0, "Logged in anonymously");
1677 else
1678 reply(0, "Logged in as %s%s", pw->pw_name,
1679 curclass.type == CLASS_CHROOT ? " (chroot)" : "");
1680 } else if (askpasswd)
1681 reply(0, "Waiting for password");
1682 else
1683 reply(0, "Waiting for user name");
1684 cprintf(stdout, " TYPE: %s", typenames[type]);
1685 if (type == TYPE_A || type == TYPE_E)
1686 cprintf(stdout, ", FORM: %s", formnames[form]);
1687 if (type == TYPE_L) {
1688 #if NBBY == 8
1689 cprintf(stdout, " %d", NBBY);
1690 #else
1691 /* XXX: `bytesize' needs to be defined in this case */
1692 cprintf(stdout, " %d", bytesize);
1693 #endif
1694 }
1695 cprintf(stdout, "; STRUcture: %s; transfer MODE: %s\r\n",
1696 strunames[stru], modenames[mode]);
1697 ispassive = 0;
1698 if (data != -1) {
1699 reply(0, "Data connection open");
1700 su = NULL;
1701 } else if (pdata != -1) {
1702 reply(0, "in Passive mode");
1703 su = (union sockunion *)&pasv_addr;
1704 ispassive = 1;
1705 goto printaddr;
1706 } else if (usedefault == 0) {
1707 if (epsvall) {
1708 reply(0, "EPSV only mode (EPSV ALL)");
1709 goto epsvonly;
1710 }
1711 su = (union sockunion *)&data_dest;
1712 printaddr:
1713 /* PASV/PORT */
1714 if (su->su_family == AF_INET) {
1715 a = (u_char *) &su->su_sin.sin_addr;
1716 p = (u_char *) &su->su_sin.sin_port;
1717 #define UC(b) (((int) b) & 0xff)
1718 reply(0, "%s (%d,%d,%d,%d,%d,%d)",
1719 ispassive ? "PASV" : "PORT" ,
1720 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
1721 UC(p[0]), UC(p[1]));
1722 }
1723
1724 /* LPSV/LPRT */
1725 {
1726 int alen, af, i;
1727
1728 alen = 0;
1729 switch (su->su_family) {
1730 case AF_INET:
1731 a = (u_char *) &su->su_sin.sin_addr;
1732 p = (u_char *) &su->su_sin.sin_port;
1733 alen = sizeof(su->su_sin.sin_addr);
1734 af = 4;
1735 break;
1736 case AF_INET6:
1737 a = (u_char *) &su->su_sin6.sin6_addr;
1738 p = (u_char *) &su->su_sin6.sin6_port;
1739 alen = sizeof(su->su_sin6.sin6_addr);
1740 af = 6;
1741 break;
1742 default:
1743 af = 0;
1744 break;
1745 }
1746 if (af) {
1747 cprintf(stdout, " %s (%d,%d",
1748 ispassive ? "LPSV" : "LPRT", af, alen);
1749 for (i = 0; i < alen; i++)
1750 cprintf(stdout, ",%d", UC(a[i]));
1751 cprintf(stdout, ",%d,%d,%d)", 2, UC(p[0]), UC(p[1]));
1752 #undef UC
1753 }
1754 }
1755
1756 /* EPRT/EPSV */
1757 epsvonly:
1758 switch (su->su_family) {
1759 case AF_INET:
1760 af = 1;
1761 break;
1762 case AF_INET6:
1763 af = 2;
1764 break;
1765 default:
1766 af = 0;
1767 break;
1768 }
1769 if (af) {
1770 if (getnameinfo((struct sockaddr *)su, su->su_len,
1771 ntop_buf, sizeof(ntop_buf), NULL, 0,
1772 NI_NUMERICHOST) == 0) {
1773 reply(0, "%s (|%d|%s|%d|)",
1774 ispassive ? "EPSV" : "EPRT",
1775 af, ntop_buf, ntohs(su->su_port));
1776 }
1777 }
1778 } else
1779 reply(0, "No data connection");
1780
1781 if (logged_in) {
1782 reply(0, "Data sent: %qd byte%s in %qd file%s",
1783 (qdfmt_t)total_data_out, PLURAL(total_data_out),
1784 (qdfmt_t)total_files_out, PLURAL(total_files_out));
1785 reply(0, "Data received: %qd byte%s in %qd file%s",
1786 (qdfmt_t)total_data_in, PLURAL(total_data_in),
1787 (qdfmt_t)total_files_in, PLURAL(total_files_in));
1788 reply(0, "Total data: %qd byte%s in %qd file%s",
1789 (qdfmt_t)total_data, PLURAL(total_data),
1790 (qdfmt_t)total_files, PLURAL(total_files));
1791 }
1792 otbi = total_bytes_in;
1793 otbo = total_bytes_out;
1794 otb = total_bytes;
1795 reply(0, "Traffic sent: %qd byte%s in %qd transfer%s",
1796 (qdfmt_t)otbo, PLURAL(otbo),
1797 (qdfmt_t)total_xfers_out, PLURAL(total_xfers_out));
1798 reply(0, "Traffic received: %qd byte%s in %qd transfer%s",
1799 (qdfmt_t)otbi, PLURAL(otbi),
1800 (qdfmt_t)total_xfers_in, PLURAL(total_xfers_in));
1801 reply(0, "Total traffic: %qd byte%s in %qd transfer%s",
1802 (qdfmt_t)otb, PLURAL(otb),
1803 (qdfmt_t)total_xfers, PLURAL(total_xfers));
1804
1805 if (logged_in) {
1806 struct ftpconv *cp;
1807
1808 reply(0, "");
1809 reply(0, "Class: %s, type: %s",
1810 curclass.classname, CURCLASSTYPE);
1811 reply(0, "Check PORT/LPRT commands: %sabled",
1812 curclass.checkportcmd ? "en" : "dis");
1813 if (curclass.display != NULL)
1814 reply(0, "Display file: %s", curclass.display);
1815 if (curclass.notify != NULL)
1816 reply(0, "Notify fileglob: %s", curclass.notify);
1817 reply(0, "Idle timeout: %d, maximum timeout: %d",
1818 curclass.timeout, curclass.maxtimeout);
1819 reply(0, "Current connections: %d", connections);
1820 if (curclass.limit == -1)
1821 reply(0, "Maximum connections: unlimited");
1822 else
1823 reply(0, "Maximum connections: %d", curclass.limit);
1824 if (curclass.limitfile)
1825 reply(0, "Connection limit exceeded file: %s",
1826 curclass.limitfile);
1827 if (curclass.motd != NULL)
1828 reply(0, "MotD file: %s", curclass.motd);
1829 reply(0,
1830 "Modify commands (CHMOD, DELE, MKD, RMD, RNFR, UMASK): %sabled",
1831 curclass.modify ? "en" : "dis");
1832 reply(0, "Upload commands (APPE, STOR, STOU): %sabled",
1833 curclass.upload ? "en" : "dis");
1834 if (curclass.portmin && curclass.portmax)
1835 reply(0, "PASV port range: %d - %d",
1836 curclass.portmin, curclass.portmax);
1837 if (curclass.rateget)
1838 reply(0, "Rate get limit: %d bytes/sec",
1839 curclass.rateget);
1840 else
1841 reply(0, "Rate get limit: disabled");
1842 if (curclass.rateput)
1843 reply(0, "Rate put limit: %d bytes/sec",
1844 curclass.rateput);
1845 else
1846 reply(0, "Rate put limit: disabled");
1847 reply(0, "Umask: %.04o", curclass.umask);
1848 for (cp = curclass.conversions; cp != NULL; cp=cp->next) {
1849 if (cp->suffix == NULL || cp->types == NULL ||
1850 cp->command == NULL)
1851 continue;
1852 reply(0, "Conversion: %s [%s] disable: %s, command: %s",
1853 cp->suffix, cp->types, cp->disable, cp->command);
1854 }
1855 }
1856
1857 reply(211, "End of status");
1858 }
1859
1860 void
1861 fatal(const char *s)
1862 {
1863
1864 reply(451, "Error in server: %s\n", s);
1865 reply(221, "Closing connection due to server error.");
1866 dologout(0);
1867 /* NOTREACHED */
1868 }
1869
1870 /*
1871 * reply() --
1872 * depending on the value of n, display fmt with a trailing CRLF and
1873 * prefix of:
1874 * n < -1 prefix the message with abs(n) + "-" (initial line)
1875 * n == 0 prefix the message with 4 spaces (middle lines)
1876 * n > 0 prefix the message with n + " " (final line)
1877 */
1878 void
1879 reply(int n, const char *fmt, ...)
1880 {
1881 off_t b;
1882 va_list ap;
1883
1884 va_start(ap, fmt);
1885 b = 0;
1886 if (n == 0)
1887 cprintf(stdout, " ");
1888 else if (n < 0)
1889 cprintf(stdout, "%d-", -n);
1890 else
1891 cprintf(stdout, "%d ", n);
1892 b = vprintf(fmt, ap);
1893 total_bytes += b;
1894 total_bytes_out += b;
1895 cprintf(stdout, "\r\n");
1896 (void)fflush(stdout);
1897 if (debug) {
1898 syslog(LOG_DEBUG, "<--- %d%c", abs(n), (n < 0) ? '-' : ' ');
1899 vsyslog(LOG_DEBUG, fmt, ap);
1900 }
1901 }
1902
1903 static void
1904 dolog(struct sockaddr *who)
1905 {
1906 getnameinfo(who, who->sa_len, remotehost, sizeof(remotehost), NULL,0,0);
1907 #ifdef HASSETPROCTITLE
1908 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
1909 setproctitle(proctitle);
1910 #endif /* HASSETPROCTITLE */
1911 if (logging)
1912 syslog(LOG_INFO, "connection from %s to %s",
1913 remotehost, hostname);
1914 }
1915
1916 /*
1917 * Record logout in wtmp file
1918 * and exit with supplied status.
1919 */
1920 void
1921 dologout(int status)
1922 {
1923 /*
1924 * Prevent reception of SIGURG from resulting in a resumption
1925 * back to the main program loop.
1926 */
1927 transflag = 0;
1928
1929 if (logged_in) {
1930 (void) seteuid((uid_t)0);
1931 logwtmp(ttyline, "", "");
1932 if (doutmp)
1933 logout(utmp.ut_line);
1934 #ifdef KERBEROS
1935 if (!notickets && krbtkfile_env)
1936 unlink(krbtkfile_env);
1937 #endif
1938 }
1939 /* beware of flushing buffers after a SIGPIPE */
1940 _exit(status);
1941 }
1942
1943 static void
1944 myoob(int signo)
1945 {
1946 char *cp;
1947
1948 /* only process if transfer occurring */
1949 if (!transflag)
1950 return;
1951 cp = tmpline;
1952 if (getline(cp, 7, stdin) == NULL) {
1953 reply(221, "You could at least say goodbye.");
1954 dologout(0);
1955 }
1956 if (strcasecmp(cp, "ABOR\r\n") == 0) {
1957 tmpline[0] = '\0';
1958 reply(426, "Transfer aborted. Data connection closed.");
1959 reply(226, "Abort successful");
1960 longjmp(urgcatch, 1);
1961 }
1962 if (strcasecmp(cp, "STAT\r\n") == 0) {
1963 tmpline[0] = '\0';
1964 if (file_size != (off_t) -1)
1965 reply(213, "Status: %qd of %qd byte%s transferred",
1966 (qdfmt_t)byte_count, (qdfmt_t)file_size,
1967 PLURAL(byte_count));
1968 else
1969 reply(213, "Status: %qd byte%s transferred",
1970 (qdfmt_t)byte_count, PLURAL(byte_count));
1971 }
1972 }
1973
1974 static int
1975 bind_pasv_addr(void)
1976 {
1977 static int passiveport;
1978 int port, len;
1979
1980 len = pasv_addr.su_len;
1981 if (curclass.portmin == 0 && curclass.portmax == 0) {
1982 pasv_addr.su_port = 0;
1983 return (bind(pdata, (struct sockaddr *)&pasv_addr, len));
1984 }
1985
1986 if (passiveport == 0) {
1987 srand(getpid());
1988 passiveport = rand() % (curclass.portmax - curclass.portmin)
1989 + curclass.portmin;
1990 }
1991
1992 port = passiveport;
1993 while (1) {
1994 port++;
1995 if (port > curclass.portmax)
1996 port = curclass.portmin;
1997 else if (port == passiveport) {
1998 errno = EAGAIN;
1999 return (-1);
2000 }
2001 pasv_addr.su_port = htons(port);
2002 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) == 0)
2003 break;
2004 if (errno != EADDRINUSE)
2005 return (-1);
2006 }
2007 passiveport = port;
2008 return (0);
2009 }
2010
2011 /*
2012 * Note: a response of 425 is not mentioned as a possible response to
2013 * the PASV command in RFC959. However, it has been blessed as
2014 * a legitimate response by Jon Postel in a telephone conversation
2015 * with Rick Adams on 25 Jan 89.
2016 */
2017 void
2018 passive(void)
2019 {
2020 int len;
2021 char *p, *a;
2022
2023 if (pdata >= 0)
2024 close(pdata);
2025 pdata = socket(AF_INET, SOCK_STREAM, 0);
2026 if (pdata < 0 || !logged_in) {
2027 perror_reply(425, "Can't open passive connection");
2028 return;
2029 }
2030 pasv_addr = ctrl_addr;
2031
2032 if (bind_pasv_addr() < 0)
2033 goto pasv_error;
2034 len = pasv_addr.su_len;
2035 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2036 goto pasv_error;
2037 if (listen(pdata, 1) < 0)
2038 goto pasv_error;
2039 a = (char *) &pasv_addr.su_sin.sin_addr;
2040 p = (char *) &pasv_addr.su_port;
2041
2042 #define UC(b) (((int) b) & 0xff)
2043
2044 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2045 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2046 return;
2047
2048 pasv_error:
2049 (void) close(pdata);
2050 pdata = -1;
2051 perror_reply(425, "Can't open passive connection");
2052 return;
2053 }
2054
2055 /*
2056 * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)
2057 * 229 Entering Extended Passive Mode (|||port|)
2058 */
2059 void
2060 long_passive(char *cmd, int pf)
2061 {
2062 int len;
2063 char *p, *a;
2064
2065 if (!logged_in) {
2066 syslog(LOG_NOTICE, "long passive but not logged in");
2067 reply(503, "Login with USER first.");
2068 return;
2069 }
2070
2071 if (pf != PF_UNSPEC) {
2072 if (ctrl_addr.su_family != pf) {
2073 switch (ctrl_addr.su_family) {
2074 case AF_INET:
2075 pf = 1;
2076 break;
2077 case AF_INET6:
2078 pf = 2;
2079 break;
2080 default:
2081 pf = 0;
2082 break;
2083 }
2084 /*
2085 * XXX
2086 * only EPRT/EPSV ready clients will understand this
2087 */
2088 if (strcmp(cmd, "EPSV") == 0 && pf) {
2089 reply(522, "Network protocol mismatch, "
2090 "use (%d)", pf);
2091 } else
2092 reply(501, "Network protocol mismatch"); /*XXX*/
2093
2094 return;
2095 }
2096 }
2097
2098 if (pdata >= 0)
2099 close(pdata);
2100 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2101 if (pdata < 0) {
2102 perror_reply(425, "Can't open passive connection");
2103 return;
2104 }
2105 pasv_addr = ctrl_addr;
2106 if (bind_pasv_addr() < 0)
2107 goto pasv_error;
2108 len = pasv_addr.su_len;
2109 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2110 goto pasv_error;
2111 if (listen(pdata, 1) < 0)
2112 goto pasv_error;
2113 p = (char *) &pasv_addr.su_port;
2114
2115 #define UC(b) (((int) b) & 0xff)
2116
2117 if (strcmp(cmd, "LPSV") == 0) {
2118 switch (pasv_addr.su_family) {
2119 case AF_INET:
2120 a = (char *) &pasv_addr.su_sin.sin_addr;
2121 reply(228, "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2122 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2123 2, UC(p[0]), UC(p[1]));
2124 return;
2125 case AF_INET6:
2126 a = (char *) &pasv_addr.su_sin6.sin6_addr;
2127 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)",
2128 6, 16,
2129 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2130 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2131 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2132 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2133 2, UC(p[0]), UC(p[1]));
2134 return;
2135 }
2136 #undef UC
2137 } else if (strcmp(cmd, "EPSV") == 0) {
2138 switch (pasv_addr.su_family) {
2139 case AF_INET:
2140 case AF_INET6:
2141 reply(229, "Entering Extended Passive Mode (|||%d|)",
2142 ntohs(pasv_addr.su_port));
2143 return;
2144 }
2145 } else {
2146 /* more proper error code? */
2147 }
2148
2149 pasv_error:
2150 (void) close(pdata);
2151 pdata = -1;
2152 perror_reply(425, "Can't open passive connection");
2153 return;
2154 }
2155
2156 /*
2157 * Generate unique name for file with basename "local".
2158 * The file named "local" is already known to exist.
2159 * Generates failure reply on error.
2160 *
2161 * XXX this function should under go changes similar to
2162 * the mktemp(3)/mkstemp(3) changes.
2163 */
2164 static char *
2165 gunique(const char *local)
2166 {
2167 static char new[MAXPATHLEN];
2168 struct stat st;
2169 char *cp;
2170 int count;
2171
2172 cp = strrchr(local, '/');
2173 if (cp)
2174 *cp = '\0';
2175 if (stat(cp ? local : ".", &st) < 0) {
2176 perror_reply(553, cp ? local : ".");
2177 return (NULL);
2178 }
2179 if (cp)
2180 *cp = '/';
2181 for (count = 1; count < 100; count++) {
2182 (void)snprintf(new, sizeof(new) - 1, "%s.%d", local, count);
2183 if (stat(new, &st) < 0)
2184 return (new);
2185 }
2186 reply(452, "Unique file name cannot be created.");
2187 return (NULL);
2188 }
2189
2190 /*
2191 * Format and send reply containing system error number.
2192 */
2193 void
2194 perror_reply(int code, const char *string)
2195 {
2196 int save_errno;
2197
2198 save_errno = errno;
2199 reply(code, "%s: %s.", string, strerror(errno));
2200 errno = save_errno;
2201 }
2202
2203 static char *onefile[] = {
2204 "",
2205 0
2206 };
2207
2208 void
2209 send_file_list(const char *whichf)
2210 {
2211 struct stat st;
2212 DIR *dirp = NULL;
2213 struct dirent *dir;
2214 FILE *dout = NULL;
2215 char **dirlist, *dirname, *p;
2216 int simple = 0;
2217 int freeglob = 0;
2218 glob_t gl;
2219 off_t b;
2220
2221 #ifdef __GNUC__
2222 (void) &dout;
2223 (void) &dirlist;
2224 (void) &simple;
2225 (void) &freeglob;
2226 #endif
2227
2228 p = NULL;
2229 if (strpbrk(whichf, "~{[*?") != NULL) {
2230 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
2231
2232 memset(&gl, 0, sizeof(gl));
2233 freeglob = 1;
2234 if (glob(whichf, flags, 0, &gl)) {
2235 reply(550, "not found");
2236 goto out;
2237 } else if (gl.gl_pathc == 0) {
2238 errno = ENOENT;
2239 perror_reply(550, whichf);
2240 goto out;
2241 }
2242 dirlist = gl.gl_pathv;
2243 } else {
2244 p = xstrdup(whichf);
2245 onefile[0] = p;
2246 dirlist = onefile;
2247 simple = 1;
2248 }
2249 /* XXX: } for vi sm */
2250
2251 if (setjmp(urgcatch)) {
2252 transflag = 0;
2253 goto out;
2254 }
2255 while ((dirname = *dirlist++) != NULL) {
2256 int trailingslash = 0;
2257
2258 if (stat(dirname, &st) < 0) {
2259 /*
2260 * If user typed "ls -l", etc, and the client
2261 * used NLST, do what the user meant.
2262 */
2263 /* XXX: nuke this support? */
2264 if (dirname[0] == '-' && *dirlist == NULL &&
2265 transflag == 0) {
2266 char *argv[] = { INTERNAL_LS, "", NULL };
2267
2268 argv[1] = dirname;
2269 retrieve(argv, dirname);
2270 goto out;
2271 }
2272 perror_reply(550, whichf);
2273 goto cleanup_send_file_list;
2274 }
2275
2276 if (S_ISREG(st.st_mode)) {
2277 if (dout == NULL) {
2278 dout = dataconn("file list", (off_t)-1, "w");
2279 if (dout == NULL)
2280 goto out;
2281 transflag++;
2282 }
2283 b = fprintf(dout, "%s%s\n", dirname,
2284 type == TYPE_A ? "\r" : "");
2285 total_bytes += b;
2286 total_bytes_out += b;
2287 byte_count += strlen(dirname) + 1;
2288 continue;
2289 } else if (!S_ISDIR(st.st_mode))
2290 continue;
2291
2292 if (dirname[strlen(dirname) - 1] == '/')
2293 trailingslash++;
2294
2295 if ((dirp = opendir(dirname)) == NULL)
2296 continue;
2297
2298 while ((dir = readdir(dirp)) != NULL) {
2299 char nbuf[MAXPATHLEN];
2300
2301 if (ISDOTDIR(dir->d_name) || ISDOTDOTDIR(dir->d_name))
2302 continue;
2303
2304 (void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
2305 trailingslash ? "" : "/", dir->d_name);
2306
2307 /*
2308 * We have to do a stat to ensure it's
2309 * not a directory or special file.
2310 */
2311 /* XXX: follow RFC959 and filter out non files ? */
2312 if (simple || (stat(nbuf, &st) == 0 &&
2313 S_ISREG(st.st_mode))) {
2314 char *p;
2315
2316 if (dout == NULL) {
2317 dout = dataconn("file list", (off_t)-1,
2318 "w");
2319 if (dout == NULL)
2320 goto out;
2321 transflag++;
2322 }
2323 p = nbuf;
2324 if (nbuf[0] == '.' && nbuf[1] == '/')
2325 p = &nbuf[2];
2326 b = fprintf(dout, "%s%s\n", p,
2327 type == TYPE_A ? "\r" : "");
2328 total_bytes += b;
2329 total_bytes_out += b;
2330 byte_count += strlen(nbuf) + 1;
2331 }
2332 }
2333 (void) closedir(dirp);
2334 }
2335
2336 if (dout == NULL)
2337 reply(550, "No files found.");
2338 else if (ferror(dout) != 0)
2339 perror_reply(550, "Data connection");
2340 else
2341 reply(226, "Transfer complete.");
2342
2343 cleanup_send_file_list:
2344 transflag = 0;
2345 closedataconn(dout);
2346 out:
2347 total_xfers++;
2348 total_xfers_out++;
2349 if (p)
2350 free(p);
2351 if (freeglob)
2352 globfree(&gl);
2353 }
2354
2355 char *
2356 conffilename(const char *s)
2357 {
2358 static char filename[MAXPATHLEN];
2359
2360 if (*s == '/')
2361 strlcpy(filename, s, sizeof(filename));
2362 else
2363 (void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
2364 return (filename);
2365 }
2366
2367 /*
2368 * logcmd --
2369 * based on the arguments, syslog a message:
2370 * if bytes != -1 "<command> <file1> = <bytes> bytes"
2371 * else if file2 != NULL "<command> <file1> <file2>"
2372 * else "<command> <file1>"
2373 * if elapsed != NULL, append "in xxx.yyy seconds"
2374 * if error != NULL, append ": " + error
2375 */
2376 void
2377 logcmd(const char *command, off_t bytes, const char *file1, const char *file2,
2378 const struct timeval *elapsed, const char *error)
2379 {
2380 char buf[MAXPATHLEN * 2 + 100], realfile[MAXPATHLEN];
2381 const char *p;
2382 size_t len;
2383
2384 if (logging <=1)
2385 return;
2386
2387 if ((p = realpath(file1, realfile)) == NULL) {
2388 #if 0 /* XXX: too noisy */
2389 syslog(LOG_WARNING, "realpath `%s' failed: %s",
2390 realfile, strerror(errno));
2391 #endif
2392 p = file1;
2393 }
2394 len = snprintf(buf, sizeof(buf), "%s %s", command, p);
2395
2396 if (bytes != (off_t)-1) {
2397 len += snprintf(buf + len, sizeof(buf) - len,
2398 " = %qd byte%s", (qdfmt_t) bytes, PLURAL(bytes));
2399 } else if (file2 != NULL) {
2400 if ((p = realpath(file2, realfile)) == NULL) {
2401 #if 0 /* XXX: too noisy */
2402 syslog(LOG_WARNING, "realpath `%s' failed: %s",
2403 realfile, strerror(errno));
2404 #endif
2405 p = file2;
2406 }
2407 len += snprintf(buf + len, sizeof(buf) - len, " %s", p);
2408 }
2409
2410 if (elapsed != NULL) {
2411 len += snprintf(buf + len, sizeof(buf) - len,
2412 " in %ld.%.03d seconds", elapsed->tv_sec,
2413 (int)(elapsed->tv_usec / 1000));
2414 }
2415
2416 if (error != NULL)
2417 len += snprintf(buf + len, sizeof(buf) - len, ": %s", error);
2418
2419 syslog(LOG_INFO, "%s", buf);
2420 }
2421
2422 char *
2423 xstrdup(const char *s)
2424 {
2425 char *new = strdup(s);
2426
2427 if (new == NULL)
2428 fatal("Local resource failure: malloc");
2429 /* NOTREACHED */
2430 return (new);
2431 }
2432
2433 /*
2434 * As per fprintf(), but increment total_bytes and total_bytes_out,
2435 * by the appropriate amount.
2436 */
2437 void
2438 cprintf(FILE *fd, const char *fmt, ...)
2439 {
2440 off_t b;
2441 va_list ap;
2442
2443 va_start(ap, fmt);
2444 b = vfprintf(fd, fmt, ap);
2445 total_bytes += b;
2446 total_bytes_out += b;
2447 }
2448