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