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