ftpd.c revision 1.45 1 /* $NetBSD: ftpd.c,v 1.45 1998/02/01 14:10:22 christos 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.45 1998/02/01 14:10:22 christos 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, *home;
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 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
646 rval = 2;
647 /*
648 * If rval > 0, the user failed the authentication check
649 * above. If rval == 0, either Kerberos or local authentication
650 * succeeded.
651 */
652 if (rval) {
653 reply(530, rval == 2 ? "Password expired." :
654 "Login incorrect.");
655 if (logging) {
656 syslog(LOG_NOTICE,
657 "FTP LOGIN FAILED FROM %s", remotehost);
658 syslog(LOG_AUTHPRIV | LOG_NOTICE,
659 "FTP LOGIN FAILED FROM %s, %s",
660 remotehost, curname);
661 }
662 pw = NULL;
663 if (login_attempts++ >= 5) {
664 syslog(LOG_NOTICE,
665 "repeated login failures from %s",
666 remotehost);
667 exit(0);
668 }
669 return;
670 }
671 }
672
673 /* password was ok; see if anything else prevents login */
674 if (checkaccess(pw->pw_name)) {
675 reply(530, "User %s may not use FTP.", pw->pw_name);
676 if (logging)
677 syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
678 remotehost, pw->pw_name);
679 pw = (struct passwd *) NULL;
680 return;
681 }
682 /* check for valid shell, if not guest user */
683 if ((shell = pw->pw_shell) == NULL || *shell == 0)
684 shell = _PATH_BSHELL;
685 while ((cp = getusershell()) != NULL)
686 if (strcmp(cp, shell) == 0)
687 break;
688 endusershell();
689 if (cp == NULL && guest == 0) {
690 reply(530, "User %s may not use FTP.", pw->pw_name);
691 if (logging)
692 syslog(LOG_NOTICE,
693 "FTP LOGIN REFUSED FROM %s, %s",
694 remotehost, pw->pw_name);
695 pw = (struct passwd *) NULL;
696 return;
697 }
698
699 login_attempts = 0; /* this time successful */
700 if (setegid((gid_t)pw->pw_gid) < 0) {
701 reply(550, "Can't set gid.");
702 return;
703 }
704 (void) initgroups(pw->pw_name, pw->pw_gid);
705
706 /* open wtmp before chroot */
707 logwtmp(ttyline, pw->pw_name, remotehost);
708 logged_in = 1;
709
710 dochroot = checkuser(conffilename(_PATH_FTPCHROOT), pw->pw_name);
711
712 /* parse ftpd.conf, setting up various parameters */
713 if (guest)
714 parse_conf(CLASS_GUEST);
715 else if (dochroot)
716 parse_conf(CLASS_CHROOT);
717 else
718 parse_conf(CLASS_REAL);
719
720 home = "/";
721 if (guest) {
722 /*
723 * We MUST do a chdir() after the chroot. Otherwise
724 * the old current directory will be accessible as "."
725 * outside the new root!
726 */
727 if (chroot(anondir ? anondir : pw->pw_dir) < 0 ||
728 chdir("/") < 0) {
729 reply(550, "Can't set guest privileges.");
730 goto bad;
731 }
732 } else if (dochroot) {
733 if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
734 reply(550, "Can't change root.");
735 goto bad;
736 }
737 } else if (chdir(pw->pw_dir) < 0) {
738 if (chdir("/") < 0) {
739 reply(530, "User %s: can't change directory to %s.",
740 pw->pw_name, pw->pw_dir);
741 goto bad;
742 } else
743 lreply(230, "No directory! Logging in with home=/");
744 } else
745 home = pw->pw_dir;
746 if (seteuid((uid_t)pw->pw_uid) < 0) {
747 reply(550, "Can't set uid.");
748 goto bad;
749 }
750 setenv("HOME", home, 1);
751
752
753 /*
754 * Display a login message, if it exists.
755 * N.B. reply(230,) must follow the message.
756 */
757 if ((fd = fopen(conffilename(_PATH_FTPLOGINMESG), "r")) != NULL) {
758 char *cp, line[LINE_MAX];
759
760 while (fgets(line, sizeof(line), fd) != NULL) {
761 if ((cp = strchr(line, '\n')) != NULL)
762 *cp = '\0';
763 lreply(230, "%s", line);
764 }
765 (void) fflush(stdout);
766 (void) fclose(fd);
767 }
768 show_chdir_messages(230);
769 if (guest) {
770 reply(230, "Guest login ok, access restrictions apply.");
771 #ifdef HASSETPROCTITLE
772 snprintf(proctitle, sizeof(proctitle),
773 "%s: anonymous/%.*s", remotehost,
774 (int) (sizeof(proctitle) - sizeof(remotehost) -
775 sizeof(": anonymous/")), passwd);
776 setproctitle(proctitle);
777 #endif /* HASSETPROCTITLE */
778 if (logging)
779 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
780 remotehost, passwd);
781 } else {
782 reply(230, "User %s logged in.", pw->pw_name);
783 #ifdef HASSETPROCTITLE
784 snprintf(proctitle, sizeof(proctitle),
785 "%s: %s", remotehost, pw->pw_name);
786 setproctitle(proctitle);
787 #endif /* HASSETPROCTITLE */
788 if (logging)
789 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
790 remotehost, pw->pw_name);
791 }
792 (void) umask(curclass.umask);
793 return;
794 bad:
795 /* Forget all about it... */
796 end_login();
797 }
798
799 void
800 retrieve(cmd, name)
801 char *cmd, *name;
802 {
803 FILE *fin = NULL, *dout;
804 struct stat st;
805 int (*closefunc) __P((FILE *)) = NULL;
806 int log;
807
808 log = (cmd == 0);
809 if (cmd == 0) {
810 fin = fopen(name, "r"), closefunc = fclose;
811 if (fin == NULL)
812 cmd = do_conversion(name);
813 }
814 if (cmd) {
815 char line[BUFSIZ];
816
817 (void)snprintf(line, sizeof(line), cmd, name), name = line;
818 fin = ftpd_popen(line, "r", 1), closefunc = ftpd_pclose;
819 st.st_size = -1;
820 st.st_blksize = BUFSIZ;
821 }
822 if (fin == NULL) {
823 if (errno != 0) {
824 perror_reply(550, name);
825 if (log) {
826 LOGCMD("get", name);
827 }
828 }
829 return;
830 }
831 byte_count = -1;
832 if (cmd == 0 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
833 reply(550, "%s: not a plain file.", name);
834 goto done;
835 }
836 if (restart_point) {
837 if (type == TYPE_A) {
838 off_t i, n;
839 int c;
840
841 n = restart_point;
842 i = 0;
843 while (i++ < n) {
844 if ((c=getc(fin)) == EOF) {
845 perror_reply(550, name);
846 goto done;
847 }
848 if (c == '\n')
849 i++;
850 }
851 } else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
852 perror_reply(550, name);
853 goto done;
854 }
855 }
856 dout = dataconn(name, st.st_size, "w");
857 if (dout == NULL)
858 goto done;
859 send_data(fin, dout, st.st_blksize);
860 (void) fclose(dout);
861 data = -1;
862 pdata = -1;
863 done:
864 if (log)
865 LOGBYTES("get", name, byte_count);
866 (*closefunc)(fin);
867 }
868
869 void
870 store(name, mode, unique)
871 char *name, *mode;
872 int unique;
873 {
874 FILE *fout, *din;
875 struct stat st;
876 int (*closefunc) __P((FILE *));
877
878 if (unique && stat(name, &st) == 0 &&
879 (name = gunique(name)) == NULL) {
880 LOGCMD(*mode == 'w' ? "put" : "append", name);
881 return;
882 }
883
884 if (restart_point)
885 mode = "r+";
886 fout = fopen(name, mode);
887 closefunc = fclose;
888 if (fout == NULL) {
889 perror_reply(553, name);
890 LOGCMD(*mode == 'w' ? "put" : "append", name);
891 return;
892 }
893 byte_count = -1;
894 if (restart_point) {
895 if (type == TYPE_A) {
896 off_t i, n;
897 int c;
898
899 n = restart_point;
900 i = 0;
901 while (i++ < n) {
902 if ((c=getc(fout)) == EOF) {
903 perror_reply(550, name);
904 goto done;
905 }
906 if (c == '\n')
907 i++;
908 }
909 /*
910 * We must do this seek to "current" position
911 * because we are changing from reading to
912 * writing.
913 */
914 if (fseek(fout, 0L, SEEK_CUR) < 0) {
915 perror_reply(550, name);
916 goto done;
917 }
918 } else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
919 perror_reply(550, name);
920 goto done;
921 }
922 }
923 din = dataconn(name, (off_t)-1, "r");
924 if (din == NULL)
925 goto done;
926 if (receive_data(din, fout) == 0) {
927 if (unique)
928 reply(226, "Transfer complete (unique file name:%s).",
929 name);
930 else
931 reply(226, "Transfer complete.");
932 }
933 (void) fclose(din);
934 data = -1;
935 pdata = -1;
936 done:
937 LOGBYTES(*mode == 'w' ? "put" : "append", name, byte_count);
938 (*closefunc)(fout);
939 }
940
941 static FILE *
942 getdatasock(mode)
943 char *mode;
944 {
945 int on = 1, s, t, tries;
946
947 if (data >= 0)
948 return (fdopen(data, mode));
949 (void) seteuid((uid_t)0);
950 s = socket(AF_INET, SOCK_STREAM, 0);
951 if (s < 0)
952 goto bad;
953 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
954 (char *) &on, sizeof(on)) < 0)
955 goto bad;
956 /* anchor socket to avoid multi-homing problems */
957 data_source.sin_len = sizeof(struct sockaddr_in);
958 data_source.sin_family = AF_INET;
959 data_source.sin_addr = ctrl_addr.sin_addr;
960 for (tries = 1; ; tries++) {
961 if (bind(s, (struct sockaddr *)&data_source,
962 sizeof(data_source)) >= 0)
963 break;
964 if (errno != EADDRINUSE || tries > 10)
965 goto bad;
966 sleep(tries);
967 }
968 (void) seteuid((uid_t)pw->pw_uid);
969 #ifdef IP_TOS
970 on = IPTOS_THROUGHPUT;
971 if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on, sizeof(int)) < 0)
972 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
973 #endif
974 return (fdopen(s, mode));
975 bad:
976 /* Return the real value of errno (close may change it) */
977 t = errno;
978 (void) seteuid((uid_t)pw->pw_uid);
979 (void) close(s);
980 errno = t;
981 return (NULL);
982 }
983
984 static FILE *
985 dataconn(name, size, mode)
986 char *name;
987 off_t size;
988 char *mode;
989 {
990 char sizebuf[32];
991 FILE *file;
992 int retry = 0, tos;
993
994 file_size = size;
995 byte_count = 0;
996 if (size != (off_t) -1)
997 (void)snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)",
998 (long long)size);
999 else
1000 sizebuf[0] = '\0';
1001 if (pdata >= 0) {
1002 struct sockaddr_in from;
1003 int s, fromlen = sizeof(from);
1004
1005 (void) alarm(curclass.timeout);
1006 s = accept(pdata, (struct sockaddr *)&from, &fromlen);
1007 (void) alarm(0);
1008 if (s < 0) {
1009 reply(425, "Can't open data connection.");
1010 (void) close(pdata);
1011 pdata = -1;
1012 return (NULL);
1013 }
1014 (void) close(pdata);
1015 pdata = s;
1016 #ifdef IP_TOS
1017 tos = IPTOS_THROUGHPUT;
1018 (void) setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&tos,
1019 sizeof(int));
1020 #endif
1021 reply(150, "Opening %s mode data connection for '%s'%s.",
1022 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1023 return (fdopen(pdata, mode));
1024 }
1025 if (data >= 0) {
1026 reply(125, "Using existing data connection for '%s'%s.",
1027 name, sizebuf);
1028 usedefault = 1;
1029 return (fdopen(data, mode));
1030 }
1031 if (usedefault)
1032 data_dest = his_addr;
1033 usedefault = 1;
1034 file = getdatasock(mode);
1035 if (file == NULL) {
1036 reply(425, "Can't create data socket (%s,%d): %s.",
1037 inet_ntoa(data_source.sin_addr),
1038 ntohs(data_source.sin_port), strerror(errno));
1039 return (NULL);
1040 }
1041 data = fileno(file);
1042 while (connect(data, (struct sockaddr *)&data_dest,
1043 sizeof(data_dest)) < 0) {
1044 if (errno == EADDRINUSE && retry < swaitmax) {
1045 sleep((unsigned) swaitint);
1046 retry += swaitint;
1047 continue;
1048 }
1049 perror_reply(425, "Can't build data connection");
1050 (void) fclose(file);
1051 data = -1;
1052 return (NULL);
1053 }
1054 reply(150, "Opening %s mode data connection for '%s'%s.",
1055 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1056 return (file);
1057 }
1058
1059 /*
1060 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1061 * encapsulation of the data subject * to Mode, Structure, and Type.
1062 *
1063 * NB: Form isn't handled.
1064 */
1065 static void
1066 send_data(instr, outstr, blksize)
1067 FILE *instr, *outstr;
1068 off_t blksize;
1069 {
1070 int c, cnt, filefd, netfd;
1071 char *buf;
1072
1073 transflag++;
1074 if (setjmp(urgcatch)) {
1075 transflag = 0;
1076 return;
1077 }
1078
1079 switch (type) {
1080
1081 case TYPE_A:
1082 while ((c = getc(instr)) != EOF) {
1083 byte_count++;
1084 if (c == '\n') {
1085 if (ferror(outstr))
1086 goto data_err;
1087 (void) putc('\r', outstr);
1088 }
1089 (void) putc(c, outstr);
1090 }
1091 fflush(outstr);
1092 transflag = 0;
1093 if (ferror(instr))
1094 goto file_err;
1095 if (ferror(outstr))
1096 goto data_err;
1097 reply(226, "Transfer complete.");
1098 return;
1099
1100 case TYPE_I:
1101 case TYPE_L:
1102 if ((buf = malloc((u_int)blksize)) == NULL) {
1103 transflag = 0;
1104 perror_reply(451, "Local resource failure: malloc");
1105 return;
1106 }
1107 netfd = fileno(outstr);
1108 filefd = fileno(instr);
1109 while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
1110 write(netfd, buf, cnt) == cnt)
1111 byte_count += cnt;
1112 transflag = 0;
1113 (void)free(buf);
1114 if (cnt != 0) {
1115 if (cnt < 0)
1116 goto file_err;
1117 goto data_err;
1118 }
1119 reply(226, "Transfer complete.");
1120 return;
1121 default:
1122 transflag = 0;
1123 reply(550, "Unimplemented TYPE %d in send_data", type);
1124 return;
1125 }
1126
1127 data_err:
1128 transflag = 0;
1129 perror_reply(426, "Data connection");
1130 return;
1131
1132 file_err:
1133 transflag = 0;
1134 perror_reply(551, "Error on input file");
1135 }
1136
1137 /*
1138 * Transfer data from peer to "outstr" using the appropriate encapulation of
1139 * the data subject to Mode, Structure, and Type.
1140 *
1141 * N.B.: Form isn't handled.
1142 */
1143 static int
1144 receive_data(instr, outstr)
1145 FILE *instr, *outstr;
1146 {
1147 int c, cnt, bare_lfs;
1148 char buf[BUFSIZ];
1149 #ifdef __GNUC__
1150 (void) &bare_lfs;
1151 #endif
1152
1153 bare_lfs = 0;
1154 transflag++;
1155 if (setjmp(urgcatch)) {
1156 transflag = 0;
1157 return (-1);
1158 }
1159
1160 switch (type) {
1161
1162 case TYPE_I:
1163 case TYPE_L:
1164 while ((cnt = read(fileno(instr), buf, sizeof(buf))) > 0) {
1165 if (write(fileno(outstr), buf, cnt) != cnt)
1166 goto file_err;
1167 byte_count += cnt;
1168 }
1169 if (cnt < 0)
1170 goto data_err;
1171 transflag = 0;
1172 return (0);
1173
1174 case TYPE_E:
1175 reply(553, "TYPE E not implemented.");
1176 transflag = 0;
1177 return (-1);
1178
1179 case TYPE_A:
1180 while ((c = getc(instr)) != EOF) {
1181 byte_count++;
1182 if (c == '\n')
1183 bare_lfs++;
1184 while (c == '\r') {
1185 if (ferror(outstr))
1186 goto data_err;
1187 if ((c = getc(instr)) != '\n') {
1188 (void) putc ('\r', outstr);
1189 if (c == '\0' || c == EOF)
1190 goto contin2;
1191 }
1192 }
1193 (void) putc(c, outstr);
1194 contin2: ;
1195 }
1196 fflush(outstr);
1197 if (ferror(instr))
1198 goto data_err;
1199 if (ferror(outstr))
1200 goto file_err;
1201 transflag = 0;
1202 if (bare_lfs) {
1203 lreply(226,
1204 "WARNING! %d bare linefeeds received in ASCII mode",
1205 bare_lfs);
1206 (void)printf(" File may not have transferred correctly.\r\n");
1207 }
1208 return (0);
1209 default:
1210 reply(550, "Unimplemented TYPE %d in receive_data", type);
1211 transflag = 0;
1212 return (-1);
1213 }
1214
1215 data_err:
1216 transflag = 0;
1217 perror_reply(426, "Data Connection");
1218 return (-1);
1219
1220 file_err:
1221 transflag = 0;
1222 perror_reply(452, "Error writing file");
1223 return (-1);
1224 }
1225
1226 void
1227 statfilecmd(filename)
1228 char *filename;
1229 {
1230 FILE *fin;
1231 int c;
1232 char line[LINE_MAX];
1233
1234 (void)snprintf(line, sizeof(line), "/bin/ls -lgA %s", filename);
1235 fin = ftpd_popen(line, "r", 0);
1236 lreply(211, "status of %s:", filename);
1237 while ((c = getc(fin)) != EOF) {
1238 if (c == '\n') {
1239 if (ferror(stdout)){
1240 perror_reply(421, "control connection");
1241 (void) ftpd_pclose(fin);
1242 dologout(1);
1243 /* NOTREACHED */
1244 }
1245 if (ferror(fin)) {
1246 perror_reply(551, filename);
1247 (void) ftpd_pclose(fin);
1248 return;
1249 }
1250 (void) putc('\r', stdout);
1251 }
1252 (void) putc(c, stdout);
1253 }
1254 (void) ftpd_pclose(fin);
1255 reply(211, "End of Status");
1256 }
1257
1258 void
1259 statcmd()
1260 {
1261 struct sockaddr_in *sin;
1262 u_char *a, *p;
1263
1264 lreply(211, "%s FTP server status:", hostname);
1265 lreply(211, "%s", version);
1266 if (isdigit(remotehost[0]))
1267 lreply(211, "Connected to %s", remotehost);
1268 else
1269 lreply(211, "Connected to %s (%s)", remotehost,
1270 inet_ntoa(his_addr.sin_addr));
1271 if (logged_in) {
1272 if (guest)
1273 lreply(211, "Logged in anonymously");
1274 else
1275 lreply(211, "Logged in as %s", pw->pw_name);
1276 } else if (askpasswd)
1277 lreply(211, "Waiting for password");
1278 else
1279 lreply(211, "Waiting for user name");
1280 printf("211- TYPE: %s", typenames[type]);
1281 if (type == TYPE_A || type == TYPE_E)
1282 printf(", FORM: %s", formnames[form]);
1283 if (type == TYPE_L)
1284 #if NBBY == 8
1285 printf(" %d", NBBY);
1286 #else
1287 printf(" %d", bytesize); /* need definition! */
1288 #endif
1289 printf("; STRUcture: %s; transfer MODE: %s\r\n",
1290 strunames[stru], modenames[mode]);
1291 if (data != -1)
1292 lreply(211, "Data connection open");
1293 else if (pdata != -1) {
1294 printf("211- in Passive mode");
1295 sin = &pasv_addr;
1296 goto printaddr;
1297 } else if (usedefault == 0) {
1298 printf("211- PORT");
1299 sin = &data_dest;
1300 printaddr:
1301 a = (u_char *) &sin->sin_addr;
1302 p = (u_char *) &sin->sin_port;
1303 #define UC(b) (((int) b) & 0xff)
1304 printf(" (%d,%d,%d,%d,%d,%d)\r\n", UC(a[0]),
1305 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
1306 #undef UC
1307 } else
1308 lreply(211, "No data connection");
1309
1310 if (logged_in) {
1311 struct ftpconv *cp;
1312
1313 lreply(211, "");
1314 lreply(211, "Class: %s", curclass.classname);
1315 lreply(211, "Check PORT commands: %sabled",
1316 curclass.checkportcmd ? "en" : "dis");
1317 if (curclass.display)
1318 lreply(211, "Display file: %s", curclass.display);
1319 if (curclass.notify)
1320 lreply(211, "Notify fileglob: %s", curclass.notify);
1321 lreply(211, "Idle timeout: %d, maximum timeout: %d",
1322 curclass.timeout, curclass.maxtimeout);
1323 lreply(211, "DELE, MKD, RMD, UMASK, CHMOD commands: %sabled",
1324 curclass.modify ? "en" : "dis");
1325 lreply(211, "Umask: %.04o", curclass.umask);
1326 for (cp = curclass.conversions; cp != NULL; cp=cp->next) {
1327 if (cp->suffix == NULL || cp->types == NULL ||
1328 cp->command == NULL)
1329 continue;
1330 lreply(211,
1331 "Conversion: %s [%s] disable: %s, command: %s",
1332 cp->suffix, cp->types, cp->disable, cp->command);
1333 }
1334 }
1335
1336 reply(211, "End of status");
1337 }
1338
1339 void
1340 fatal(s)
1341 char *s;
1342 {
1343
1344 reply(451, "Error in server: %s\n", s);
1345 reply(221, "Closing connection due to server error.");
1346 dologout(0);
1347 /* NOTREACHED */
1348 }
1349
1350 void
1351 #ifdef __STDC__
1352 reply(int n, const char *fmt, ...)
1353 #else
1354 reply(n, fmt, va_alist)
1355 int n;
1356 char *fmt;
1357 va_dcl
1358 #endif
1359 {
1360 va_list ap;
1361 #ifdef __STDC__
1362 va_start(ap, fmt);
1363 #else
1364 va_start(ap);
1365 #endif
1366 (void)printf("%d ", n);
1367 (void)vprintf(fmt, ap);
1368 (void)printf("\r\n");
1369 (void)fflush(stdout);
1370 if (debug) {
1371 syslog(LOG_DEBUG, "<--- %d ", n);
1372 vsyslog(LOG_DEBUG, fmt, ap);
1373 }
1374 }
1375
1376 void
1377 #ifdef __STDC__
1378 lreply(int n, const char *fmt, ...)
1379 #else
1380 lreply(n, fmt, va_alist)
1381 int n;
1382 char *fmt;
1383 va_dcl
1384 #endif
1385 {
1386 va_list ap;
1387 #ifdef __STDC__
1388 va_start(ap, fmt);
1389 #else
1390 va_start(ap);
1391 #endif
1392 (void)printf("%d- ", n);
1393 (void)vprintf(fmt, ap);
1394 (void)printf("\r\n");
1395 (void)fflush(stdout);
1396 if (debug) {
1397 syslog(LOG_DEBUG, "<--- %d- ", n);
1398 vsyslog(LOG_DEBUG, fmt, ap);
1399 }
1400 }
1401
1402 static void
1403 ack(s)
1404 char *s;
1405 {
1406
1407 reply(250, "%s command successful.", s);
1408 }
1409
1410 void
1411 nack(s)
1412 char *s;
1413 {
1414
1415 reply(502, "%s command not implemented.", s);
1416 }
1417
1418 /* ARGSUSED */
1419 void
1420 yyerror(s)
1421 char *s;
1422 {
1423 char *cp;
1424
1425 if ((cp = strchr(cbuf,'\n')) != NULL)
1426 *cp = '\0';
1427 reply(500, "'%s': command not understood.", cbuf);
1428 }
1429
1430 void
1431 delete(name)
1432 char *name;
1433 {
1434
1435 LOGCMD("delete", name);
1436 if (remove(name) < 0)
1437 perror_reply(550, name);
1438 else
1439 ack("DELE");
1440 }
1441
1442 void
1443 cwd(path)
1444 char *path;
1445 {
1446
1447 if (chdir(path) < 0)
1448 perror_reply(550, path);
1449 else {
1450 show_chdir_messages(250);
1451 ack("CWD");
1452 }
1453 }
1454
1455 static void
1456 replydirname(name, message)
1457 const char *name, *message;
1458 {
1459 char npath[MAXPATHLEN + 1];
1460 int i;
1461
1462 for (i = 0; *name != '\0' && i < sizeof(npath) - 1; i++, name++) {
1463 npath[i] = *name;
1464 if (*name == '"')
1465 npath[++i] = '"';
1466 }
1467 npath[i] = '\0';
1468 reply(257, "\"%s\" %s", npath, message);
1469 }
1470
1471 void
1472 makedir(name)
1473 char *name;
1474 {
1475
1476 LOGCMD("mkdir", name);
1477 if (mkdir(name, 0777) < 0)
1478 perror_reply(550, name);
1479 else
1480 replydirname(name, "directory created.");
1481 }
1482
1483 void
1484 removedir(name)
1485 char *name;
1486 {
1487
1488 LOGCMD("rmdir", name);
1489 if (rmdir(name) < 0)
1490 perror_reply(550, name);
1491 else
1492 ack("RMD");
1493 }
1494
1495 void
1496 pwd()
1497 {
1498 char path[MAXPATHLEN + 1];
1499
1500 if (getcwd(path, sizeof(path) - 1) == NULL)
1501 reply(550, "%s.", path);
1502 else
1503 replydirname(path, "is the current directory.");
1504 }
1505
1506 char *
1507 renamefrom(name)
1508 char *name;
1509 {
1510 struct stat st;
1511
1512 if (stat(name, &st) < 0) {
1513 perror_reply(550, name);
1514 return ((char *)0);
1515 }
1516 reply(350, "File exists, ready for destination name");
1517 return (name);
1518 }
1519
1520 void
1521 renamecmd(from, to)
1522 char *from, *to;
1523 {
1524
1525 LOGCMD2("rename", from, to);
1526 if (rename(from, to) < 0)
1527 perror_reply(550, "rename");
1528 else
1529 ack("RNTO");
1530 }
1531
1532 static void
1533 dolog(sin)
1534 struct sockaddr_in *sin;
1535 {
1536 struct hostent *hp = gethostbyaddr((char *)&sin->sin_addr,
1537 sizeof(struct in_addr), AF_INET);
1538
1539 if (hp)
1540 (void) strncpy(remotehost, hp->h_name, sizeof(remotehost));
1541 else
1542 (void) strncpy(remotehost, inet_ntoa(sin->sin_addr),
1543 sizeof(remotehost));
1544 #ifdef HASSETPROCTITLE
1545 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
1546 setproctitle(proctitle);
1547 #endif /* HASSETPROCTITLE */
1548
1549 if (logging)
1550 syslog(LOG_INFO, "connection from %s", remotehost);
1551 }
1552
1553 /*
1554 * Record logout in wtmp file
1555 * and exit with supplied status.
1556 */
1557 void
1558 dologout(status)
1559 int status;
1560 {
1561 /*
1562 * Prevent reception of SIGURG from resulting in a resumption
1563 * back to the main program loop.
1564 */
1565 transflag = 0;
1566
1567 if (logged_in) {
1568 (void) seteuid((uid_t)0);
1569 logwtmp(ttyline, "", "");
1570 #ifdef KERBEROS
1571 if (!notickets && krbtkfile_env)
1572 unlink(krbtkfile_env);
1573 #endif
1574 }
1575 /* beware of flushing buffers after a SIGPIPE */
1576 _exit(status);
1577 }
1578
1579 static void
1580 myoob(signo)
1581 int signo;
1582 {
1583 char *cp;
1584
1585 /* only process if transfer occurring */
1586 if (!transflag)
1587 return;
1588 cp = tmpline;
1589 if (getline(cp, 7, stdin) == NULL) {
1590 reply(221, "You could at least say goodbye.");
1591 dologout(0);
1592 }
1593 upper(cp);
1594 if (strcmp(cp, "ABOR\r\n") == 0) {
1595 tmpline[0] = '\0';
1596 reply(426, "Transfer aborted. Data connection closed.");
1597 reply(226, "Abort successful");
1598 longjmp(urgcatch, 1);
1599 }
1600 if (strcmp(cp, "STAT\r\n") == 0) {
1601 if (file_size != (off_t) -1)
1602 reply(213, "Status: %qd of %qd bytes transferred",
1603 byte_count, file_size);
1604 else
1605 reply(213, "Status: %qd bytes transferred", byte_count);
1606 }
1607 }
1608
1609 /*
1610 * Note: a response of 425 is not mentioned as a possible response to
1611 * the PASV command in RFC959. However, it has been blessed as
1612 * a legitimate response by Jon Postel in a telephone conversation
1613 * with Rick Adams on 25 Jan 89.
1614 */
1615 void
1616 passive()
1617 {
1618 int len;
1619 char *p, *a;
1620
1621 pdata = socket(AF_INET, SOCK_STREAM, 0);
1622 if (pdata < 0 || !logged_in) {
1623 perror_reply(425, "Can't open passive connection");
1624 return;
1625 }
1626 pasv_addr = ctrl_addr;
1627 pasv_addr.sin_port = 0;
1628 (void) seteuid((uid_t)0);
1629 if (bind(pdata, (struct sockaddr *)&pasv_addr, sizeof(pasv_addr)) < 0) {
1630 (void) seteuid((uid_t)pw->pw_uid);
1631 goto pasv_error;
1632 }
1633 (void) seteuid((uid_t)pw->pw_uid);
1634 len = sizeof(pasv_addr);
1635 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
1636 goto pasv_error;
1637 if (listen(pdata, 1) < 0)
1638 goto pasv_error;
1639 a = (char *) &pasv_addr.sin_addr;
1640 p = (char *) &pasv_addr.sin_port;
1641
1642 #define UC(b) (((int) b) & 0xff)
1643
1644 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
1645 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
1646 return;
1647
1648 pasv_error:
1649 (void) close(pdata);
1650 pdata = -1;
1651 perror_reply(425, "Can't open passive connection");
1652 return;
1653 }
1654
1655 /*
1656 * Generate unique name for file with basename "local".
1657 * The file named "local" is already known to exist.
1658 * Generates failure reply on error.
1659 *
1660 * XXX this function should under go changes similar to
1661 * the mktemp(3)/mkstemp(3) changes.
1662 */
1663 static char *
1664 gunique(local)
1665 char *local;
1666 {
1667 static char new[MAXPATHLEN];
1668 struct stat st;
1669 int count, len;
1670 char *cp;
1671
1672 cp = strrchr(local, '/');
1673 if (cp)
1674 *cp = '\0';
1675 if (stat(cp ? local : ".", &st) < 0) {
1676 perror_reply(553, cp ? local : ".");
1677 return ((char *) 0);
1678 }
1679 if (cp)
1680 *cp = '/';
1681 (void) strcpy(new, local);
1682 len = strlen(new);
1683 cp = new + len;
1684 *cp++ = '.';
1685 for (count = 1; count < 100; count++) {
1686 (void)snprintf(cp, sizeof(new) - len - 2, "%d", count);
1687 if (stat(new, &st) < 0)
1688 return (new);
1689 }
1690 reply(452, "Unique file name cannot be created.");
1691 return (NULL);
1692 }
1693
1694 /*
1695 * Format and send reply containing system error number.
1696 */
1697 void
1698 perror_reply(code, string)
1699 int code;
1700 char *string;
1701 {
1702
1703 reply(code, "%s: %s.", string, strerror(errno));
1704 }
1705
1706 static char *onefile[] = {
1707 "",
1708 0
1709 };
1710
1711 void
1712 send_file_list(whichf)
1713 char *whichf;
1714 {
1715 struct stat st;
1716 DIR *dirp = NULL;
1717 struct dirent *dir;
1718 FILE *dout = NULL;
1719 char **dirlist, *dirname;
1720 int simple = 0;
1721 int freeglob = 0;
1722 glob_t gl;
1723 #ifdef __GNUC__
1724 (void) &dout;
1725 (void) &dirlist;
1726 (void) &simple;
1727 (void) &freeglob;
1728 #endif
1729
1730 if (strpbrk(whichf, "~{[*?") != NULL) {
1731 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
1732
1733 memset(&gl, 0, sizeof(gl));
1734 freeglob = 1;
1735 if (glob(whichf, flags, 0, &gl)) {
1736 reply(550, "not found");
1737 goto out;
1738 } else if (gl.gl_pathc == 0) {
1739 errno = ENOENT;
1740 perror_reply(550, whichf);
1741 goto out;
1742 }
1743 dirlist = gl.gl_pathv;
1744 } else {
1745 onefile[0] = whichf;
1746 dirlist = onefile;
1747 simple = 1;
1748 }
1749
1750 if (setjmp(urgcatch)) {
1751 transflag = 0;
1752 goto out;
1753 }
1754 while ((dirname = *dirlist++) != NULL) {
1755 int trailingslash = 0;
1756
1757 if (stat(dirname, &st) < 0) {
1758 /*
1759 * If user typed "ls -l", etc, and the client
1760 * used NLST, do what the user meant.
1761 */
1762 if (dirname[0] == '-' && *dirlist == NULL &&
1763 transflag == 0) {
1764 retrieve("/bin/ls %s", dirname);
1765 goto out;
1766 }
1767 perror_reply(550, whichf);
1768 if (dout != NULL) {
1769 (void) fclose(dout);
1770 transflag = 0;
1771 data = -1;
1772 pdata = -1;
1773 }
1774 goto out;
1775 }
1776
1777 if (S_ISREG(st.st_mode)) {
1778 if (dout == NULL) {
1779 dout = dataconn("file list", (off_t)-1, "w");
1780 if (dout == NULL)
1781 goto out;
1782 transflag++;
1783 }
1784 fprintf(dout, "%s%s\n", dirname,
1785 type == TYPE_A ? "\r" : "");
1786 byte_count += strlen(dirname) + 1;
1787 continue;
1788 } else if (!S_ISDIR(st.st_mode))
1789 continue;
1790
1791 if (dirname[strlen(dirname) - 1] == '/')
1792 trailingslash++;
1793
1794 if ((dirp = opendir(dirname)) == NULL)
1795 continue;
1796
1797 while ((dir = readdir(dirp)) != NULL) {
1798 char nbuf[MAXPATHLEN];
1799
1800 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
1801 continue;
1802 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
1803 dir->d_namlen == 2)
1804 continue;
1805
1806 (void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
1807 trailingslash ? "" : "/", dir->d_name);
1808
1809 /*
1810 * We have to do a stat to ensure it's
1811 * not a directory or special file.
1812 */
1813 if (simple || (stat(nbuf, &st) == 0 &&
1814 S_ISREG(st.st_mode))) {
1815 if (dout == NULL) {
1816 dout = dataconn("file list", (off_t)-1,
1817 "w");
1818 if (dout == NULL)
1819 goto out;
1820 transflag++;
1821 }
1822 if (nbuf[0] == '.' && nbuf[1] == '/')
1823 fprintf(dout, "%s%s\n", &nbuf[2],
1824 type == TYPE_A ? "\r" : "");
1825 else
1826 fprintf(dout, "%s%s\n", nbuf,
1827 type == TYPE_A ? "\r" : "");
1828 byte_count += strlen(nbuf) + 1;
1829 }
1830 }
1831 (void) closedir(dirp);
1832 }
1833
1834 if (dout == NULL)
1835 reply(550, "No files found.");
1836 else if (ferror(dout) != 0)
1837 perror_reply(550, "Data connection");
1838 else
1839 reply(226, "Transfer complete.");
1840
1841 transflag = 0;
1842 if (dout != NULL)
1843 (void) fclose(dout);
1844 data = -1;
1845 pdata = -1;
1846 out:
1847 if (freeglob) {
1848 freeglob = 0;
1849 globfree(&gl);
1850 }
1851 }
1852
1853 char *
1854 conffilename(s)
1855 const char *s;
1856 {
1857 static char filename[MAXPATHLEN];
1858
1859 (void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
1860 return filename;
1861 }
1862