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