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