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