ftpd.c revision 1.84 1 /* $NetBSD: ftpd.c,v 1.84 2000/01/12 22:39:28 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.84 2000/01/12 22:39:28 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 curclass.type = CLASS_REAL;
782 }
783
784 void
785 pass(passwd)
786 const char *passwd;
787 {
788 int rval;
789 const char *cp, *shell, *home;
790 char *class;
791
792 class = NULL;
793 if (logged_in || askpasswd == 0) {
794 reply(503, "Login with USER first.");
795 return;
796 }
797 askpasswd = 0;
798 if (curclass.type != CLASS_GUEST) {
799 /* "ftp" is only account allowed no password */
800 if (pw == NULL) {
801 rval = 1; /* failure below */
802 goto skip;
803 }
804 #if defined(KERBEROS) || defined(KERBEROS5)
805 if (klogin(pw, "", hostname, (char *)passwd) == 0) {
806 rval = 0;
807 goto skip;
808 }
809 #endif
810 #ifdef SKEY
811 if (skey_haskey(pw->pw_name) == 0) {
812 char *p;
813 int r;
814
815 p = xstrdup(passwd);
816 r = skey_passcheck(pw->pw_name, p);
817 free(p);
818 if (r != -1) {
819 rval = 0;
820 goto skip;
821 }
822 }
823 #endif
824 if (!sflag && *pw->pw_passwd != '\0' &&
825 !strcmp(crypt(passwd, pw->pw_passwd), pw->pw_passwd)) {
826 rval = 0;
827 goto skip;
828 }
829 rval = 1;
830
831 skip:
832 if (pw != NULL && pw->pw_expire && time(NULL) >= pw->pw_expire)
833 rval = 2;
834 /*
835 * If rval > 0, the user failed the authentication check
836 * above. If rval == 0, either Kerberos or local authentication
837 * succeeded.
838 */
839 if (rval) {
840 reply(530, rval == 2 ? "Password expired." :
841 "Login incorrect.");
842 if (logging) {
843 syslog(LOG_NOTICE,
844 "FTP LOGIN FAILED FROM %s", remotehost);
845 syslog(LOG_AUTHPRIV | LOG_NOTICE,
846 "FTP LOGIN FAILED FROM %s, %s",
847 remotehost, curname);
848 }
849 pw = NULL;
850 if (login_attempts++ >= 5) {
851 syslog(LOG_NOTICE,
852 "repeated login failures from %s",
853 remotehost);
854 exit(0);
855 }
856 return;
857 }
858 }
859
860 /* password was ok; see if anything else prevents login */
861 if (! checkuser(_PATH_FTPUSERS, pw->pw_name, 1, 0, &class)) {
862 reply(530, "User %s may not use FTP.", pw->pw_name);
863 if (logging)
864 syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
865 remotehost, pw->pw_name);
866 goto bad;
867 }
868 /* check for valid shell, if not guest user */
869 if ((shell = pw->pw_shell) == NULL || *shell == 0)
870 shell = _PATH_BSHELL;
871 while ((cp = getusershell()) != NULL)
872 if (strcmp(cp, shell) == 0)
873 break;
874 endusershell();
875 if (cp == NULL && curclass.type != CLASS_GUEST) {
876 reply(530, "User %s may not use FTP.", pw->pw_name);
877 if (logging)
878 syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
879 remotehost, pw->pw_name);
880 goto bad;
881 }
882
883 login_attempts = 0; /* this time successful */
884 if (setegid((gid_t)pw->pw_gid) < 0) {
885 reply(550, "Can't set gid.");
886 goto bad;
887 }
888 (void) initgroups(pw->pw_name, pw->pw_gid);
889
890 /* open wtmp before chroot */
891 logwtmp(ttyline, pw->pw_name, remotehost);
892
893 /* open utmp before chroot */
894 if (doutmp) {
895 memset((void *)&utmp, 0, sizeof(utmp));
896 (void)time(&utmp.ut_time);
897 (void)strncpy(utmp.ut_name, pw->pw_name, sizeof(utmp.ut_name));
898 (void)strncpy(utmp.ut_host, remotehost, sizeof(utmp.ut_host));
899 (void)strncpy(utmp.ut_line, ttyline, sizeof(utmp.ut_line));
900 login(&utmp);
901 }
902
903 logged_in = 1;
904
905 /* check user in /etc/ftpchroot */
906 if (checkuser(_PATH_FTPCHROOT, pw->pw_name, 0, 0, NULL)) {
907 if (curclass.type == CLASS_GUEST) {
908 syslog(LOG_NOTICE,
909 "Can't change guest user to chroot class; remove entry in %s",
910 _PATH_FTPCHROOT);
911 exit(1);
912 }
913 curclass.type = CLASS_CHROOT;
914 }
915 if (class == NULL) {
916 switch (curclass.type) {
917 case CLASS_GUEST:
918 class = xstrdup("guest");
919 break;
920 case CLASS_CHROOT:
921 class = xstrdup("chroot");
922 break;
923 case CLASS_REAL:
924 class = xstrdup("real");
925 break;
926 default:
927 abort();
928 }
929 }
930
931 /* parse ftpd.conf, setting up various parameters */
932 parse_conf(class);
933 count_users();
934 if (curclass.limit != -1 && connections > curclass.limit) {
935 if (! EMPTYSTR(curclass.limitfile))
936 (void)format_file(conffilename(curclass.limitfile),530);
937 reply(530,
938 "User %s access denied, connection limit of %d reached.",
939 pw->pw_name, curclass.limit);
940 syslog(LOG_NOTICE,
941 "Maximum connection limit of %d for class %s reached, login refused",
942 curclass.limit, curclass.classname);
943 goto bad;
944 }
945
946 home = "/";
947 switch (curclass.type) {
948 case CLASS_GUEST:
949 /*
950 * We MUST do a chdir() after the chroot. Otherwise
951 * the old current directory will be accessible as "."
952 * outside the new root!
953 */
954 if (chroot(anondir ? anondir : pw->pw_dir) < 0 ||
955 chdir("/") < 0) {
956 reply(550, "Can't set guest privileges.");
957 goto bad;
958 }
959 break;
960 case CLASS_CHROOT:
961 if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
962 reply(550, "Can't change root.");
963 goto bad;
964 }
965 break;
966 case CLASS_REAL:
967 if (chdir(pw->pw_dir) < 0) {
968 if (chdir("/") < 0) {
969 reply(530,
970 "User %s: can't change directory to %s.",
971 pw->pw_name, pw->pw_dir);
972 goto bad;
973 } else
974 lreply(230,
975 "No directory! Logging in with home=/");
976 } else
977 home = pw->pw_dir;
978 break;
979 }
980 if (seteuid((uid_t)pw->pw_uid) < 0) {
981 reply(550, "Can't set uid.");
982 goto bad;
983 }
984 setenv("HOME", home, 1);
985
986 /*
987 * Display a login message, if it exists.
988 * N.B. reply(230,) must follow the message.
989 */
990 (void)format_file(conffilename(curclass.motd), 230);
991 show_chdir_messages(230);
992 if (curclass.type == CLASS_GUEST) {
993 reply(230, "Guest login ok, access restrictions apply.");
994 #ifdef HASSETPROCTITLE
995 snprintf(proctitle, sizeof(proctitle),
996 "%s: anonymous/%.*s", remotehost,
997 (int) (sizeof(proctitle) - sizeof(remotehost) -
998 sizeof(": anonymous/")), passwd);
999 setproctitle(proctitle);
1000 #endif /* HASSETPROCTITLE */
1001 if (logging)
1002 syslog(LOG_INFO,
1003 "ANONYMOUS FTP LOGIN FROM %s, %s (class: %s, type: %s)",
1004 remotehost, passwd,
1005 curclass.classname, CURCLASSTYPE);
1006 } else {
1007 reply(230, "User %s logged in.", pw->pw_name);
1008 #ifdef HASSETPROCTITLE
1009 snprintf(proctitle, sizeof(proctitle),
1010 "%s: %s", remotehost, pw->pw_name);
1011 setproctitle(proctitle);
1012 #endif /* HASSETPROCTITLE */
1013 if (logging)
1014 syslog(LOG_INFO,
1015 "FTP LOGIN FROM %s as %s (class: %s, type: %s)",
1016 remotehost, pw->pw_name,
1017 curclass.classname, CURCLASSTYPE);
1018 }
1019 (void) umask(curclass.umask);
1020 goto cleanuppass;
1021 bad:
1022 /* Forget all about it... */
1023 end_login();
1024 cleanuppass:
1025 if (class)
1026 free(class);
1027 }
1028
1029 void
1030 retrieve(argv, name)
1031 char *argv[];
1032 const char *name;
1033 {
1034 FILE *fin = NULL, *dout;
1035 struct stat st;
1036 int (*closefunc) __P((FILE *)) = NULL;
1037 int log, sendrv, closerv, stderrfd, isconversion, isdata, isls;
1038 struct timeval start, finish, td, *tdp;
1039 const char *dispname;
1040
1041 sendrv = closerv = stderrfd = -1;
1042 isconversion = isdata = isls = log = 0;
1043 tdp = NULL;
1044 dispname = name;
1045 if (argv == NULL) {
1046 log = 1;
1047 isdata = 1;
1048 fin = fopen(name, "r");
1049 closefunc = fclose;
1050 if (fin == NULL)
1051 argv = do_conversion(name);
1052 if (argv != NULL) {
1053 isconversion++;
1054 syslog(LOG_INFO, "get command: '%s' on '%s'",
1055 argv[0], name);
1056 }
1057 }
1058 if (argv != NULL) {
1059 char temp[MAXPATHLEN];
1060
1061 if (strcmp(argv[0], INTERNAL_LS) == 0) {
1062 isls = 1;
1063 stderrfd = -1;
1064 } else {
1065 (void)snprintf(temp, sizeof(temp), "%s", TMPFILE);
1066 stderrfd = mkstemp(temp);
1067 if (stderrfd != -1)
1068 (void)unlink(temp);
1069 }
1070 dispname = argv[0];
1071 fin = ftpd_popen(argv, "r", stderrfd);
1072 closefunc = ftpd_pclose;
1073 st.st_size = -1;
1074 st.st_blksize = BUFSIZ;
1075 }
1076 if (fin == NULL) {
1077 if (errno != 0) {
1078 perror_reply(550, dispname);
1079 if (log)
1080 logcmd("get", -1, name, NULL, NULL,
1081 strerror(errno));
1082 }
1083 goto cleanupretrieve;
1084 }
1085 byte_count = -1;
1086 if (argv == NULL
1087 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
1088 reply(550, "%s: not a plain file.", dispname);
1089 goto done;
1090 }
1091 if (restart_point) {
1092 if (type == TYPE_A) {
1093 off_t i;
1094 int c;
1095
1096 for (i = 0; i < restart_point; i++) {
1097 if ((c=getc(fin)) == EOF) {
1098 perror_reply(550, dispname);
1099 goto done;
1100 }
1101 if (c == '\n')
1102 i++;
1103 }
1104 } else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
1105 perror_reply(550, dispname);
1106 goto done;
1107 }
1108 }
1109 dout = dataconn(dispname, st.st_size, "w");
1110 if (dout == NULL)
1111 goto done;
1112
1113 (void)gettimeofday(&start, NULL);
1114 sendrv = send_data(fin, dout, st.st_blksize, isdata);
1115 (void)gettimeofday(&finish, NULL);
1116 (void) fclose(dout);
1117 timersub(&finish, &start, &td);
1118 tdp = &td;
1119 data = -1;
1120 pdata = -1;
1121 done:
1122 if (log)
1123 logcmd("get", byte_count, name, NULL, tdp, NULL);
1124 closerv = (*closefunc)(fin);
1125 if (sendrv == 0) {
1126 FILE *err;
1127 struct stat sb;
1128
1129 if (!isls && argv != NULL && closerv != 0) {
1130 lreply(226,
1131 "Command returned an exit status of %d",
1132 closerv);
1133 if (isconversion)
1134 syslog(LOG_INFO,
1135 "retrieve command: '%s' returned %d",
1136 argv[0], closerv);
1137 }
1138 if (!isls && argv != NULL && stderrfd != -1 &&
1139 (fstat(stderrfd, &sb) == 0) && sb.st_size > 0 &&
1140 ((err = fdopen(stderrfd, "r")) != NULL)) {
1141 char *cp, line[LINE_MAX];
1142
1143 lreply(226, "Command error messages:");
1144 rewind(err);
1145 while (fgets(line, sizeof(line), err) != NULL) {
1146 if ((cp = strchr(line, '\n')) != NULL)
1147 *cp = '\0';
1148 lreply(0, " %s", line);
1149 }
1150 (void) fflush(stdout);
1151 (void) fclose(err);
1152 /* a reply(226,) must follow */
1153 }
1154 reply(226, "Transfer complete.");
1155 }
1156 cleanupretrieve:
1157 if (stderrfd != -1)
1158 (void)close(stderrfd);
1159 if (isconversion)
1160 free(argv);
1161 }
1162
1163 void
1164 store(name, mode, unique)
1165 const char *name, *mode;
1166 int unique;
1167 {
1168 FILE *fout, *din;
1169 struct stat st;
1170 int (*closefunc) __P((FILE *));
1171 struct timeval start, finish, td, *tdp;
1172 char *desc;
1173
1174 desc = (*mode == 'w') ? "put" : "append";
1175 if (unique && stat(name, &st) == 0 &&
1176 (name = gunique(name)) == NULL) {
1177 logcmd(desc, -1, name, NULL, NULL, "cannot create unique file");
1178 return;
1179 }
1180
1181 if (restart_point)
1182 mode = "r+";
1183 fout = fopen(name, mode);
1184 closefunc = fclose;
1185 tdp = NULL;
1186 if (fout == NULL) {
1187 perror_reply(553, name);
1188 logcmd(desc, -1, name, NULL, NULL, strerror(errno));
1189 return;
1190 }
1191 byte_count = -1;
1192 if (restart_point) {
1193 if (type == TYPE_A) {
1194 off_t i;
1195 int c;
1196
1197 for (i = 0; i < restart_point; i++) {
1198 if ((c=getc(fout)) == EOF) {
1199 perror_reply(550, name);
1200 goto done;
1201 }
1202 if (c == '\n')
1203 i++;
1204 }
1205 /*
1206 * We must do this seek to "current" position
1207 * because we are changing from reading to
1208 * writing.
1209 */
1210 if (fseek(fout, 0L, SEEK_CUR) < 0) {
1211 perror_reply(550, name);
1212 goto done;
1213 }
1214 } else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1215 perror_reply(550, name);
1216 goto done;
1217 }
1218 }
1219 din = dataconn(name, (off_t)-1, "r");
1220 if (din == NULL)
1221 goto done;
1222 (void)gettimeofday(&start, NULL);
1223 if (receive_data(din, fout) == 0) {
1224 if (unique)
1225 reply(226, "Transfer complete (unique file name:%s).",
1226 name);
1227 else
1228 reply(226, "Transfer complete.");
1229 }
1230 (void)gettimeofday(&finish, NULL);
1231 (void) fclose(din);
1232 timersub(&finish, &start, &td);
1233 tdp = &td;
1234 data = -1;
1235 pdata = -1;
1236 done:
1237 logcmd(desc, byte_count, name, NULL, tdp, NULL);
1238 (*closefunc)(fout);
1239 }
1240
1241 static FILE *
1242 getdatasock(mode)
1243 const char *mode;
1244 {
1245 int on = 1, s, t, tries;
1246
1247 if (data >= 0)
1248 return (fdopen(data, mode));
1249 (void) seteuid((uid_t)0);
1250 s = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
1251 if (s < 0)
1252 goto bad;
1253 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
1254 (char *) &on, sizeof(on)) < 0)
1255 goto bad;
1256 if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
1257 (char *) &on, sizeof(on)) < 0)
1258 goto bad;
1259 /* anchor socket to avoid multi-homing problems */
1260 data_source = ctrl_addr;
1261 data_source.su_port = htons(20); /* ftp-data port */
1262 for (tries = 1; ; tries++) {
1263 if (bind(s, (struct sockaddr *)&data_source,
1264 data_source.su_len) >= 0)
1265 break;
1266 if (errno != EADDRINUSE || tries > 10)
1267 goto bad;
1268 sleep(tries);
1269 }
1270 (void) seteuid((uid_t)pw->pw_uid);
1271 #ifdef IP_TOS
1272 if (!mapped && ctrl_addr.su_family == AF_INET) {
1273 on = IPTOS_THROUGHPUT;
1274 if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on,
1275 sizeof(int)) < 0)
1276 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
1277 }
1278 #endif
1279 return (fdopen(s, mode));
1280 bad:
1281 /* Return the real value of errno (close may change it) */
1282 t = errno;
1283 (void) seteuid((uid_t)pw->pw_uid);
1284 (void) close(s);
1285 errno = t;
1286 return (NULL);
1287 }
1288
1289 static FILE *
1290 dataconn(name, size, mode)
1291 const char *name;
1292 off_t size;
1293 const char *mode;
1294 {
1295 char sizebuf[32];
1296 FILE *file;
1297 int retry = 0, tos, keepalive;
1298
1299 file_size = size;
1300 byte_count = 0;
1301 if (size != (off_t) -1)
1302 (void)snprintf(sizebuf, sizeof(sizebuf), " (%qd byte%s)",
1303 (qdfmt_t)size, PLURAL(size));
1304 else
1305 sizebuf[0] = '\0';
1306 if (pdata >= 0) {
1307 union sockunion from;
1308 int s, fromlen = sizeof(from);
1309
1310 (void) alarm(curclass.timeout);
1311 s = accept(pdata, (struct sockaddr *)&from, &fromlen);
1312 (void) alarm(0);
1313 if (s < 0) {
1314 reply(425, "Can't open data connection.");
1315 (void) close(pdata);
1316 pdata = -1;
1317 return (NULL);
1318 }
1319 (void) close(pdata);
1320 pdata = s;
1321 switch (from.su_family) {
1322 case AF_INET:
1323 #ifdef IP_TOS
1324 if (!mapped) {
1325 tos = IPTOS_THROUGHPUT;
1326 (void) setsockopt(s, IPPROTO_IP, IP_TOS,
1327 (char *)&tos, sizeof(int));
1328 }
1329 break;
1330 #endif
1331 }
1332 /* Set keepalives on the socket to detect dropped conns. */
1333 #ifdef SO_KEEPALIVE
1334 keepalive = 1;
1335 (void) setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
1336 (char *)&keepalive, sizeof(int));
1337 #endif
1338 reply(150, "Opening %s mode data connection for '%s'%s.",
1339 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1340 return (fdopen(pdata, mode));
1341 }
1342 if (data >= 0) {
1343 reply(125, "Using existing data connection for '%s'%s.",
1344 name, sizebuf);
1345 usedefault = 1;
1346 return (fdopen(data, mode));
1347 }
1348 if (usedefault)
1349 data_dest = his_addr;
1350 usedefault = 1;
1351 file = getdatasock(mode);
1352 if (file == NULL) {
1353 char hbuf[INET6_ADDRSTRLEN];
1354 char pbuf[10];
1355 getnameinfo((struct sockaddr *)&data_source, data_source.su_len,
1356 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf),
1357 NI_NUMERICHOST | NI_NUMERICSERV);
1358 reply(425, "Can't create data socket (%s,%s): %s.",
1359 hbuf, pbuf, strerror(errno));
1360 return (NULL);
1361 }
1362 data = fileno(file);
1363 while (connect(data, (struct sockaddr *)&data_dest,
1364 data_dest.su_len) < 0) {
1365 if (errno == EADDRINUSE && retry < swaitmax) {
1366 sleep((unsigned) swaitint);
1367 retry += swaitint;
1368 continue;
1369 }
1370 perror_reply(425, "Can't build data connection");
1371 (void) fclose(file);
1372 data = -1;
1373 return (NULL);
1374 }
1375 reply(150, "Opening %s mode data connection for '%s'%s.",
1376 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1377 return (file);
1378 }
1379
1380 /*
1381 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1382 * encapsulation of the data subject * to Mode, Structure, and Type.
1383 *
1384 * NB: Form isn't handled.
1385 */
1386 static int
1387 send_data(instr, outstr, blksize, isdata)
1388 FILE *instr, *outstr;
1389 off_t blksize;
1390 int isdata;
1391 {
1392 int c, filefd, netfd, rval;
1393 char *buf;
1394
1395 transflag = 1;
1396 rval = -1;
1397 buf = NULL;
1398 if (setjmp(urgcatch))
1399 goto cleanup_send_data;
1400
1401 switch (type) {
1402
1403 case TYPE_A:
1404 /* XXXX: rate limit ascii send (get) */
1405 (void) alarm(curclass.timeout);
1406 while ((c = getc(instr)) != EOF) {
1407 byte_count++;
1408 if (c == '\n') {
1409 if (ferror(outstr))
1410 goto data_err;
1411 (void) putc('\r', outstr);
1412 if (isdata) {
1413 total_data_out++;
1414 total_data++;
1415 }
1416 total_bytes_out++;
1417 total_bytes++;
1418 }
1419 (void) putc(c, outstr);
1420 if (isdata) {
1421 total_data_out++;
1422 total_data++;
1423 }
1424 total_bytes_out++;
1425 total_bytes++;
1426 if ((byte_count % 4096) == 0)
1427 (void) alarm(curclass.timeout);
1428 }
1429 (void) alarm(0);
1430 fflush(outstr);
1431 if (ferror(instr))
1432 goto file_err;
1433 if (ferror(outstr))
1434 goto data_err;
1435 rval = 0;
1436 goto cleanup_send_data;
1437
1438 case TYPE_I:
1439 case TYPE_L:
1440 if ((buf = malloc((size_t)blksize)) == NULL) {
1441 perror_reply(451, "Local resource failure: malloc");
1442 goto cleanup_send_data;
1443 }
1444 filefd = fileno(instr);
1445 netfd = fileno(outstr);
1446 (void) alarm(curclass.timeout);
1447 if (curclass.rateget) {
1448 while (1) {
1449 int d;
1450 struct timeval then, now, td;
1451 off_t bufrem;
1452 char *bufp;
1453
1454 (void)gettimeofday(&then, NULL);
1455 errno = c = d = 0;
1456 bufrem = curclass.rateget;
1457 while (bufrem > 0) {
1458 if ((c = read(filefd, buf,
1459 MIN(blksize, bufrem))) <= 0)
1460 goto senddone;
1461 (void) alarm(curclass.timeout);
1462 bufrem -= c;
1463 byte_count += c;
1464 if (isdata) {
1465 total_data_out += c;
1466 total_data += c;
1467 }
1468 total_bytes_out += c;
1469 total_bytes += c;
1470 for (bufp = buf; c > 0;
1471 c -= d, bufp += d)
1472 if ((d =
1473 write(netfd, bufp, c)) <= 0)
1474 break;
1475 if (d < 0)
1476 goto data_err;
1477 }
1478 (void)gettimeofday(&now, NULL);
1479 timersub(&now, &then, &td);
1480 if (td.tv_sec > 0)
1481 break;
1482 usleep(1000000 - td.tv_usec);
1483 }
1484 } else {
1485 while ((c = read(filefd, buf, (size_t)blksize)) > 0) {
1486 if (write(netfd, buf, c) != c)
1487 goto data_err;
1488 (void) alarm(curclass.timeout);
1489 byte_count += c;
1490 if (isdata) {
1491 total_data_out += c;
1492 total_data += c;
1493 }
1494 total_bytes_out += c;
1495 total_bytes += c;
1496 }
1497 }
1498 senddone:
1499 if (c < 0)
1500 goto file_err;
1501 rval = 0;
1502 goto cleanup_send_data;
1503
1504 default:
1505 reply(550, "Unimplemented TYPE %d in send_data", type);
1506 goto cleanup_send_data;
1507 }
1508
1509 data_err:
1510 (void) alarm(0);
1511 perror_reply(426, "Data connection");
1512 goto cleanup_send_data;
1513
1514 file_err:
1515 (void) alarm(0);
1516 perror_reply(551, "Error on input file");
1517 /* FALLTHROUGH */
1518
1519 cleanup_send_data:
1520 (void) alarm(0);
1521 transflag = 0;
1522 if (buf)
1523 free(buf);
1524 if (isdata) {
1525 total_files_out++;
1526 total_files++;
1527 }
1528 total_xfers_out++;
1529 total_xfers++;
1530 return (rval);
1531 }
1532
1533 /*
1534 * Transfer data from peer to "outstr" using the appropriate encapulation of
1535 * the data subject to Mode, Structure, and Type.
1536 *
1537 * N.B.: Form isn't handled.
1538 */
1539 static int
1540 receive_data(instr, outstr)
1541 FILE *instr, *outstr;
1542 {
1543 int c, bare_lfs, netfd, filefd, rval;
1544 char buf[BUFSIZ];
1545 #ifdef __GNUC__
1546 (void) &bare_lfs;
1547 #endif
1548
1549 bare_lfs = 0;
1550 transflag = 1;
1551 rval = -1;
1552 if (setjmp(urgcatch))
1553 goto cleanup_recv_data;
1554
1555 switch (type) {
1556
1557 case TYPE_I:
1558 case TYPE_L:
1559 netfd = fileno(instr);
1560 filefd = fileno(outstr);
1561 (void) alarm(curclass.timeout);
1562 if (curclass.rateput) {
1563 while (1) {
1564 int d;
1565 struct timeval then, now, td;
1566 off_t bufrem;
1567
1568 (void)gettimeofday(&then, NULL);
1569 errno = c = d = 0;
1570 for (bufrem = curclass.rateput; bufrem > 0; ) {
1571 if ((c = read(netfd, buf,
1572 MIN(sizeof(buf), bufrem))) <= 0)
1573 goto recvdone;
1574 if ((d = write(filefd, buf, c)) != c)
1575 goto recvdone;
1576 (void) alarm(curclass.timeout);
1577 bufrem -= c;
1578 byte_count += c;
1579 total_data_in += c;
1580 total_data += c;
1581 total_bytes_in += c;
1582 total_bytes += c;
1583 }
1584 (void)gettimeofday(&now, NULL);
1585 timersub(&now, &then, &td);
1586 if (td.tv_sec > 0)
1587 break;
1588 usleep(1000000 - td.tv_usec);
1589 }
1590 } else {
1591 while ((c = read(netfd, buf, sizeof(buf))) > 0) {
1592 if (write(filefd, buf, c) != c)
1593 goto file_err;
1594 (void) alarm(curclass.timeout);
1595 byte_count += c;
1596 total_data_in += c;
1597 total_data += c;
1598 total_bytes_in += c;
1599 total_bytes += c;
1600 }
1601 }
1602 recvdone:
1603 if (c < 0)
1604 goto data_err;
1605 rval = 0;
1606 goto cleanup_recv_data;
1607
1608 case TYPE_E:
1609 reply(553, "TYPE E not implemented.");
1610 goto cleanup_recv_data;
1611
1612 case TYPE_A:
1613 (void) alarm(curclass.timeout);
1614 /* XXXX: rate limit ascii receive (put) */
1615 while ((c = getc(instr)) != EOF) {
1616 byte_count++;
1617 total_data_in++;
1618 total_data++;
1619 total_bytes_in++;
1620 total_bytes++;
1621 if ((byte_count % 4096) == 0)
1622 (void) alarm(curclass.timeout);
1623 if (c == '\n')
1624 bare_lfs++;
1625 while (c == '\r') {
1626 if (ferror(outstr))
1627 goto data_err;
1628 if ((c = getc(instr)) != '\n') {
1629 byte_count++;
1630 total_data_in++;
1631 total_data++;
1632 total_bytes_in++;
1633 total_bytes++;
1634 if ((byte_count % 4096) == 0)
1635 (void) alarm(curclass.timeout);
1636 (void) putc ('\r', outstr);
1637 if (c == '\0' || c == EOF)
1638 goto contin2;
1639 }
1640 }
1641 (void) putc(c, outstr);
1642 contin2: ;
1643 }
1644 (void) alarm(0);
1645 fflush(outstr);
1646 if (ferror(instr))
1647 goto data_err;
1648 if (ferror(outstr))
1649 goto file_err;
1650 if (bare_lfs) {
1651 lreply(226,
1652 "WARNING! %d bare linefeeds received in ASCII mode",
1653 bare_lfs);
1654 lreply(0, "File may not have transferred correctly.");
1655 }
1656 rval = 0;
1657 goto cleanup_recv_data;
1658
1659 default:
1660 reply(550, "Unimplemented TYPE %d in receive_data", type);
1661 goto cleanup_recv_data;
1662 }
1663
1664 data_err:
1665 (void) alarm(0);
1666 perror_reply(426, "Data Connection");
1667 goto cleanup_recv_data;
1668
1669 file_err:
1670 (void) alarm(0);
1671 perror_reply(452, "Error writing file");
1672 goto cleanup_recv_data;
1673
1674 cleanup_recv_data:
1675 (void) alarm(0);
1676 transflag = 0;
1677 total_files_in++;
1678 total_files++;
1679 total_xfers_in++;
1680 total_xfers++;
1681 return (rval);
1682 }
1683
1684 void
1685 statfilecmd(filename)
1686 const char *filename;
1687 {
1688 FILE *fin;
1689 int c;
1690 char *argv[] = { INTERNAL_LS, "-lgA", "", NULL };
1691
1692 argv[2] = (char *)filename;
1693 fin = ftpd_popen(argv, "r", STDOUT_FILENO);
1694 lreply(211, "status of %s:", filename);
1695 while ((c = getc(fin)) != EOF) {
1696 if (c == '\n') {
1697 if (ferror(stdout)){
1698 perror_reply(421, "control connection");
1699 (void) ftpd_pclose(fin);
1700 dologout(1);
1701 /* NOTREACHED */
1702 }
1703 if (ferror(fin)) {
1704 perror_reply(551, filename);
1705 (void) ftpd_pclose(fin);
1706 return;
1707 }
1708 (void) putchar('\r');
1709 total_bytes++;
1710 total_bytes_out++;
1711 }
1712 (void) putchar(c);
1713 total_bytes++;
1714 total_bytes_out++;
1715 }
1716 (void) ftpd_pclose(fin);
1717 reply(211, "End of Status");
1718 }
1719
1720 void
1721 statcmd()
1722 {
1723 union sockunion *su = NULL;
1724 static char ntop_buf[INET6_ADDRSTRLEN];
1725 u_char *a, *p;
1726 int ispassive;
1727 off_t b, otbi, otbo, otb;
1728
1729 a = p = (u_char *)NULL;
1730
1731 lreply(211, "%s FTP server status:", hostname);
1732 lreply(0, "%s", version);
1733 ntop_buf[0] = '\0';
1734 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1735 ntop_buf, sizeof(ntop_buf), NULL, 0, NI_NUMERICHOST)
1736 && strcmp(remotehost, ntop_buf) != 0) {
1737 lreply(0, "Connected to %s (%s)", remotehost, ntop_buf);
1738 } else
1739 lreply(0, "Connected to %s", remotehost);
1740 if (logged_in) {
1741 if (curclass.type == CLASS_GUEST)
1742 lreply(0, "Logged in anonymously");
1743 else
1744 lreply(0, "Logged in as %s%s", pw->pw_name,
1745 curclass.type == CLASS_CHROOT ? " (chroot)" : "");
1746 } else if (askpasswd)
1747 lreply(0, "Waiting for password");
1748 else
1749 lreply(0, "Waiting for user name");
1750 b = printf(" TYPE: %s", typenames[type]);
1751 total_bytes += b;
1752 total_bytes_out += b;
1753 if (type == TYPE_A || type == TYPE_E) {
1754 b = printf(", FORM: %s", formnames[form]);
1755 total_bytes += b;
1756 total_bytes_out += b;
1757 }
1758 if (type == TYPE_L) {
1759 #if NBBY == 8
1760 b = printf(" %d", NBBY);
1761 #else
1762 /* XXX: `bytesize' needs to be defined in this case */
1763 b = printf(" %d", bytesize);
1764 #endif
1765 total_bytes += b;
1766 total_bytes_out += b;
1767 }
1768 b = printf("; STRUcture: %s; transfer MODE: %s\r\n",
1769 strunames[stru], modenames[mode]);
1770 total_bytes += b;
1771 total_bytes_out += b;
1772 ispassive = 0;
1773 if (data != -1) {
1774 lreply(0, "Data connection open");
1775 su = NULL;
1776 } else if (pdata != -1) {
1777 b = printf(" in Passive mode");
1778 total_bytes += b;
1779 total_bytes_out += b;
1780 su = (union sockunion *)&pasv_addr;
1781 ispassive = 1;
1782 goto printaddr;
1783 } else if (usedefault == 0) {
1784 if (epsvall) {
1785 b = printf("211- EPSV only mode (EPSV ALL )\r\n");
1786 total_bytes += b;
1787 total_bytes_out += b;
1788 goto epsvonly;
1789 }
1790 b = printf("211- %s",
1791 (data_dest.su_family == AF_INET) ? "PORT" : "LPRT");
1792 total_bytes += b;
1793 total_bytes_out += b;
1794 su = (union sockunion *)&data_dest;
1795 printaddr:
1796 /* PASV/PORT */
1797 if (su->su_family == AF_INET) {
1798 if (ispassive)
1799 b = printf("211- PASV ");
1800 else
1801 b = printf("211- PORT ");
1802 a = (u_char *) &su->su_sin.sin_addr;
1803 p = (u_char *) &su->su_sin.sin_port;
1804 #define UC(b) (((int) b) & 0xff)
1805 b += printf("(%d,%d,%d,%d,%d,%d)\r\n",
1806 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
1807 UC(p[0]), UC(p[1]));
1808 total_bytes += b;
1809 total_bytes_out += b;
1810 }
1811
1812 /* LPSV/LPRT */
1813 {
1814 int alen, af, i;
1815
1816 alen = 0;
1817 switch (su->su_family) {
1818 case AF_INET:
1819 a = (u_char *) &su->su_sin.sin_addr;
1820 p = (u_char *) &su->su_sin.sin_port;
1821 alen = sizeof(su->su_sin.sin_addr);
1822 af = 4;
1823 break;
1824 case AF_INET6:
1825 a = (u_char *) &su->su_sin6.sin6_addr;
1826 p = (u_char *) &su->su_sin6.sin6_port;
1827 alen = sizeof(su->su_sin6.sin6_addr);
1828 af = 6;
1829 break;
1830 default:
1831 af = 0;
1832 break;
1833 }
1834 if (af) {
1835 if (ispassive)
1836 b = printf("211- LPSV ");
1837 else
1838 b = printf("211- LPRT ");
1839 printf("(%d,%d", af, alen);
1840 for (i = 0; i < alen; i++)
1841 b += printf("%d,", UC(a[alen]));
1842 b += printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
1843 total_bytes += b;
1844 total_bytes_out += b;
1845 #undef UC
1846 }
1847 }
1848
1849 /* EPRT/EPSV */
1850 epsvonly:;
1851 {
1852 int af;
1853
1854 switch (su->su_family) {
1855 case AF_INET:
1856 af = 1;
1857 break;
1858 case AF_INET6:
1859 af = 2;
1860 break;
1861 default:
1862 af = 0;
1863 break;
1864 }
1865 if (af) {
1866 if (getnameinfo((struct sockaddr *)su, su->su_len,
1867 ntop_buf, sizeof(ntop_buf), NULL, 0,
1868 NI_NUMERICHOST) == 0) {
1869 if (ispassive)
1870 b = printf("211 - EPSV ");
1871 else
1872 b = printf("211 - EPRT ");
1873 b += printf("(|%d|%s|%d|)\r\n",
1874 af, ntop_buf, ntohs(su->su_port));
1875 total_bytes += b;
1876 total_bytes_out += b;
1877 }
1878 }
1879 }
1880 } else
1881 lreply(0, "No data connection");
1882
1883 if (logged_in) {
1884 lreply(0, "Data sent: %qd byte%s in %qd file%s",
1885 (qdfmt_t)total_data_out, PLURAL(total_data_out),
1886 (qdfmt_t)total_files_out, PLURAL(total_files_out));
1887 lreply(0, "Data received: %qd byte%s in %qd file%s",
1888 (qdfmt_t)total_data_in, PLURAL(total_data_in),
1889 (qdfmt_t)total_files_in, PLURAL(total_files_in));
1890 lreply(0, "Total data: %qd byte%s in %qd file%s",
1891 (qdfmt_t)total_data, PLURAL(total_data),
1892 (qdfmt_t)total_files, PLURAL(total_files));
1893 }
1894 otbi = total_bytes_in;
1895 otbo = total_bytes_out;
1896 otb = total_bytes;
1897 lreply(0, "Traffic sent: %qd byte%s in %qd transfer%s",
1898 (qdfmt_t)otbo, PLURAL(otbo),
1899 (qdfmt_t)total_xfers_out, PLURAL(total_xfers_out));
1900 lreply(0, "Traffic received: %qd byte%s in %qd transfer%s",
1901 (qdfmt_t)otbi, PLURAL(otbi),
1902 (qdfmt_t)total_xfers_in, PLURAL(total_xfers_in));
1903 lreply(0, "Total traffic: %qd byte%s in %qd transfer%s",
1904 (qdfmt_t)otb, PLURAL(otb),
1905 (qdfmt_t)total_xfers, PLURAL(total_xfers));
1906
1907 if (logged_in) {
1908 struct ftpconv *cp;
1909
1910 lreply(0, "");
1911 lreply(0, "Class: %s, type: %s",
1912 curclass.classname, CURCLASSTYPE);
1913 lreply(0, "Check PORT/LPRT commands: %sabled",
1914 curclass.checkportcmd ? "en" : "dis");
1915 if (curclass.display != NULL)
1916 lreply(0, "Display file: %s", curclass.display);
1917 if (curclass.notify != NULL)
1918 lreply(0, "Notify fileglob: %s", curclass.notify);
1919 lreply(0, "Idle timeout: %d, maximum timeout: %d",
1920 curclass.timeout, curclass.maxtimeout);
1921 lreply(0, "Current connections: %d", connections);
1922 if (curclass.limit == -1)
1923 lreply(0, "Maximum connections: unlimited");
1924 else
1925 lreply(0, "Maximum connections: %d", curclass.limit);
1926 if (curclass.limitfile)
1927 lreply(0, "Connection limit exceeded file: %s",
1928 curclass.limitfile);
1929 if (curclass.motd != NULL)
1930 lreply(0, "MotD file: %s", curclass.motd);
1931 lreply(0,
1932 "Modify commands (CHMOD, DELE, MKD, RMD, RNFR, UMASK): %sabled",
1933 curclass.modify ? "en" : "dis");
1934 lreply(0,
1935 "Upload commands (APPE, STOR, STOU): %sabled",
1936 curclass.upload ? "en" : "dis");
1937 if (curclass.rateget)
1938 lreply(0, "Rate get limit: %d bytes/sec",
1939 curclass.rateget);
1940 else
1941 lreply(0, "Rate get limit: disabled");
1942 if (curclass.rateput)
1943 lreply(0, "Rate put limit: %d bytes/sec",
1944 curclass.rateput);
1945 else
1946 lreply(0, "Rate put limit: disabled");
1947 lreply(0, "Umask: %.04o", curclass.umask);
1948 for (cp = curclass.conversions; cp != NULL; cp=cp->next) {
1949 if (cp->suffix == NULL || cp->types == NULL ||
1950 cp->command == NULL)
1951 continue;
1952 lreply(0,
1953 "Conversion: %s [%s] disable: %s, command: %s",
1954 cp->suffix, cp->types, cp->disable, cp->command);
1955 }
1956 }
1957
1958 reply(211, "End of status");
1959 }
1960
1961 void
1962 fatal(s)
1963 const char *s;
1964 {
1965
1966 reply(451, "Error in server: %s\n", s);
1967 reply(221, "Closing connection due to server error.");
1968 dologout(0);
1969 /* NOTREACHED */
1970 }
1971
1972 void
1973 #ifdef __STDC__
1974 reply(int n, const char *fmt, ...)
1975 #else
1976 reply(n, fmt, va_alist)
1977 int n;
1978 char *fmt;
1979 va_dcl
1980 #endif
1981 {
1982 off_t b;
1983 va_list ap;
1984 #ifdef __STDC__
1985 va_start(ap, fmt);
1986 #else
1987 va_start(ap);
1988 #endif
1989 b = 0;
1990 b += printf("%d ", n);
1991 b += vprintf(fmt, ap);
1992 b += printf("\r\n");
1993 total_bytes += b;
1994 total_bytes_out += b;
1995 (void)fflush(stdout);
1996 if (debug) {
1997 syslog(LOG_DEBUG, "<--- %d ", n);
1998 vsyslog(LOG_DEBUG, fmt, ap);
1999 }
2000 }
2001
2002 void
2003 #ifdef __STDC__
2004 lreply(int n, const char *fmt, ...)
2005 #else
2006 lreply(n, fmt, va_alist)
2007 int n;
2008 char *fmt;
2009 va_dcl
2010 #endif
2011 {
2012 off_t b;
2013 va_list ap;
2014 #ifdef __STDC__
2015 va_start(ap, fmt);
2016 #else
2017 va_start(ap);
2018 #endif
2019 b = 0;
2020 switch (n) {
2021 case 0:
2022 b += printf(" ");
2023 case -1:
2024 break;
2025 default:
2026 b += printf("%d-", n);
2027 break;
2028 }
2029 b += vprintf(fmt, ap);
2030 b += printf("\r\n");
2031 total_bytes += b;
2032 total_bytes_out += b;
2033 (void)fflush(stdout);
2034 if (debug) {
2035 syslog(LOG_DEBUG, "<--- %d- ", n);
2036 vsyslog(LOG_DEBUG, fmt, ap);
2037 }
2038 }
2039
2040 static void
2041 ack(s)
2042 const char *s;
2043 {
2044
2045 reply(250, "%s command successful.", s);
2046 }
2047
2048 void
2049 delete(name)
2050 const char *name;
2051 {
2052 char *p = NULL;
2053
2054 if (remove(name) < 0) {
2055 p = strerror(errno);
2056 perror_reply(550, name);
2057 } else
2058 ack("DELE");
2059 logcmd("delete", -1, name, NULL, NULL, p);
2060 }
2061
2062 void
2063 cwd(path)
2064 const char *path;
2065 {
2066
2067 if (chdir(path) < 0)
2068 perror_reply(550, path);
2069 else {
2070 show_chdir_messages(250);
2071 ack("CWD");
2072 }
2073 }
2074
2075 static void
2076 replydirname(name, message)
2077 const char *name, *message;
2078 {
2079 char npath[MAXPATHLEN];
2080 int i;
2081
2082 for (i = 0; *name != '\0' && i < sizeof(npath) - 1; i++, name++) {
2083 npath[i] = *name;
2084 if (*name == '"')
2085 npath[++i] = '"';
2086 }
2087 npath[i] = '\0';
2088 reply(257, "\"%s\" %s", npath, message);
2089 }
2090
2091 void
2092 makedir(name)
2093 const char *name;
2094 {
2095 char *p = NULL;
2096
2097 if (mkdir(name, 0777) < 0) {
2098 p = strerror(errno);
2099 perror_reply(550, name);
2100 } else
2101 replydirname(name, "directory created.");
2102 logcmd("mkdir", -1, name, NULL, NULL, p);
2103 }
2104
2105 void
2106 removedir(name)
2107 const char *name;
2108 {
2109 char *p = NULL;
2110
2111 if (rmdir(name) < 0) {
2112 p = strerror(errno);
2113 perror_reply(550, name);
2114 } else
2115 ack("RMD");
2116 logcmd("rmdir", -1, name, NULL, NULL, p);
2117 }
2118
2119 void
2120 pwd()
2121 {
2122 char path[MAXPATHLEN];
2123
2124 if (getcwd(path, sizeof(path) - 1) == NULL)
2125 reply(550, "Can't get the current directory: %s.",
2126 strerror(errno));
2127 else
2128 replydirname(path, "is the current directory.");
2129 }
2130
2131 char *
2132 renamefrom(name)
2133 char *name;
2134 {
2135 struct stat st;
2136
2137 if (stat(name, &st) < 0) {
2138 perror_reply(550, name);
2139 return (NULL);
2140 }
2141 reply(350, "File exists, ready for destination name");
2142 return (xstrdup(name));
2143 }
2144
2145 void
2146 renamecmd(from, to)
2147 const char *from, *to;
2148 {
2149 char *p = NULL;
2150
2151 if (rename(from, to) < 0) {
2152 p = strerror(errno);
2153 perror_reply(550, "rename");
2154 } else
2155 ack("RNTO");
2156 logcmd("rename", -1, from, to, NULL, p);
2157 }
2158
2159 static void
2160 dolog(who)
2161 struct sockaddr *who;
2162 {
2163 getnameinfo(who, who->sa_len, remotehost, sizeof(remotehost), NULL,0,0);
2164 #ifdef HASSETPROCTITLE
2165 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
2166 setproctitle(proctitle);
2167 #endif /* HASSETPROCTITLE */
2168 if (logging)
2169 syslog(LOG_INFO, "connection from %s to %s",
2170 remotehost, hostname);
2171 }
2172
2173 /*
2174 * Record logout in wtmp file
2175 * and exit with supplied status.
2176 */
2177 void
2178 dologout(status)
2179 int status;
2180 {
2181 /*
2182 * Prevent reception of SIGURG from resulting in a resumption
2183 * back to the main program loop.
2184 */
2185 transflag = 0;
2186
2187 if (logged_in) {
2188 (void) seteuid((uid_t)0);
2189 logwtmp(ttyline, "", "");
2190 if (doutmp)
2191 logout(utmp.ut_line);
2192 #ifdef KERBEROS
2193 if (!notickets && krbtkfile_env)
2194 unlink(krbtkfile_env);
2195 #endif
2196 }
2197 /* beware of flushing buffers after a SIGPIPE */
2198 _exit(status);
2199 }
2200
2201 static void
2202 myoob(signo)
2203 int signo;
2204 {
2205 char *cp;
2206
2207 /* only process if transfer occurring */
2208 if (!transflag)
2209 return;
2210 cp = tmpline;
2211 if (getline(cp, 7, stdin) == NULL) {
2212 reply(221, "You could at least say goodbye.");
2213 dologout(0);
2214 }
2215 if (strcasecmp(cp, "ABOR\r\n") == 0) {
2216 tmpline[0] = '\0';
2217 reply(426, "Transfer aborted. Data connection closed.");
2218 reply(226, "Abort successful");
2219 longjmp(urgcatch, 1);
2220 }
2221 if (strcasecmp(cp, "STAT\r\n") == 0) {
2222 tmpline[0] = '\0';
2223 if (file_size != (off_t) -1)
2224 reply(213, "Status: %qd of %qd byte%s transferred",
2225 (qdfmt_t)byte_count, (qdfmt_t)file_size,
2226 PLURAL(byte_count));
2227 else
2228 reply(213, "Status: %qd byte%s transferred",
2229 (qdfmt_t)byte_count, PLURAL(byte_count));
2230 }
2231 }
2232
2233 static int
2234 bind_pasv_addr()
2235 {
2236 static int passiveport;
2237 int port, len;
2238
2239 len = pasv_addr.su_len;
2240 if (curclass.portmin == 0 && curclass.portmax == 0) {
2241 pasv_addr.su_port = 0;
2242 return (bind(pdata, (struct sockaddr *)&pasv_addr, len));
2243 }
2244
2245 if (passiveport == 0) {
2246 srand(getpid());
2247 passiveport = rand() % (curclass.portmax - curclass.portmin)
2248 + curclass.portmin;
2249 }
2250
2251 port = passiveport;
2252 while (1) {
2253 port++;
2254 if (port > curclass.portmax)
2255 port = curclass.portmin;
2256 else if (port == passiveport) {
2257 errno = EAGAIN;
2258 return (-1);
2259 }
2260 pasv_addr.su_port = htons(port);
2261 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) == 0)
2262 break;
2263 if (errno != EADDRINUSE)
2264 return (-1);
2265 }
2266 passiveport = port;
2267 return (0);
2268 }
2269
2270 /*
2271 * Note: a response of 425 is not mentioned as a possible response to
2272 * the PASV command in RFC959. However, it has been blessed as
2273 * a legitimate response by Jon Postel in a telephone conversation
2274 * with Rick Adams on 25 Jan 89.
2275 */
2276 void
2277 passive()
2278 {
2279 int len;
2280 char *p, *a;
2281
2282 if (pdata >= 0)
2283 close(pdata);
2284 pdata = socket(AF_INET, SOCK_STREAM, 0);
2285 if (pdata < 0 || !logged_in) {
2286 perror_reply(425, "Can't open passive connection");
2287 return;
2288 }
2289 pasv_addr = ctrl_addr;
2290
2291 if (bind_pasv_addr() < 0)
2292 goto pasv_error;
2293 len = pasv_addr.su_len;
2294 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2295 goto pasv_error;
2296 if (listen(pdata, 1) < 0)
2297 goto pasv_error;
2298 a = (char *) &pasv_addr.su_sin.sin_addr;
2299 p = (char *) &pasv_addr.su_port;
2300
2301 #define UC(b) (((int) b) & 0xff)
2302
2303 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2304 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2305 return;
2306
2307 pasv_error:
2308 (void) close(pdata);
2309 pdata = -1;
2310 perror_reply(425, "Can't open passive connection");
2311 return;
2312 }
2313
2314 /*
2315 * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)
2316 * 229 Entering Extended Passive Mode (|||port|)
2317 */
2318 void
2319 long_passive(char *cmd, int pf)
2320 {
2321 int len;
2322 char *p, *a;
2323
2324 if (!logged_in) {
2325 syslog(LOG_NOTICE, "long passive but not logged in");
2326 reply(503, "Login with USER first.");
2327 return;
2328 }
2329
2330 if (pf != PF_UNSPEC) {
2331 if (ctrl_addr.su_family != pf) {
2332 switch (ctrl_addr.su_family) {
2333 case AF_INET:
2334 pf = 1;
2335 break;
2336 case AF_INET6:
2337 pf = 2;
2338 break;
2339 default:
2340 pf = 0;
2341 break;
2342 }
2343 /*
2344 * XXX
2345 * only EPRT/EPSV ready clients will understand this
2346 */
2347 if (strcmp(cmd, "EPSV") == 0 && pf) {
2348 reply(522, "Network protocol mismatch, "
2349 "use (%d)", pf);
2350 } else
2351 reply(501, "Network protocol mismatch"); /*XXX*/
2352
2353 return;
2354 }
2355 }
2356
2357 if (pdata >= 0)
2358 close(pdata);
2359 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2360 if (pdata < 0) {
2361 perror_reply(425, "Can't open passive connection");
2362 return;
2363 }
2364 pasv_addr = ctrl_addr;
2365 if (bind_pasv_addr() < 0)
2366 goto pasv_error;
2367 len = pasv_addr.su_len;
2368 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2369 goto pasv_error;
2370 if (listen(pdata, 1) < 0)
2371 goto pasv_error;
2372 p = (char *) &pasv_addr.su_port;
2373
2374 #define UC(b) (((int) b) & 0xff)
2375
2376 if (strcmp(cmd, "LPSV") == 0) {
2377 switch (pasv_addr.su_family) {
2378 case AF_INET:
2379 a = (char *) &pasv_addr.su_sin.sin_addr;
2380 reply(228, "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2381 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2382 2, UC(p[0]), UC(p[1]));
2383 return;
2384 case AF_INET6:
2385 a = (char *) &pasv_addr.su_sin6.sin6_addr;
2386 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)",
2387 6, 16,
2388 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2389 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2390 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2391 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2392 2, UC(p[0]), UC(p[1]));
2393 return;
2394 }
2395 #undef UC
2396 } else if (strcmp(cmd, "EPSV") == 0) {
2397 switch (pasv_addr.su_family) {
2398 case AF_INET:
2399 case AF_INET6:
2400 reply(229, "Entering Extended Passive Mode (|||%d|)",
2401 ntohs(pasv_addr.su_port));
2402 return;
2403 }
2404 } else {
2405 /* more proper error code? */
2406 }
2407
2408 pasv_error:
2409 (void) close(pdata);
2410 pdata = -1;
2411 perror_reply(425, "Can't open passive connection");
2412 return;
2413 }
2414
2415 /*
2416 * Generate unique name for file with basename "local".
2417 * The file named "local" is already known to exist.
2418 * Generates failure reply on error.
2419 *
2420 * XXX this function should under go changes similar to
2421 * the mktemp(3)/mkstemp(3) changes.
2422 */
2423 static char *
2424 gunique(local)
2425 const char *local;
2426 {
2427 static char new[MAXPATHLEN];
2428 struct stat st;
2429 char *cp;
2430 int count;
2431
2432 cp = strrchr(local, '/');
2433 if (cp)
2434 *cp = '\0';
2435 if (stat(cp ? local : ".", &st) < 0) {
2436 perror_reply(553, cp ? local : ".");
2437 return (NULL);
2438 }
2439 if (cp)
2440 *cp = '/';
2441 for (count = 1; count < 100; count++) {
2442 (void)snprintf(new, sizeof(new) - 1, "%s.%d", local, count);
2443 if (stat(new, &st) < 0)
2444 return (new);
2445 }
2446 reply(452, "Unique file name cannot be created.");
2447 return (NULL);
2448 }
2449
2450 /*
2451 * Format and send reply containing system error number.
2452 */
2453 void
2454 perror_reply(code, string)
2455 int code;
2456 const char *string;
2457 {
2458 int save_errno;
2459
2460 save_errno = errno;
2461 reply(code, "%s: %s.", string, strerror(errno));
2462 errno = save_errno;
2463 }
2464
2465 static char *onefile[] = {
2466 "",
2467 0
2468 };
2469
2470 void
2471 send_file_list(whichf)
2472 const char *whichf;
2473 {
2474 struct stat st;
2475 DIR *dirp = NULL;
2476 struct dirent *dir;
2477 FILE *dout = NULL;
2478 char **dirlist, *dirname, *p;
2479 int simple = 0;
2480 int freeglob = 0;
2481 glob_t gl;
2482 off_t b;
2483
2484 #ifdef __GNUC__
2485 (void) &dout;
2486 (void) &dirlist;
2487 (void) &simple;
2488 (void) &freeglob;
2489 #endif
2490
2491 p = NULL;
2492 if (strpbrk(whichf, "~{[*?") != NULL) {
2493 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
2494
2495 memset(&gl, 0, sizeof(gl));
2496 freeglob = 1;
2497 if (glob(whichf, flags, 0, &gl)) {
2498 reply(550, "not found");
2499 goto out;
2500 } else if (gl.gl_pathc == 0) {
2501 errno = ENOENT;
2502 perror_reply(550, whichf);
2503 goto out;
2504 }
2505 dirlist = gl.gl_pathv;
2506 } else {
2507 p = xstrdup(whichf);
2508 onefile[0] = p;
2509 dirlist = onefile;
2510 simple = 1;
2511 }
2512 /* XXX: } for vi sm */
2513
2514 if (setjmp(urgcatch)) {
2515 transflag = 0;
2516 goto out;
2517 }
2518 while ((dirname = *dirlist++) != NULL) {
2519 int trailingslash = 0;
2520
2521 if (stat(dirname, &st) < 0) {
2522 /*
2523 * If user typed "ls -l", etc, and the client
2524 * used NLST, do what the user meant.
2525 */
2526 /* XXX: nuke this support? */
2527 if (dirname[0] == '-' && *dirlist == NULL &&
2528 transflag == 0) {
2529 char *argv[] = { INTERNAL_LS, "", NULL };
2530
2531 argv[1] = dirname;
2532 retrieve(argv, dirname);
2533 goto out;
2534 }
2535 perror_reply(550, whichf);
2536 if (dout != NULL) {
2537 (void) fclose(dout);
2538 transflag = 0;
2539 data = -1;
2540 pdata = -1;
2541 }
2542 goto out;
2543 }
2544
2545 if (S_ISREG(st.st_mode)) {
2546 if (dout == NULL) {
2547 dout = dataconn("file list", (off_t)-1, "w");
2548 if (dout == NULL)
2549 goto out;
2550 transflag++;
2551 }
2552 b = fprintf(dout, "%s%s\n", dirname,
2553 type == TYPE_A ? "\r" : "");
2554 total_bytes += b;
2555 total_bytes_out += b;
2556 byte_count += strlen(dirname) + 1;
2557 continue;
2558 } else if (!S_ISDIR(st.st_mode))
2559 continue;
2560
2561 if (dirname[strlen(dirname) - 1] == '/')
2562 trailingslash++;
2563
2564 if ((dirp = opendir(dirname)) == NULL)
2565 continue;
2566
2567 while ((dir = readdir(dirp)) != NULL) {
2568 char nbuf[MAXPATHLEN];
2569
2570 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
2571 continue;
2572 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
2573 dir->d_namlen == 2)
2574 continue;
2575
2576 (void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
2577 trailingslash ? "" : "/", dir->d_name);
2578
2579 /*
2580 * We have to do a stat to ensure it's
2581 * not a directory or special file.
2582 */
2583 /* XXX: follow RFC959 and filter out non files ? */
2584 if (simple || (stat(nbuf, &st) == 0 &&
2585 S_ISREG(st.st_mode))) {
2586 char *p;
2587
2588 if (dout == NULL) {
2589 dout = dataconn("file list", (off_t)-1,
2590 "w");
2591 if (dout == NULL)
2592 goto out;
2593 transflag++;
2594 }
2595 p = nbuf;
2596 if (nbuf[0] == '.' && nbuf[1] == '/')
2597 p = &nbuf[2];
2598 b = fprintf(dout, "%s%s\n", p,
2599 type == TYPE_A ? "\r" : "");
2600 total_bytes += b;
2601 total_bytes_out += b;
2602 byte_count += strlen(nbuf) + 1;
2603 }
2604 }
2605 (void) closedir(dirp);
2606 }
2607
2608 if (dout == NULL)
2609 reply(550, "No files found.");
2610 else if (ferror(dout) != 0)
2611 perror_reply(550, "Data connection");
2612 else
2613 reply(226, "Transfer complete.");
2614
2615 transflag = 0;
2616 if (dout != NULL)
2617 (void) fclose(dout);
2618 data = -1;
2619 pdata = -1;
2620 out:
2621 total_xfers++;
2622 total_xfers_out++;
2623 if (p)
2624 free(p);
2625 if (freeglob)
2626 globfree(&gl);
2627 }
2628
2629 char *
2630 conffilename(s)
2631 const char *s;
2632 {
2633 static char filename[MAXPATHLEN];
2634
2635 if (*s == '/')
2636 strlcpy(filename, s, sizeof(filename));
2637 else
2638 (void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
2639 return (filename);
2640 }
2641
2642 /*
2643 * logcmd --
2644 * based on the arguments, syslog a message:
2645 * if bytes != -1 "<command> <file1> = <bytes> bytes"
2646 * else if file2 != NULL "<command> <file1> <file2>"
2647 * else "<command> <file1>"
2648 * if elapsed != NULL, append "in xxx.yyy seconds"
2649 * if error != NULL, append ": " + error
2650 */
2651
2652 void
2653 logcmd(command, bytes, file1, file2, elapsed, error)
2654 const char *command;
2655 off_t bytes;
2656 const char *file1;
2657 const char *file2;
2658 const struct timeval *elapsed;
2659 const char *error;
2660 {
2661 char buf[MAXPATHLEN * 2 + 100], realfile[MAXPATHLEN];
2662 const char *p;
2663 size_t len;
2664
2665 if (logging <=1)
2666 return;
2667
2668 if ((p = realpath(file1, realfile)) == NULL) {
2669 #if 0 /* XXX: too noisy */
2670 syslog(LOG_WARNING, "realpath `%s' failed: %s",
2671 realfile, strerror(errno));
2672 #endif
2673 p = file1;
2674 }
2675 len = snprintf(buf, sizeof(buf), "%s %s", command, p);
2676
2677 if (bytes != (off_t)-1) {
2678 len += snprintf(buf + len, sizeof(buf) - len,
2679 " = %qd byte%s", (qdfmt_t) bytes, PLURAL(bytes));
2680 } else if (file2 != NULL) {
2681 if ((p = realpath(file2, realfile)) == NULL) {
2682 #if 0 /* XXX: too noisy */
2683 syslog(LOG_WARNING, "realpath `%s' failed: %s",
2684 realfile, strerror(errno));
2685 #endif
2686 p = file2;
2687 }
2688 len += snprintf(buf + len, sizeof(buf) - len, " %s", p);
2689 }
2690
2691 if (elapsed != NULL) {
2692 len += snprintf(buf + len, sizeof(buf) - len,
2693 " in %ld.%.03d seconds", elapsed->tv_sec,
2694 (int)(elapsed->tv_usec / 1000));
2695 }
2696
2697 if (error != NULL)
2698 len += snprintf(buf + len, sizeof(buf) - len, ": %s", error);
2699
2700 syslog(LOG_INFO, "%s", buf);
2701 }
2702
2703 char *
2704 xstrdup(s)
2705 const char *s;
2706 {
2707 char *new = strdup(s);
2708
2709 if (new == NULL)
2710 fatal("Local resource failure: malloc");
2711 /* NOTREACHED */
2712 return (new);
2713 }
2714