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