ftpd.c revision 1.61.2.1 1 /* $NetBSD: ftpd.c,v 1.61.2.1 1999/10/01 12:08:06 he Exp $ */
2
3 /*
4 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
5 * The Regents of the University of California. 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. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36 #include <sys/cdefs.h>
37 #ifndef lint
38 __COPYRIGHT(
39 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
40 The Regents of the University of California. All rights reserved.\n");
41 #endif /* not lint */
42
43 #ifndef lint
44 #if 0
45 static char sccsid[] = "@(#)ftpd.c 8.5 (Berkeley) 4/28/95";
46 #else
47 __RCSID("$NetBSD: ftpd.c,v 1.61.2.1 1999/10/01 12:08:06 he Exp $");
48 #endif
49 #endif /* not lint */
50
51 /*
52 * FTP server.
53 */
54 #include <sys/param.h>
55 #include <sys/stat.h>
56 #include <sys/ioctl.h>
57 #include <sys/socket.h>
58 #include <sys/wait.h>
59
60 #include <netinet/in.h>
61 #include <netinet/in_systm.h>
62 #include <netinet/ip.h>
63
64 #define FTP_NAMES
65 #include <arpa/ftp.h>
66 #include <arpa/inet.h>
67 #include <arpa/telnet.h>
68
69 #include <ctype.h>
70 #include <dirent.h>
71 #include <err.h>
72 #include <errno.h>
73 #include <fcntl.h>
74 #include <fnmatch.h>
75 #include <glob.h>
76 #include <limits.h>
77 #include <netdb.h>
78 #include <pwd.h>
79 #include <setjmp.h>
80 #include <signal.h>
81 #include <stdio.h>
82 #include <stdlib.h>
83 #include <string.h>
84 #include <syslog.h>
85 #include <time.h>
86 #include <unistd.h>
87 #ifdef SKEY
88 #include <skey.h>
89 #endif
90 #ifdef KERBEROS5
91 #include <krb5.h>
92 #endif
93
94 #include "extern.h"
95 #include "pathnames.h"
96
97 #if __STDC__
98 #include <stdarg.h>
99 #else
100 #include <varargs.h>
101 #endif
102
103 #ifndef TRUE
104 #define TRUE 1
105 #define FALSE 0
106 #endif
107
108 const char version[] = "Version: 7.1.0";
109
110 struct sockaddr_in ctrl_addr;
111 struct sockaddr_in data_source;
112 struct sockaddr_in data_dest;
113 struct sockaddr_in his_addr;
114 struct sockaddr_in pasv_addr;
115
116 int data;
117 jmp_buf errcatch, urgcatch;
118 int logged_in;
119 struct passwd *pw;
120 int debug;
121 int sflag;
122 int logging;
123 int guest;
124 int dochroot;
125 int type;
126 int form;
127 int stru; /* avoid C keyword */
128 int mode;
129 int usedefault = 1; /* for data transfers */
130 int pdata = -1; /* for passive mode */
131 sig_atomic_t transflag;
132 off_t file_size;
133 off_t byte_count;
134 char tmpline[7];
135 char hostname[MAXHOSTNAMELEN+1];
136 char remotehost[MAXHOSTNAMELEN+1];
137 static char ttyline[20];
138 char *tty = ttyline; /* for klogin */
139
140 static char *anondir = NULL;
141 static char confdir[MAXPATHLEN];
142
143 #if defined(KERBEROS) || defined(KERBEROS5)
144 int notickets = 1;
145 char *krbtkfile_env = NULL;
146 #endif
147
148 /*
149 * Timeout intervals for retrying connections
150 * to hosts that don't accept PORT cmds. This
151 * is a kludge, but given the problems with TCP...
152 */
153 #define SWAITMAX 90 /* wait at most 90 seconds */
154 #define SWAITINT 5 /* interval between retries */
155
156 int swaitmax = SWAITMAX;
157 int swaitint = SWAITINT;
158
159 #ifdef HASSETPROCTITLE
160 char proctitle[BUFSIZ]; /* initial part of title */
161 #endif /* HASSETPROCTITLE */
162
163 static void ack __P((char *));
164 static void myoob __P((int));
165 static int checkuser __P((const char *, const char *, int, int));
166 static int checkaccess __P((const char *));
167 static FILE *dataconn __P((char *, off_t, char *));
168 static void dolog __P((struct sockaddr_in *));
169 static void end_login __P((void));
170 static FILE *getdatasock __P((char *));
171 static char *gunique __P((char *));
172 static void lostconn __P((int));
173 static int receive_data __P((FILE *, FILE *));
174 static void replydirname __P((const char *, const char *));
175 static int send_data __P((FILE *, FILE *, off_t));
176 static struct passwd *
177 sgetpwnam __P((const char *));
178
179 int main __P((int, char *[]));
180
181 #if defined(KERBEROS) || defined(KERBEROS5)
182 int klogin __P((struct passwd *, char *, char *, char *));
183 void kdestroy __P((void));
184 #endif
185 int
186 main(argc, argv)
187 int argc;
188 char *argv[];
189 {
190 int addrlen, ch, on = 1, tos;
191 char *cp, line[LINE_MAX];
192 FILE *fd;
193 #ifdef KERBEROS5
194 krb5_error_code kerror;
195 #endif
196
197 debug = 0;
198 logging = 0;
199 sflag = 0;
200 (void)strcpy(confdir, _DEFAULT_CONFDIR);
201
202 while ((ch = getopt(argc, argv, "a:c:C:dlst:T:u:v")) != -1) {
203 switch (ch) {
204 case 'a':
205 anondir = optarg;
206 break;
207
208 case 'c':
209 (void)strncpy(confdir, optarg, sizeof(confdir));
210 confdir[sizeof(confdir)-1] = '\0';
211 break;
212
213 case 'C':
214 exit(checkaccess(optarg));
215 /* NOTREACHED */
216
217 case 'd':
218 case 'v': /* deprecated */
219 debug = 1;
220 break;
221
222 case 'l':
223 logging++; /* > 1 == extra logging */
224 break;
225
226 case 's':
227 sflag = 1;
228 break;
229
230 case 't':
231 case 'T':
232 case 'u':
233 warnx("-%c has been deprecated in favour of ftpd.conf",
234 ch);
235 break;
236
237 default:
238 if (optopt == 'a' || optopt == 'C')
239 exit(1);
240 warnx("unknown flag -%c ignored", optopt);
241 break;
242 }
243 }
244
245 /*
246 * LOG_NDELAY sets up the logging connection immediately,
247 * necessary for anonymous ftp's that chroot and can't do it later.
248 */
249 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
250 addrlen = sizeof(his_addr);
251 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
252 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
253 exit(1);
254 }
255 addrlen = sizeof(ctrl_addr);
256 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
257 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
258 exit(1);
259 }
260 #ifdef IP_TOS
261 tos = IPTOS_LOWDELAY;
262 if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(int)) < 0)
263 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
264 #endif
265 data_source.sin_port = htons(ntohs(ctrl_addr.sin_port) - 1);
266
267 /* set this here so klogin can use it... */
268 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
269
270 (void) freopen(_PATH_DEVNULL, "w", stderr);
271 (void) signal(SIGPIPE, lostconn);
272 (void) signal(SIGCHLD, SIG_IGN);
273 if ((long)signal(SIGURG, myoob) < 0)
274 syslog(LOG_ERR, "signal: %m");
275
276 /* Try to handle urgent data inline */
277 #ifdef SO_OOBINLINE
278 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
279 syslog(LOG_ERR, "setsockopt: %m");
280 #endif
281
282 #ifdef F_SETOWN
283 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
284 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
285 #endif
286 dolog(&his_addr);
287 /*
288 * Set up default state
289 */
290 data = -1;
291 type = TYPE_A;
292 form = FORM_N;
293 stru = STRU_F;
294 mode = MODE_S;
295 tmpline[0] = '\0';
296 hasyyerrored = 0;
297
298 #ifdef KERBEROS5
299 kerror = krb5_init_context(&kcontext);
300 if (kerror) {
301 syslog(LOG_NOTICE, "%s when initializing Kerberos context",
302 error_message(kerror));
303 exit(0);
304 }
305 #endif /* KERBEROS5 */
306
307 /* If logins are disabled, print out the message. */
308 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
309 while (fgets(line, sizeof(line), fd) != NULL) {
310 if ((cp = strchr(line, '\n')) != NULL)
311 *cp = '\0';
312 lreply(530, "%s", line);
313 }
314 (void) fflush(stdout);
315 (void) fclose(fd);
316 reply(530, "System not available.");
317 exit(0);
318 }
319 if ((fd = fopen(conffilename(_PATH_FTPWELCOME), "r")) != NULL) {
320 while (fgets(line, sizeof(line), fd) != NULL) {
321 if ((cp = strchr(line, '\n')) != NULL)
322 *cp = '\0';
323 lreply(220, "%s", line);
324 }
325 (void) fflush(stdout);
326 (void) fclose(fd);
327 /* reply(220,) must follow */
328 }
329 (void)gethostname(hostname, sizeof(hostname));
330 hostname[sizeof(hostname) - 1] = '\0';
331 reply(220, "%s FTP server (%s) ready.", hostname, version);
332 curclass.timeout = 300; /* 5 minutes, as per login(1) */
333 (void) setjmp(errcatch);
334 for (;;)
335 (void) yyparse();
336 /* NOTREACHED */
337 }
338
339 static void
340 lostconn(signo)
341 int signo;
342 {
343
344 if (debug)
345 syslog(LOG_DEBUG, "lost connection");
346 dologout(1);
347 }
348
349 /*
350 * Save the result of a getpwnam. Used for USER command, since
351 * the data returned must not be clobbered by any other command
352 * (e.g., globbing).
353 */
354 static struct passwd *
355 sgetpwnam(name)
356 const char *name;
357 {
358 static struct passwd save;
359 struct passwd *p;
360
361 if ((p = getpwnam(name)) == NULL)
362 return (p);
363 if (save.pw_name) {
364 free((char *)save.pw_name);
365 free((char *)save.pw_passwd);
366 free((char *)save.pw_gecos);
367 free((char *)save.pw_dir);
368 free((char *)save.pw_shell);
369 }
370 save = *p;
371 save.pw_name = xstrdup(p->pw_name);
372 save.pw_passwd = xstrdup(p->pw_passwd);
373 save.pw_gecos = xstrdup(p->pw_gecos);
374 save.pw_dir = xstrdup(p->pw_dir);
375 save.pw_shell = xstrdup(p->pw_shell);
376 return (&save);
377 }
378
379 static int login_attempts; /* number of failed login attempts */
380 static int askpasswd; /* had user command, ask for passwd */
381 static char curname[10]; /* current USER name */
382
383 /*
384 * USER command.
385 * Sets global passwd pointer pw if named account exists and is acceptable;
386 * sets askpasswd if a PASS command is expected. If logged in previously,
387 * need to reset state. If name is "ftp" or "anonymous", the name is not in
388 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
389 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
390 * requesting login privileges. Disallow anyone who does not have a standard
391 * shell as returned by getusershell(). Disallow anyone mentioned in the file
392 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
393 */
394 void
395 user(name)
396 char *name;
397 {
398 if (logged_in) {
399 if (guest) {
400 reply(530, "Can't change user from guest login.");
401 return;
402 } else if (dochroot) {
403 reply(530, "Can't change user from chroot user.");
404 return;
405 }
406 end_login();
407 }
408
409 #if defined(KERBEROS) || defined(KERBEROS5)
410 kdestroy();
411 #endif
412
413 guest = 0;
414 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
415 if (checkaccess("ftp") || checkaccess("anonymous"))
416 reply(530, "User %s access denied.", name);
417 else if ((pw = sgetpwnam("ftp")) != NULL) {
418 guest = 1;
419 askpasswd = 1;
420 reply(331,
421 "Guest login ok, type your name as password.");
422 } else
423 reply(530, "User %s unknown.", name);
424 if (!askpasswd && logging)
425 syslog(LOG_NOTICE,
426 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
427 return;
428 }
429
430 pw = sgetpwnam(name);
431 if (logging)
432 strncpy(curname, name, sizeof(curname)-1);
433
434 #ifdef SKEY
435 if (skey_haskey(name) == 0) {
436 char *myskey;
437
438 myskey = skey_keyinfo(name);
439 reply(331, "Password [%s] required for %s.",
440 myskey ? myskey : "error getting challenge", name);
441 } else
442 #endif
443 reply(331, "Password required for %s.", name);
444
445 askpasswd = 1;
446 /*
447 * Delay before reading passwd after first failed
448 * attempt to slow down passwd-guessing programs.
449 */
450 if (login_attempts)
451 sleep((unsigned) login_attempts);
452 }
453
454 /*
455 * Determine whether something is to happen (allow access, chroot)
456 * for a user. Each line is a shell-style glob followed by
457 * `yes' or `no'.
458 *
459 * For backward compatability, `allow' and `deny' are synonymns
460 * for `yes' and `no', respectively.
461 *
462 * Each glob is matched against the username in turn, and the first
463 * match found is used. If no match is found, the result is the
464 * argument `def'. If a match is found but without and explicit
465 * `yes'/`no', the result is the opposite of def.
466 *
467 * If the file doesn't exist at all, the result is the argument
468 * `nofile'
469 *
470 * Any line starting with `#' is considered a comment and ignored.
471 *
472 * Returns FALSE if the user is denied, or TRUE if they are allowed.
473 */
474 int
475 checkuser(fname, name, def, nofile)
476 const char *fname, *name;
477 int def, nofile;
478 {
479 FILE *fd;
480 int retval;
481 char *glob, *perm, line[BUFSIZ];
482
483 retval = def;
484 if ((fd = fopen(conffilename(fname), "r")) == NULL)
485 return nofile;
486
487 while (fgets(line, sizeof(line), fd) != NULL) {
488 glob = strtok(line, " \t\n");
489 if (glob == NULL || glob[0] == '#')
490 continue;
491 perm = strtok(NULL, " \t\n");
492 if (perm == NULL)
493 continue;
494 if (fnmatch(glob, name, 0) == 0) {
495 if (perm != NULL &&
496 ((strcasecmp(perm, "allow") == 0) ||
497 (strcasecmp(perm, "yes") == 0)))
498 retval = TRUE;
499 else if (perm != NULL &&
500 ((strcasecmp(perm, "deny") == 0) ||
501 (strcasecmp(perm, "no") == 0)))
502 retval = FALSE;
503 else
504 retval = !def;
505 break;
506 }
507 }
508 (void) fclose(fd);
509 return (retval);
510 }
511
512 /*
513 * Check if user is allowed by /etc/ftpusers
514 * returns 0 for yes, 1 for no
515 */
516 int
517 checkaccess(name)
518 const char *name;
519 {
520
521 return (! checkuser(_PATH_FTPUSERS, name, TRUE, FALSE));
522 }
523
524 /*
525 * Terminate login as previous user, if any, resetting state;
526 * used when USER command is given or login fails.
527 */
528 static void
529 end_login()
530 {
531
532 (void) seteuid((uid_t)0);
533 if (logged_in)
534 logwtmp(ttyline, "", "");
535 pw = NULL;
536 logged_in = 0;
537 guest = 0;
538 dochroot = 0;
539 }
540
541 void
542 pass(passwd)
543 char *passwd;
544 {
545 int rval;
546 FILE *fd;
547 char const *cp, *shell, *home;
548
549 if (logged_in || askpasswd == 0) {
550 reply(503, "Login with USER first.");
551 return;
552 }
553 askpasswd = 0;
554 if (!guest) { /* "ftp" is only account allowed no password */
555 if (pw == NULL) {
556 rval = 1; /* failure below */
557 goto skip;
558 }
559 #ifdef KERBEROS
560 if (klogin(pw, "", hostname, passwd) == 0) {
561 rval = 0;
562 goto skip;
563 }
564 #endif
565 #ifdef KERBEROS5
566 if (klogin(pw, "", hostname, passwd) == 0) {
567 rval = 0;
568 goto skip;
569 }
570 #endif
571 #ifdef SKEY
572 if (skey_haskey(pw->pw_name) == 0 &&
573 skey_passcheck(pw->pw_name, passwd) != -1) {
574 rval = 0;
575 goto skip;
576 }
577 #endif
578 if (!sflag && *pw->pw_passwd != '\0' &&
579 !strcmp(crypt(passwd, pw->pw_passwd), pw->pw_passwd)) {
580 rval = 0;
581 goto skip;
582 }
583 rval = 1;
584
585 skip:
586 if (pw != NULL && pw->pw_expire && time(NULL) >= pw->pw_expire)
587 rval = 2;
588 /*
589 * If rval > 0, the user failed the authentication check
590 * above. If rval == 0, either Kerberos or local authentication
591 * succeeded.
592 */
593 if (rval) {
594 reply(530, rval == 2 ? "Password expired." :
595 "Login incorrect.");
596 if (logging) {
597 syslog(LOG_NOTICE,
598 "FTP LOGIN FAILED FROM %s", remotehost);
599 syslog(LOG_AUTHPRIV | LOG_NOTICE,
600 "FTP LOGIN FAILED FROM %s, %s",
601 remotehost, curname);
602 }
603 pw = NULL;
604 if (login_attempts++ >= 5) {
605 syslog(LOG_NOTICE,
606 "repeated login failures from %s",
607 remotehost);
608 exit(0);
609 }
610 return;
611 }
612 }
613
614 /* password was ok; see if anything else prevents login */
615 if (checkaccess(pw->pw_name)) {
616 reply(530, "User %s may not use FTP.", pw->pw_name);
617 if (logging)
618 syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
619 remotehost, pw->pw_name);
620 pw = (struct passwd *) NULL;
621 return;
622 }
623 /* check for valid shell, if not guest user */
624 if ((shell = pw->pw_shell) == NULL || *shell == 0)
625 shell = _PATH_BSHELL;
626 while ((cp = getusershell()) != NULL)
627 if (strcmp(cp, shell) == 0)
628 break;
629 endusershell();
630 if (cp == NULL && guest == 0) {
631 reply(530, "User %s may not use FTP.", pw->pw_name);
632 if (logging)
633 syslog(LOG_NOTICE,
634 "FTP LOGIN REFUSED FROM %s, %s",
635 remotehost, pw->pw_name);
636 pw = (struct passwd *) NULL;
637 return;
638 }
639
640 login_attempts = 0; /* this time successful */
641 if (setegid((gid_t)pw->pw_gid) < 0) {
642 reply(550, "Can't set gid.");
643 return;
644 }
645 (void) initgroups(pw->pw_name, pw->pw_gid);
646
647 /* open wtmp before chroot */
648 logwtmp(ttyline, pw->pw_name, remotehost);
649 logged_in = 1;
650
651 dochroot = checkuser(_PATH_FTPCHROOT, pw->pw_name, FALSE, FALSE);
652
653 /* parse ftpd.conf, setting up various parameters */
654 if (guest)
655 parse_conf(CLASS_GUEST);
656 else if (dochroot)
657 parse_conf(CLASS_CHROOT);
658 else
659 parse_conf(CLASS_REAL);
660
661 home = "/";
662 if (guest) {
663 /*
664 * We MUST do a chdir() after the chroot. Otherwise
665 * the old current directory will be accessible as "."
666 * outside the new root!
667 */
668 if (chroot(anondir ? anondir : pw->pw_dir) < 0 ||
669 chdir("/") < 0) {
670 reply(550, "Can't set guest privileges.");
671 goto bad;
672 }
673 } else if (dochroot) {
674 if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
675 reply(550, "Can't change root.");
676 goto bad;
677 }
678 } else if (chdir(pw->pw_dir) < 0) {
679 if (chdir("/") < 0) {
680 reply(530, "User %s: can't change directory to %s.",
681 pw->pw_name, pw->pw_dir);
682 goto bad;
683 } else
684 lreply(230, "No directory! Logging in with home=/");
685 } else
686 home = pw->pw_dir;
687 if (seteuid((uid_t)pw->pw_uid) < 0) {
688 reply(550, "Can't set uid.");
689 goto bad;
690 }
691 setenv("HOME", home, 1);
692
693
694 /*
695 * Display a login message, if it exists.
696 * N.B. reply(230,) must follow the message.
697 */
698 if ((fd = fopen(conffilename(_PATH_FTPLOGINMESG), "r")) != NULL) {
699 char *cp, line[LINE_MAX];
700
701 while (fgets(line, sizeof(line), fd) != NULL) {
702 if ((cp = strchr(line, '\n')) != NULL)
703 *cp = '\0';
704 lreply(230, "%s", line);
705 }
706 (void) fflush(stdout);
707 (void) fclose(fd);
708 }
709 show_chdir_messages(230);
710 if (guest) {
711 reply(230, "Guest login ok, access restrictions apply.");
712 #ifdef HASSETPROCTITLE
713 snprintf(proctitle, sizeof(proctitle),
714 "%s: anonymous/%.*s", remotehost,
715 (int) (sizeof(proctitle) - sizeof(remotehost) -
716 sizeof(": anonymous/")), passwd);
717 setproctitle(proctitle);
718 #endif /* HASSETPROCTITLE */
719 if (logging)
720 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
721 remotehost, passwd);
722 } else {
723 reply(230, "User %s logged in.", pw->pw_name);
724 #ifdef HASSETPROCTITLE
725 snprintf(proctitle, sizeof(proctitle),
726 "%s: %s", remotehost, pw->pw_name);
727 setproctitle(proctitle);
728 #endif /* HASSETPROCTITLE */
729 if (logging)
730 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
731 remotehost, pw->pw_name);
732 }
733 (void) umask(curclass.umask);
734 return;
735 bad:
736 /* Forget all about it... */
737 end_login();
738 }
739
740 void
741 retrieve(cmd, name)
742 char *cmd, *name;
743 {
744 FILE *fin = NULL, *dout;
745 struct stat st;
746 int (*closefunc) __P((FILE *)) = NULL;
747 int log, sendrv, closerv, stderrfd, isconversion;
748
749 sendrv = closerv = stderrfd = -1;
750 isconversion = 0;
751 log = (cmd == 0);
752 if (cmd == NULL) {
753 fin = fopen(name, "r"), closefunc = fclose;
754 if (fin == NULL)
755 cmd = do_conversion(name);
756 if (cmd != NULL) {
757 isconversion++;
758 syslog(LOG_INFO, "get command: '%s'", cmd);
759 }
760 }
761 if (cmd != NULL) {
762 char line[BUFSIZ];
763 char temp[MAXPATHLEN + 1];
764
765 (void)snprintf(temp, sizeof(temp), "%s", TMPFILE);
766 stderrfd = mkstemp(temp);
767 if (stderrfd != -1)
768 (void)unlink(temp);
769 (void)snprintf(line, sizeof(line), cmd, name), name = line;
770 fin = ftpd_popen(line, "r", stderrfd), closefunc = ftpd_pclose;
771 st.st_size = -1;
772 st.st_blksize = BUFSIZ;
773 }
774 if (fin == NULL) {
775 if (errno != 0) {
776 perror_reply(550, name);
777 if (log) {
778 logcmd("get", -1, name, NULL);
779 }
780 }
781 if (stderrfd != -1)
782 (void)close(stderrfd);
783 return;
784 }
785 byte_count = -1;
786 if (cmd == NULL
787 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
788 reply(550, "%s: not a plain file.", name);
789 goto done;
790 }
791 if (restart_point) {
792 if (type == TYPE_A) {
793 off_t i;
794 int c;
795
796 for (i = 0; i < restart_point; i++) {
797 if ((c=getc(fin)) == EOF) {
798 perror_reply(550, name);
799 goto done;
800 }
801 if (c == '\n')
802 i++;
803 }
804 } else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
805 perror_reply(550, name);
806 goto done;
807 }
808 }
809 dout = dataconn(name, st.st_size, "w");
810 if (dout == NULL)
811 goto done;
812 sendrv = send_data(fin, dout, st.st_blksize);
813 (void) fclose(dout);
814 data = -1;
815 pdata = -1;
816 done:
817 if (log)
818 logcmd("get", byte_count, name, NULL);
819 closerv = (*closefunc)(fin);
820 if (sendrv == 0) {
821 FILE *err;
822 struct stat sb;
823
824 if (cmd != NULL && closerv != 0) {
825 lreply(226,
826 "Command returned an exit status of %d",
827 closerv);
828 if (isconversion)
829 syslog(LOG_INFO,
830 "get command: '%s' returned %d",
831 cmd, closerv);
832 }
833 if (cmd != NULL && stderrfd != -1 &&
834 (fstat(stderrfd, &sb) == 0) && sb.st_size > 0 &&
835 ((err = fdopen(stderrfd, "r")) != NULL)) {
836 char *cp, line[LINE_MAX];
837
838 lreply(226, "Command error messages:");
839 rewind(err);
840 while (fgets(line, sizeof(line), err) != NULL) {
841 if ((cp = strchr(line, '\n')) != NULL)
842 *cp = '\0';
843 lreply(226, " %s", line);
844 }
845 (void) fflush(stdout);
846 (void) fclose(err);
847 lreply(226, "End of command error messages.");
848 /* a reply(226,) must follow */
849 }
850 reply(226, "Transfer complete.");
851 }
852 if (stderrfd != -1)
853 (void)close(stderrfd);
854 }
855
856 void
857 store(name, mode, unique)
858 char *name, *mode;
859 int unique;
860 {
861 FILE *fout, *din;
862 struct stat st;
863 int (*closefunc) __P((FILE *));
864
865 if (unique && stat(name, &st) == 0 &&
866 (name = gunique(name)) == NULL) {
867 logcmd(*mode == 'w' ? "put" : "append", -1, name, NULL);
868 return;
869 }
870
871 if (restart_point)
872 mode = "r+";
873 fout = fopen(name, mode);
874 closefunc = fclose;
875 if (fout == NULL) {
876 perror_reply(553, name);
877 logcmd(*mode == 'w' ? "put" : "append", -1, name, NULL);
878 return;
879 }
880 byte_count = -1;
881 if (restart_point) {
882 if (type == TYPE_A) {
883 off_t i;
884 int c;
885
886 for (i = 0; i < restart_point; i++) {
887 if ((c=getc(fout)) == EOF) {
888 perror_reply(550, name);
889 goto done;
890 }
891 if (c == '\n')
892 i++;
893 }
894 /*
895 * We must do this seek to "current" position
896 * because we are changing from reading to
897 * writing.
898 */
899 if (fseek(fout, 0L, SEEK_CUR) < 0) {
900 perror_reply(550, name);
901 goto done;
902 }
903 } else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
904 perror_reply(550, name);
905 goto done;
906 }
907 }
908 din = dataconn(name, (off_t)-1, "r");
909 if (din == NULL)
910 goto done;
911 if (receive_data(din, fout) == 0) {
912 if (unique)
913 reply(226, "Transfer complete (unique file name:%s).",
914 name);
915 else
916 reply(226, "Transfer complete.");
917 }
918 (void) fclose(din);
919 data = -1;
920 pdata = -1;
921 done:
922 logcmd(*mode == 'w' ? "put" : "append", byte_count, name, NULL);
923 (*closefunc)(fout);
924 }
925
926 static FILE *
927 getdatasock(mode)
928 char *mode;
929 {
930 int on = 1, s, t, tries;
931
932 if (data >= 0)
933 return (fdopen(data, mode));
934 (void) seteuid((uid_t)0);
935 s = socket(AF_INET, SOCK_STREAM, 0);
936 if (s < 0)
937 goto bad;
938 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
939 (char *) &on, sizeof(on)) < 0)
940 goto bad;
941 /* anchor socket to avoid multi-homing problems */
942 data_source.sin_len = sizeof(struct sockaddr_in);
943 data_source.sin_family = AF_INET;
944 data_source.sin_addr = ctrl_addr.sin_addr;
945 for (tries = 1; ; tries++) {
946 if (bind(s, (struct sockaddr *)&data_source,
947 sizeof(data_source)) >= 0)
948 break;
949 if (errno != EADDRINUSE || tries > 10)
950 goto bad;
951 sleep(tries);
952 }
953 (void) seteuid((uid_t)pw->pw_uid);
954 #ifdef IP_TOS
955 on = IPTOS_THROUGHPUT;
956 if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on, sizeof(int)) < 0)
957 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
958 #endif
959 return (fdopen(s, mode));
960 bad:
961 /* Return the real value of errno (close may change it) */
962 t = errno;
963 (void) seteuid((uid_t)pw->pw_uid);
964 (void) close(s);
965 errno = t;
966 return (NULL);
967 }
968
969 static FILE *
970 dataconn(name, size, mode)
971 char *name;
972 off_t size;
973 char *mode;
974 {
975 char sizebuf[32];
976 FILE *file;
977 int retry = 0, tos;
978
979 file_size = size;
980 byte_count = 0;
981 if (size != (off_t) -1)
982 (void)snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)",
983 (long long)size);
984 else
985 sizebuf[0] = '\0';
986 if (pdata >= 0) {
987 struct sockaddr_in from;
988 int s, fromlen = sizeof(from);
989
990 (void) alarm(curclass.timeout);
991 s = accept(pdata, (struct sockaddr *)&from, &fromlen);
992 (void) alarm(0);
993 if (s < 0) {
994 reply(425, "Can't open data connection.");
995 (void) close(pdata);
996 pdata = -1;
997 return (NULL);
998 }
999 (void) close(pdata);
1000 pdata = s;
1001 #ifdef IP_TOS
1002 tos = IPTOS_THROUGHPUT;
1003 (void) setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&tos,
1004 sizeof(int));
1005 #endif
1006 reply(150, "Opening %s mode data connection for '%s'%s.",
1007 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1008 return (fdopen(pdata, mode));
1009 }
1010 if (data >= 0) {
1011 reply(125, "Using existing data connection for '%s'%s.",
1012 name, sizebuf);
1013 usedefault = 1;
1014 return (fdopen(data, mode));
1015 }
1016 if (usedefault)
1017 data_dest = his_addr;
1018 usedefault = 1;
1019 file = getdatasock(mode);
1020 if (file == NULL) {
1021 reply(425, "Can't create data socket (%s,%d): %s.",
1022 inet_ntoa(data_source.sin_addr),
1023 ntohs(data_source.sin_port), strerror(errno));
1024 return (NULL);
1025 }
1026 data = fileno(file);
1027 while (connect(data, (struct sockaddr *)&data_dest,
1028 sizeof(data_dest)) < 0) {
1029 if (errno == EADDRINUSE && retry < swaitmax) {
1030 sleep((unsigned) swaitint);
1031 retry += swaitint;
1032 continue;
1033 }
1034 perror_reply(425, "Can't build data connection");
1035 (void) fclose(file);
1036 data = -1;
1037 return (NULL);
1038 }
1039 reply(150, "Opening %s mode data connection for '%s'%s.",
1040 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1041 return (file);
1042 }
1043
1044 /*
1045 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1046 * encapsulation of the data subject * to Mode, Structure, and Type.
1047 *
1048 * NB: Form isn't handled.
1049 */
1050 static int
1051 send_data(instr, outstr, blksize)
1052 FILE *instr, *outstr;
1053 off_t blksize;
1054 {
1055 int c, cnt, filefd, netfd;
1056 char *buf;
1057
1058 transflag++;
1059 if (setjmp(urgcatch)) {
1060 transflag = 0;
1061 return (-1);
1062 }
1063
1064 switch (type) {
1065
1066 case TYPE_A:
1067 while ((c = getc(instr)) != EOF) {
1068 byte_count++;
1069 if (c == '\n') {
1070 if (ferror(outstr))
1071 goto data_err;
1072 (void) putc('\r', outstr);
1073 }
1074 (void) putc(c, outstr);
1075 }
1076 fflush(outstr);
1077 transflag = 0;
1078 if (ferror(instr))
1079 goto file_err;
1080 if (ferror(outstr))
1081 goto data_err;
1082 return (0);
1083
1084 case TYPE_I:
1085 case TYPE_L:
1086 if ((buf = malloc((u_int)blksize)) == NULL) {
1087 transflag = 0;
1088 perror_reply(451, "Local resource failure: malloc");
1089 return (-1);
1090 }
1091 netfd = fileno(outstr);
1092 filefd = fileno(instr);
1093 while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
1094 write(netfd, buf, cnt) == cnt)
1095 byte_count += cnt;
1096 transflag = 0;
1097 (void)free(buf);
1098 if (cnt != 0) {
1099 if (cnt < 0)
1100 goto file_err;
1101 goto data_err;
1102 }
1103 return (0);
1104 default:
1105 transflag = 0;
1106 reply(550, "Unimplemented TYPE %d in send_data", type);
1107 return (-1);
1108 }
1109
1110 data_err:
1111 transflag = 0;
1112 perror_reply(426, "Data connection");
1113 return (-1);
1114
1115 file_err:
1116 transflag = 0;
1117 perror_reply(551, "Error on input file");
1118 return (-1);
1119 }
1120
1121 /*
1122 * Transfer data from peer to "outstr" using the appropriate encapulation of
1123 * the data subject to Mode, Structure, and Type.
1124 *
1125 * N.B.: Form isn't handled.
1126 */
1127 static int
1128 receive_data(instr, outstr)
1129 FILE *instr, *outstr;
1130 {
1131 int c, cnt, bare_lfs;
1132 char buf[BUFSIZ];
1133 #ifdef __GNUC__
1134 (void) &bare_lfs;
1135 #endif
1136
1137 bare_lfs = 0;
1138 transflag++;
1139 if (setjmp(urgcatch)) {
1140 transflag = 0;
1141 return (-1);
1142 }
1143
1144 switch (type) {
1145
1146 case TYPE_I:
1147 case TYPE_L:
1148 while ((cnt = read(fileno(instr), buf, sizeof(buf))) > 0) {
1149 if (write(fileno(outstr), buf, cnt) != cnt)
1150 goto file_err;
1151 byte_count += cnt;
1152 }
1153 if (cnt < 0)
1154 goto data_err;
1155 transflag = 0;
1156 return (0);
1157
1158 case TYPE_E:
1159 reply(553, "TYPE E not implemented.");
1160 transflag = 0;
1161 return (-1);
1162
1163 case TYPE_A:
1164 while ((c = getc(instr)) != EOF) {
1165 byte_count++;
1166 if (c == '\n')
1167 bare_lfs++;
1168 while (c == '\r') {
1169 if (ferror(outstr))
1170 goto data_err;
1171 if ((c = getc(instr)) != '\n') {
1172 (void) putc ('\r', outstr);
1173 if (c == '\0' || c == EOF)
1174 goto contin2;
1175 }
1176 }
1177 (void) putc(c, outstr);
1178 contin2: ;
1179 }
1180 fflush(outstr);
1181 if (ferror(instr))
1182 goto data_err;
1183 if (ferror(outstr))
1184 goto file_err;
1185 transflag = 0;
1186 if (bare_lfs) {
1187 lreply(226,
1188 "WARNING! %d bare linefeeds received in ASCII mode",
1189 bare_lfs);
1190 (void)printf(" File may not have transferred correctly.\r\n");
1191 }
1192 return (0);
1193 default:
1194 reply(550, "Unimplemented TYPE %d in receive_data", type);
1195 transflag = 0;
1196 return (-1);
1197 }
1198
1199 data_err:
1200 transflag = 0;
1201 perror_reply(426, "Data Connection");
1202 return (-1);
1203
1204 file_err:
1205 transflag = 0;
1206 perror_reply(452, "Error writing file");
1207 return (-1);
1208 }
1209
1210 void
1211 statfilecmd(filename)
1212 char *filename;
1213 {
1214 FILE *fin;
1215 int c;
1216 char line[LINE_MAX];
1217
1218 (void)snprintf(line, sizeof(line), "/bin/ls -lgA %s", filename);
1219 fin = ftpd_popen(line, "r", STDOUT_FILENO);
1220 lreply(211, "status of %s:", filename);
1221 while ((c = getc(fin)) != EOF) {
1222 if (c == '\n') {
1223 if (ferror(stdout)){
1224 perror_reply(421, "control connection");
1225 (void) ftpd_pclose(fin);
1226 dologout(1);
1227 /* NOTREACHED */
1228 }
1229 if (ferror(fin)) {
1230 perror_reply(551, filename);
1231 (void) ftpd_pclose(fin);
1232 return;
1233 }
1234 (void) putc('\r', stdout);
1235 }
1236 (void) putc(c, stdout);
1237 }
1238 (void) ftpd_pclose(fin);
1239 reply(211, "End of Status");
1240 }
1241
1242 void
1243 statcmd()
1244 {
1245 struct sockaddr_in *sin;
1246 u_char *a, *p;
1247
1248 lreply(211, "%s FTP server status:", hostname);
1249 lreply(211, "%s", version);
1250 if (isdigit(remotehost[0]))
1251 lreply(211, "Connected to %s", remotehost);
1252 else
1253 lreply(211, "Connected to %s (%s)", remotehost,
1254 inet_ntoa(his_addr.sin_addr));
1255 if (logged_in) {
1256 if (guest)
1257 lreply(211, "Logged in anonymously");
1258 else
1259 lreply(211, "Logged in as %s", pw->pw_name);
1260 } else if (askpasswd)
1261 lreply(211, "Waiting for password");
1262 else
1263 lreply(211, "Waiting for user name");
1264 printf("211- TYPE: %s", typenames[type]);
1265 if (type == TYPE_A || type == TYPE_E)
1266 printf(", FORM: %s", formnames[form]);
1267 if (type == TYPE_L)
1268 #if NBBY == 8
1269 printf(" %d", NBBY);
1270 #else
1271 printf(" %d", bytesize); /* need definition! */
1272 #endif
1273 printf("; STRUcture: %s; transfer MODE: %s\r\n",
1274 strunames[stru], modenames[mode]);
1275 if (data != -1)
1276 lreply(211, "Data connection open");
1277 else if (pdata != -1) {
1278 printf("211- in Passive mode");
1279 sin = &pasv_addr;
1280 goto printaddr;
1281 } else if (usedefault == 0) {
1282 printf("211- PORT");
1283 sin = &data_dest;
1284 printaddr:
1285 a = (u_char *) &sin->sin_addr;
1286 p = (u_char *) &sin->sin_port;
1287 #define UC(b) (((int) b) & 0xff)
1288 printf(" (%d,%d,%d,%d,%d,%d)\r\n", UC(a[0]),
1289 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
1290 #undef UC
1291 } else
1292 lreply(211, "No data connection");
1293
1294 if (logged_in) {
1295 struct ftpconv *cp;
1296
1297 lreply(211, "");
1298 lreply(211, "Class: %s", curclass.classname);
1299 lreply(211, "Check PORT commands: %sabled",
1300 curclass.checkportcmd ? "en" : "dis");
1301 if (curclass.display)
1302 lreply(211, "Display file: %s", curclass.display);
1303 if (curclass.notify)
1304 lreply(211, "Notify fileglob: %s", curclass.notify);
1305 lreply(211, "Idle timeout: %d, maximum timeout: %d",
1306 curclass.timeout, curclass.maxtimeout);
1307 lreply(211, "DELE, MKD, RMD, UMASK, CHMOD commands: %sabled",
1308 curclass.modify ? "en" : "dis");
1309 lreply(211, "Umask: %.04o", curclass.umask);
1310 for (cp = curclass.conversions; cp != NULL; cp=cp->next) {
1311 if (cp->suffix == NULL || cp->types == NULL ||
1312 cp->command == NULL)
1313 continue;
1314 lreply(211,
1315 "Conversion: %s [%s] disable: %s, command: %s",
1316 cp->suffix, cp->types, cp->disable, cp->command);
1317 }
1318 }
1319
1320 reply(211, "End of status");
1321 }
1322
1323 void
1324 fatal(s)
1325 char *s;
1326 {
1327
1328 reply(451, "Error in server: %s\n", s);
1329 reply(221, "Closing connection due to server error.");
1330 dologout(0);
1331 /* NOTREACHED */
1332 }
1333
1334 void
1335 #ifdef __STDC__
1336 reply(int n, const char *fmt, ...)
1337 #else
1338 reply(n, fmt, va_alist)
1339 int n;
1340 char *fmt;
1341 va_dcl
1342 #endif
1343 {
1344 va_list ap;
1345 #ifdef __STDC__
1346 va_start(ap, fmt);
1347 #else
1348 va_start(ap);
1349 #endif
1350 (void)printf("%d ", n);
1351 (void)vprintf(fmt, ap);
1352 (void)printf("\r\n");
1353 (void)fflush(stdout);
1354 if (debug) {
1355 syslog(LOG_DEBUG, "<--- %d ", n);
1356 vsyslog(LOG_DEBUG, fmt, ap);
1357 }
1358 }
1359
1360 void
1361 #ifdef __STDC__
1362 lreply(int n, const char *fmt, ...)
1363 #else
1364 lreply(n, fmt, va_alist)
1365 int n;
1366 char *fmt;
1367 va_dcl
1368 #endif
1369 {
1370 va_list ap;
1371 #ifdef __STDC__
1372 va_start(ap, fmt);
1373 #else
1374 va_start(ap);
1375 #endif
1376 (void)printf("%d- ", n);
1377 (void)vprintf(fmt, ap);
1378 (void)printf("\r\n");
1379 (void)fflush(stdout);
1380 if (debug) {
1381 syslog(LOG_DEBUG, "<--- %d- ", n);
1382 vsyslog(LOG_DEBUG, fmt, ap);
1383 }
1384 }
1385
1386 static void
1387 ack(s)
1388 char *s;
1389 {
1390
1391 reply(250, "%s command successful.", s);
1392 }
1393
1394 void
1395 delete(name)
1396 char *name;
1397 {
1398
1399 logcmd("delete", -1, name, NULL);
1400 if (remove(name) < 0)
1401 perror_reply(550, name);
1402 else
1403 ack("DELE");
1404 }
1405
1406 void
1407 cwd(path)
1408 const char *path;
1409 {
1410
1411 if (chdir(path) < 0)
1412 perror_reply(550, path);
1413 else {
1414 show_chdir_messages(250);
1415 ack("CWD");
1416 }
1417 }
1418
1419 static void
1420 replydirname(name, message)
1421 const char *name, *message;
1422 {
1423 char npath[MAXPATHLEN + 1];
1424 int i;
1425
1426 for (i = 0; *name != '\0' && i < sizeof(npath) - 1; i++, name++) {
1427 npath[i] = *name;
1428 if (*name == '"')
1429 npath[++i] = '"';
1430 }
1431 npath[i] = '\0';
1432 reply(257, "\"%s\" %s", npath, message);
1433 }
1434
1435 void
1436 makedir(name)
1437 char *name;
1438 {
1439
1440 logcmd("mkdir", -1, name, NULL);
1441 if (mkdir(name, 0777) < 0)
1442 perror_reply(550, name);
1443 else
1444 replydirname(name, "directory created.");
1445 }
1446
1447 void
1448 removedir(name)
1449 char *name;
1450 {
1451
1452 logcmd("rmdir", -1, name, NULL);
1453 if (rmdir(name) < 0)
1454 perror_reply(550, name);
1455 else
1456 ack("RMD");
1457 }
1458
1459 void
1460 pwd()
1461 {
1462 char path[MAXPATHLEN + 1];
1463
1464 if (getcwd(path, sizeof(path) - 1) == NULL)
1465 reply(550, "Can't get the current directory: %s.",
1466 strerror(errno));
1467 else
1468 replydirname(path, "is the current directory.");
1469 }
1470
1471 char *
1472 renamefrom(name)
1473 char *name;
1474 {
1475 struct stat st;
1476
1477 if (stat(name, &st) < 0) {
1478 perror_reply(550, name);
1479 return (NULL);
1480 }
1481 reply(350, "File exists, ready for destination name");
1482 return (name);
1483 }
1484
1485 void
1486 renamecmd(from, to)
1487 char *from, *to;
1488 {
1489
1490 logcmd("rename", -1, from, to);
1491 if (rename(from, to) < 0)
1492 perror_reply(550, "rename");
1493 else
1494 ack("RNTO");
1495 }
1496
1497 static void
1498 dolog(sin)
1499 struct sockaddr_in *sin;
1500 {
1501 struct hostent *hp = gethostbyaddr((char *)&sin->sin_addr,
1502 sizeof(struct in_addr), AF_INET);
1503
1504 if (hp)
1505 (void)strncpy(remotehost, hp->h_name, sizeof(remotehost));
1506 else
1507 (void)strncpy(remotehost, inet_ntoa(sin->sin_addr),
1508 sizeof(remotehost));
1509 remotehost[sizeof(remotehost) - 1] = '\0';
1510 #ifdef HASSETPROCTITLE
1511 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
1512 setproctitle(proctitle);
1513 #endif /* HASSETPROCTITLE */
1514
1515 if (logging)
1516 syslog(LOG_INFO, "connection from %s", remotehost);
1517 }
1518
1519 /*
1520 * Record logout in wtmp file
1521 * and exit with supplied status.
1522 */
1523 void
1524 dologout(status)
1525 int status;
1526 {
1527 /*
1528 * Prevent reception of SIGURG from resulting in a resumption
1529 * back to the main program loop.
1530 */
1531 transflag = 0;
1532
1533 if (logged_in) {
1534 (void) seteuid((uid_t)0);
1535 logwtmp(ttyline, "", "");
1536 #ifdef KERBEROS
1537 if (!notickets && krbtkfile_env)
1538 unlink(krbtkfile_env);
1539 #endif
1540 }
1541 /* beware of flushing buffers after a SIGPIPE */
1542 _exit(status);
1543 }
1544
1545 static void
1546 myoob(signo)
1547 int signo;
1548 {
1549 char *cp;
1550
1551 /* only process if transfer occurring */
1552 if (!transflag)
1553 return;
1554 cp = tmpline;
1555 if (getline(cp, 7, stdin) == NULL) {
1556 reply(221, "You could at least say goodbye.");
1557 dologout(0);
1558 }
1559 if (strcasecmp(cp, "ABOR\r\n") == 0) {
1560 tmpline[0] = '\0';
1561 reply(426, "Transfer aborted. Data connection closed.");
1562 reply(226, "Abort successful");
1563 longjmp(urgcatch, 1);
1564 }
1565 if (strcasecmp(cp, "STAT\r\n") == 0) {
1566 if (file_size != (off_t) -1)
1567 reply(213, "Status: %qd of %qd bytes transferred",
1568 byte_count, file_size);
1569 else
1570 reply(213, "Status: %qd bytes transferred", byte_count);
1571 }
1572 }
1573
1574 /*
1575 * Note: a response of 425 is not mentioned as a possible response to
1576 * the PASV command in RFC959. However, it has been blessed as
1577 * a legitimate response by Jon Postel in a telephone conversation
1578 * with Rick Adams on 25 Jan 89.
1579 */
1580 void
1581 passive()
1582 {
1583 int len;
1584 char *p, *a;
1585
1586 pdata = socket(AF_INET, SOCK_STREAM, 0);
1587 if (pdata < 0 || !logged_in) {
1588 perror_reply(425, "Can't open passive connection");
1589 return;
1590 }
1591 pasv_addr = ctrl_addr;
1592 pasv_addr.sin_port = 0;
1593 (void) seteuid((uid_t)0);
1594 if (bind(pdata, (struct sockaddr *)&pasv_addr, sizeof(pasv_addr)) < 0) {
1595 (void) seteuid((uid_t)pw->pw_uid);
1596 goto pasv_error;
1597 }
1598 (void) seteuid((uid_t)pw->pw_uid);
1599 len = sizeof(pasv_addr);
1600 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
1601 goto pasv_error;
1602 if (listen(pdata, 1) < 0)
1603 goto pasv_error;
1604 a = (char *) &pasv_addr.sin_addr;
1605 p = (char *) &pasv_addr.sin_port;
1606
1607 #define UC(b) (((int) b) & 0xff)
1608
1609 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
1610 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
1611 return;
1612
1613 pasv_error:
1614 (void) close(pdata);
1615 pdata = -1;
1616 perror_reply(425, "Can't open passive connection");
1617 return;
1618 }
1619
1620 /*
1621 * Generate unique name for file with basename "local".
1622 * The file named "local" is already known to exist.
1623 * Generates failure reply on error.
1624 *
1625 * XXX this function should under go changes similar to
1626 * the mktemp(3)/mkstemp(3) changes.
1627 */
1628 static char *
1629 gunique(local)
1630 char *local;
1631 {
1632 static char new[MAXPATHLEN + 1];
1633 struct stat st;
1634 int count, len;
1635 char *cp;
1636
1637 cp = strrchr(local, '/');
1638 if (cp)
1639 *cp = '\0';
1640 if (stat(cp ? local : ".", &st) < 0) {
1641 perror_reply(553, cp ? local : ".");
1642 return (NULL);
1643 }
1644 if (cp)
1645 *cp = '/';
1646 (void) strcpy(new, local);
1647 len = strlen(new);
1648 cp = new + len;
1649 *cp++ = '.';
1650 for (count = 1; count < 100; count++) {
1651 (void)snprintf(cp, sizeof(new) - len - 2, "%d", count);
1652 if (stat(new, &st) < 0)
1653 return (new);
1654 }
1655 reply(452, "Unique file name cannot be created.");
1656 return (NULL);
1657 }
1658
1659 /*
1660 * Format and send reply containing system error number.
1661 */
1662 void
1663 perror_reply(code, string)
1664 int code;
1665 const char *string;
1666 {
1667
1668 reply(code, "%s: %s.", string, strerror(errno));
1669 }
1670
1671 static char *onefile[] = {
1672 "",
1673 0
1674 };
1675
1676 void
1677 send_file_list(whichf)
1678 char *whichf;
1679 {
1680 struct stat st;
1681 DIR *dirp = NULL;
1682 struct dirent *dir;
1683 FILE *dout = NULL;
1684 char **dirlist, *dirname;
1685 int simple = 0;
1686 int freeglob = 0;
1687 glob_t gl;
1688 #ifdef __GNUC__
1689 (void) &dout;
1690 (void) &dirlist;
1691 (void) &simple;
1692 (void) &freeglob;
1693 #endif
1694
1695 if (strpbrk(whichf, "~{[*?") != NULL) {
1696 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
1697
1698 memset(&gl, 0, sizeof(gl));
1699 freeglob = 1;
1700 if (glob(whichf, flags, 0, &gl)) {
1701 reply(550, "not found");
1702 goto out;
1703 } else if (gl.gl_pathc == 0) {
1704 errno = ENOENT;
1705 perror_reply(550, whichf);
1706 goto out;
1707 }
1708 dirlist = gl.gl_pathv;
1709 } else {
1710 onefile[0] = whichf;
1711 dirlist = onefile;
1712 simple = 1;
1713 }
1714
1715 if (setjmp(urgcatch)) {
1716 transflag = 0;
1717 goto out;
1718 }
1719 while ((dirname = *dirlist++) != NULL) {
1720 int trailingslash = 0;
1721
1722 if (stat(dirname, &st) < 0) {
1723 /*
1724 * If user typed "ls -l", etc, and the client
1725 * used NLST, do what the user meant.
1726 */
1727 if (dirname[0] == '-' && *dirlist == NULL &&
1728 transflag == 0) {
1729 retrieve("/bin/ls %s", dirname);
1730 goto out;
1731 }
1732 perror_reply(550, whichf);
1733 if (dout != NULL) {
1734 (void) fclose(dout);
1735 transflag = 0;
1736 data = -1;
1737 pdata = -1;
1738 }
1739 goto out;
1740 }
1741
1742 if (S_ISREG(st.st_mode)) {
1743 if (dout == NULL) {
1744 dout = dataconn("file list", (off_t)-1, "w");
1745 if (dout == NULL)
1746 goto out;
1747 transflag++;
1748 }
1749 fprintf(dout, "%s%s\n", dirname,
1750 type == TYPE_A ? "\r" : "");
1751 byte_count += strlen(dirname) + 1;
1752 continue;
1753 } else if (!S_ISDIR(st.st_mode))
1754 continue;
1755
1756 if (dirname[strlen(dirname) - 1] == '/')
1757 trailingslash++;
1758
1759 if ((dirp = opendir(dirname)) == NULL)
1760 continue;
1761
1762 while ((dir = readdir(dirp)) != NULL) {
1763 char nbuf[MAXPATHLEN + 1];
1764
1765 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
1766 continue;
1767 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
1768 dir->d_namlen == 2)
1769 continue;
1770
1771 (void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
1772 trailingslash ? "" : "/", dir->d_name);
1773
1774 /*
1775 * We have to do a stat to ensure it's
1776 * not a directory or special file.
1777 */
1778 if (simple || (stat(nbuf, &st) == 0 &&
1779 S_ISREG(st.st_mode))) {
1780 if (dout == NULL) {
1781 dout = dataconn("file list", (off_t)-1,
1782 "w");
1783 if (dout == NULL)
1784 goto out;
1785 transflag++;
1786 }
1787 if (nbuf[0] == '.' && nbuf[1] == '/')
1788 fprintf(dout, "%s%s\n", &nbuf[2],
1789 type == TYPE_A ? "\r" : "");
1790 else
1791 fprintf(dout, "%s%s\n", nbuf,
1792 type == TYPE_A ? "\r" : "");
1793 byte_count += strlen(nbuf) + 1;
1794 }
1795 }
1796 (void) closedir(dirp);
1797 }
1798
1799 if (dout == NULL)
1800 reply(550, "No files found.");
1801 else if (ferror(dout) != 0)
1802 perror_reply(550, "Data connection");
1803 else
1804 reply(226, "Transfer complete.");
1805
1806 transflag = 0;
1807 if (dout != NULL)
1808 (void) fclose(dout);
1809 data = -1;
1810 pdata = -1;
1811 out:
1812 if (freeglob) {
1813 freeglob = 0;
1814 globfree(&gl);
1815 }
1816 }
1817
1818 char *
1819 conffilename(s)
1820 const char *s;
1821 {
1822 static char filename[MAXPATHLEN + 1];
1823
1824 (void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
1825 return filename;
1826 }
1827