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