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