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