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