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