ftpd.c revision 1.40 1 /* $NetBSD: ftpd.c,v 1.40 1997/11/11 06:32:17 mrg 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.40 1997/11/11 06:32:17 mrg 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 *[], 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, envp)
225 int argc;
226 char *argv[];
227 char **envp;
228 {
229 int addrlen, ch, on = 1, tos;
230 char *cp, line[LINE_MAX];
231 FILE *fd;
232 #ifdef KERBEROS5
233 krb5_error_code kerror;
234 #endif
235
236 debug = 0;
237 logging = 0;
238 (void)strcpy(confdir, _DEFAULT_CONFDIR);
239
240 while ((ch = getopt(argc, argv, "a:c:C:dlt:T:u:v")) != -1) {
241 switch (ch) {
242 case 'a':
243 anondir = optarg;
244 break;
245
246 case 'c':
247 (void)strncpy(confdir, optarg, sizeof(confdir));
248 confdir[sizeof(confdir)-1] = '\0';
249 break;
250
251 case 'C':
252 exit(checkaccess(optarg));
253 /* NOTREACHED */
254
255 case 'd':
256 case 'v': /* deprecated */
257 debug = 1;
258 break;
259
260 case 'l':
261 logging++; /* > 1 == extra logging */
262 break;
263
264 case 't':
265 case 'T':
266 case 'u':
267 warnx("-%c has been deprecated in favour of ftpd.conf",
268 ch);
269 break;
270
271 default:
272 if (optopt == 'a' || optopt == 'C')
273 exit(1);
274 warnx("unknown flag -%c ignored", optopt);
275 break;
276 }
277 }
278
279 /*
280 * LOG_NDELAY sets up the logging connection immediately,
281 * necessary for anonymous ftp's that chroot and can't do it later.
282 */
283 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
284 addrlen = sizeof(his_addr);
285 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
286 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
287 exit(1);
288 }
289 addrlen = sizeof(ctrl_addr);
290 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
291 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
292 exit(1);
293 }
294 #ifdef IP_TOS
295 tos = IPTOS_LOWDELAY;
296 if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(int)) < 0)
297 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
298 #endif
299 data_source.sin_port = htons(ntohs(ctrl_addr.sin_port) - 1);
300
301 /* set this here so klogin can use it... */
302 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
303
304 (void) freopen(_PATH_DEVNULL, "w", stderr);
305 (void) signal(SIGPIPE, lostconn);
306 (void) signal(SIGCHLD, SIG_IGN);
307 if ((long)signal(SIGURG, myoob) < 0)
308 syslog(LOG_ERR, "signal: %m");
309
310 /* Try to handle urgent data inline */
311 #ifdef SO_OOBINLINE
312 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
313 syslog(LOG_ERR, "setsockopt: %m");
314 #endif
315
316 #ifdef F_SETOWN
317 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
318 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
319 #endif
320 dolog(&his_addr);
321 /*
322 * Set up default state
323 */
324 data = -1;
325 type = TYPE_A;
326 form = FORM_N;
327 stru = STRU_F;
328 mode = MODE_S;
329 tmpline[0] = '\0';
330
331 #ifdef KERBEROS5
332 kerror = krb5_init_context(&kcontext);
333 if (kerror) {
334 syslog(LOG_NOTICE, "%s when initializing Kerberos context",
335 error_message(kerror));
336 exit(0);
337 }
338 #endif KERBEROS5
339
340 /* If logins are disabled, print out the message. */
341 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
342 while (fgets(line, sizeof(line), fd) != NULL) {
343 if ((cp = strchr(line, '\n')) != NULL)
344 *cp = '\0';
345 lreply(530, "%s", line);
346 }
347 (void) fflush(stdout);
348 (void) fclose(fd);
349 reply(530, "System not available.");
350 exit(0);
351 }
352 if ((fd = fopen(conffilename(_PATH_FTPWELCOME), "r")) != NULL) {
353 while (fgets(line, sizeof(line), fd) != NULL) {
354 if ((cp = strchr(line, '\n')) != NULL)
355 *cp = '\0';
356 lreply(220, "%s", line);
357 }
358 (void) fflush(stdout);
359 (void) fclose(fd);
360 /* reply(220,) must follow */
361 }
362 (void) gethostname(hostname, sizeof(hostname));
363 reply(220, "%s FTP server (%s) ready.", hostname, version);
364 (void) setjmp(errcatch);
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 s = accept(pdata, (struct sockaddr *)&from, &fromlen);
998 if (s < 0) {
999 reply(425, "Can't open data connection.");
1000 (void) close(pdata);
1001 pdata = -1;
1002 return (NULL);
1003 }
1004 (void) close(pdata);
1005 pdata = s;
1006 #ifdef IP_TOS
1007 tos = IPTOS_THROUGHPUT;
1008 (void) setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&tos,
1009 sizeof(int));
1010 #endif
1011 reply(150, "Opening %s mode data connection for '%s'%s.",
1012 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1013 return (fdopen(pdata, mode));
1014 }
1015 if (data >= 0) {
1016 reply(125, "Using existing data connection for '%s'%s.",
1017 name, sizebuf);
1018 usedefault = 1;
1019 return (fdopen(data, mode));
1020 }
1021 if (usedefault)
1022 data_dest = his_addr;
1023 usedefault = 1;
1024 file = getdatasock(mode);
1025 if (file == NULL) {
1026 reply(425, "Can't create data socket (%s,%d): %s.",
1027 inet_ntoa(data_source.sin_addr),
1028 ntohs(data_source.sin_port), strerror(errno));
1029 return (NULL);
1030 }
1031 data = fileno(file);
1032 while (connect(data, (struct sockaddr *)&data_dest,
1033 sizeof(data_dest)) < 0) {
1034 if (errno == EADDRINUSE && retry < swaitmax) {
1035 sleep((unsigned) swaitint);
1036 retry += swaitint;
1037 continue;
1038 }
1039 perror_reply(425, "Can't build data connection");
1040 (void) fclose(file);
1041 data = -1;
1042 return (NULL);
1043 }
1044 reply(150, "Opening %s mode data connection for '%s'%s.",
1045 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1046 return (file);
1047 }
1048
1049 /*
1050 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1051 * encapsulation of the data subject * to Mode, Structure, and Type.
1052 *
1053 * NB: Form isn't handled.
1054 */
1055 static void
1056 send_data(instr, outstr, blksize)
1057 FILE *instr, *outstr;
1058 off_t blksize;
1059 {
1060 int c, cnt, filefd, netfd;
1061 char *buf;
1062
1063 transflag++;
1064 if (setjmp(urgcatch)) {
1065 transflag = 0;
1066 return;
1067 }
1068
1069 switch (type) {
1070
1071 case TYPE_A:
1072 while ((c = getc(instr)) != EOF) {
1073 byte_count++;
1074 if (c == '\n') {
1075 if (ferror(outstr))
1076 goto data_err;
1077 (void) putc('\r', outstr);
1078 }
1079 (void) putc(c, outstr);
1080 }
1081 fflush(outstr);
1082 transflag = 0;
1083 if (ferror(instr))
1084 goto file_err;
1085 if (ferror(outstr))
1086 goto data_err;
1087 reply(226, "Transfer complete.");
1088 return;
1089
1090 case TYPE_I:
1091 case TYPE_L:
1092 if ((buf = malloc((u_int)blksize)) == NULL) {
1093 transflag = 0;
1094 perror_reply(451, "Local resource failure: malloc");
1095 return;
1096 }
1097 netfd = fileno(outstr);
1098 filefd = fileno(instr);
1099 while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
1100 write(netfd, buf, cnt) == cnt)
1101 byte_count += cnt;
1102 transflag = 0;
1103 (void)free(buf);
1104 if (cnt != 0) {
1105 if (cnt < 0)
1106 goto file_err;
1107 goto data_err;
1108 }
1109 reply(226, "Transfer complete.");
1110 return;
1111 default:
1112 transflag = 0;
1113 reply(550, "Unimplemented TYPE %d in send_data", type);
1114 return;
1115 }
1116
1117 data_err:
1118 transflag = 0;
1119 perror_reply(426, "Data connection");
1120 return;
1121
1122 file_err:
1123 transflag = 0;
1124 perror_reply(551, "Error on input file");
1125 }
1126
1127 /*
1128 * Transfer data from peer to "outstr" using the appropriate encapulation of
1129 * the data subject to Mode, Structure, and Type.
1130 *
1131 * N.B.: Form isn't handled.
1132 */
1133 static int
1134 receive_data(instr, outstr)
1135 FILE *instr, *outstr;
1136 {
1137 int c, cnt, bare_lfs;
1138 char buf[BUFSIZ];
1139 #ifdef __GNUC__
1140 (void) &bare_lfs;
1141 #endif
1142
1143 bare_lfs = 0;
1144 transflag++;
1145 if (setjmp(urgcatch)) {
1146 transflag = 0;
1147 return (-1);
1148 }
1149
1150 switch (type) {
1151
1152 case TYPE_I:
1153 case TYPE_L:
1154 while ((cnt = read(fileno(instr), buf, sizeof(buf))) > 0) {
1155 if (write(fileno(outstr), buf, cnt) != cnt)
1156 goto file_err;
1157 byte_count += cnt;
1158 }
1159 if (cnt < 0)
1160 goto data_err;
1161 transflag = 0;
1162 return (0);
1163
1164 case TYPE_E:
1165 reply(553, "TYPE E not implemented.");
1166 transflag = 0;
1167 return (-1);
1168
1169 case TYPE_A:
1170 while ((c = getc(instr)) != EOF) {
1171 byte_count++;
1172 if (c == '\n')
1173 bare_lfs++;
1174 while (c == '\r') {
1175 if (ferror(outstr))
1176 goto data_err;
1177 if ((c = getc(instr)) != '\n') {
1178 (void) putc ('\r', outstr);
1179 if (c == '\0' || c == EOF)
1180 goto contin2;
1181 }
1182 }
1183 (void) putc(c, outstr);
1184 contin2: ;
1185 }
1186 fflush(outstr);
1187 if (ferror(instr))
1188 goto data_err;
1189 if (ferror(outstr))
1190 goto file_err;
1191 transflag = 0;
1192 if (bare_lfs) {
1193 lreply(226,
1194 "WARNING! %d bare linefeeds received in ASCII mode",
1195 bare_lfs);
1196 (void)printf(" File may not have transferred correctly.\r\n");
1197 }
1198 return (0);
1199 default:
1200 reply(550, "Unimplemented TYPE %d in receive_data", type);
1201 transflag = 0;
1202 return (-1);
1203 }
1204
1205 data_err:
1206 transflag = 0;
1207 perror_reply(426, "Data Connection");
1208 return (-1);
1209
1210 file_err:
1211 transflag = 0;
1212 perror_reply(452, "Error writing file");
1213 return (-1);
1214 }
1215
1216 void
1217 statfilecmd(filename)
1218 char *filename;
1219 {
1220 FILE *fin;
1221 int c;
1222 char line[LINE_MAX];
1223
1224 (void)snprintf(line, sizeof(line), "/bin/ls -lgA %s", filename);
1225 fin = ftpd_popen(line, "r", 0);
1226 lreply(211, "status of %s:", filename);
1227 while ((c = getc(fin)) != EOF) {
1228 if (c == '\n') {
1229 if (ferror(stdout)){
1230 perror_reply(421, "control connection");
1231 (void) ftpd_pclose(fin);
1232 dologout(1);
1233 /* NOTREACHED */
1234 }
1235 if (ferror(fin)) {
1236 perror_reply(551, filename);
1237 (void) ftpd_pclose(fin);
1238 return;
1239 }
1240 (void) putc('\r', stdout);
1241 }
1242 (void) putc(c, stdout);
1243 }
1244 (void) ftpd_pclose(fin);
1245 reply(211, "End of Status");
1246 }
1247
1248 void
1249 statcmd()
1250 {
1251 struct sockaddr_in *sin;
1252 u_char *a, *p;
1253
1254 lreply(211, "%s FTP server status:", hostname);
1255 lreply(211, "%s", version);
1256 if (isdigit(remotehost[0]))
1257 lreply(211, "Connected to %s", remotehost);
1258 else
1259 lreply(211, "Connected to %s (%s)", remotehost,
1260 inet_ntoa(his_addr.sin_addr));
1261 if (logged_in) {
1262 if (guest)
1263 lreply(211, "Logged in anonymously");
1264 else
1265 lreply(211, "Logged in as %s", pw->pw_name);
1266 } else if (askpasswd)
1267 lreply(211, "Waiting for password");
1268 else
1269 lreply(211, "Waiting for user name");
1270 printf("211- TYPE: %s", typenames[type]);
1271 if (type == TYPE_A || type == TYPE_E)
1272 printf(", FORM: %s", formnames[form]);
1273 if (type == TYPE_L)
1274 #if NBBY == 8
1275 printf(" %d", NBBY);
1276 #else
1277 printf(" %d", bytesize); /* need definition! */
1278 #endif
1279 printf("; STRUcture: %s; transfer MODE: %s\r\n",
1280 strunames[stru], modenames[mode]);
1281 if (data != -1)
1282 lreply(211, "Data connection open");
1283 else if (pdata != -1) {
1284 printf("211- in Passive mode");
1285 sin = &pasv_addr;
1286 goto printaddr;
1287 } else if (usedefault == 0) {
1288 printf("211- PORT");
1289 sin = &data_dest;
1290 printaddr:
1291 a = (u_char *) &sin->sin_addr;
1292 p = (u_char *) &sin->sin_port;
1293 #define UC(b) (((int) b) & 0xff)
1294 printf(" (%d,%d,%d,%d,%d,%d)\r\n", UC(a[0]),
1295 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
1296 #undef UC
1297 } else
1298 lreply(211, "No data connection");
1299
1300 if (logged_in) {
1301 struct ftpconv *cp;
1302
1303 lreply(211, "");
1304 lreply(211, "Class: %s", curclass.classname);
1305 if (curclass.display)
1306 lreply(211, "Display file: %s", curclass.display);
1307 if (curclass.notify)
1308 lreply(211, "Notify fileglob: %s", curclass.notify);
1309 lreply(211, "Idle timeout: %d, maximum timeout: %d",
1310 curclass.timeout, curclass.maxtimeout);
1311 lreply(211, "dele, mkd, rmd, umask, chmod: %sabled",
1312 curclass.modify ? "en" : "dis");
1313 lreply(211, "Umask: %.04o", curclass.umask);
1314 for (cp = curclass.conversions; cp != NULL; cp=cp->next) {
1315 if (cp->suffix == NULL || cp->types == NULL ||
1316 cp->command == NULL)
1317 continue;
1318 lreply(211,
1319 "Conversion: %s [%s] disable: %s, command: %s",
1320 cp->suffix, cp->types, cp->disable, cp->command);
1321 }
1322 }
1323
1324 reply(211, "End of status");
1325 }
1326
1327 void
1328 fatal(s)
1329 char *s;
1330 {
1331
1332 reply(451, "Error in server: %s\n", s);
1333 reply(221, "Closing connection due to server error.");
1334 dologout(0);
1335 /* NOTREACHED */
1336 }
1337
1338 void
1339 #if __STDC__
1340 reply(int n, const char *fmt, ...)
1341 #else
1342 reply(n, fmt, va_alist)
1343 int n;
1344 char *fmt;
1345 va_dcl
1346 #endif
1347 {
1348 va_list ap;
1349 #if __STDC__
1350 va_start(ap, fmt);
1351 #else
1352 va_start(ap);
1353 #endif
1354 (void)printf("%d ", n);
1355 (void)vprintf(fmt, ap);
1356 (void)printf("\r\n");
1357 (void)fflush(stdout);
1358 if (debug) {
1359 syslog(LOG_DEBUG, "<--- %d ", n);
1360 vsyslog(LOG_DEBUG, fmt, ap);
1361 }
1362 }
1363
1364 void
1365 #if __STDC__
1366 lreply(int n, const char *fmt, ...)
1367 #else
1368 lreply(n, fmt, va_alist)
1369 int n;
1370 char *fmt;
1371 va_dcl
1372 #endif
1373 {
1374 va_list ap;
1375 #if __STDC__
1376 va_start(ap, fmt);
1377 #else
1378 va_start(ap);
1379 #endif
1380 (void)printf("%d- ", n);
1381 (void)vprintf(fmt, ap);
1382 (void)printf("\r\n");
1383 (void)fflush(stdout);
1384 if (debug) {
1385 syslog(LOG_DEBUG, "<--- %d- ", n);
1386 vsyslog(LOG_DEBUG, fmt, ap);
1387 }
1388 }
1389
1390 static void
1391 ack(s)
1392 char *s;
1393 {
1394
1395 reply(250, "%s command successful.", s);
1396 }
1397
1398 void
1399 nack(s)
1400 char *s;
1401 {
1402
1403 reply(502, "%s command not implemented.", s);
1404 }
1405
1406 /* ARGSUSED */
1407 void
1408 yyerror(s)
1409 char *s;
1410 {
1411 char *cp;
1412
1413 if ((cp = strchr(cbuf,'\n')) != NULL)
1414 *cp = '\0';
1415 reply(500, "'%s': command not understood.", cbuf);
1416 }
1417
1418 void
1419 delete(name)
1420 char *name;
1421 {
1422
1423 LOGCMD("delete", name);
1424 if (remove(name) < 0)
1425 perror_reply(550, name);
1426 else
1427 ack("DELE");
1428 }
1429
1430 void
1431 cwd(path)
1432 char *path;
1433 {
1434
1435 if (chdir(path) < 0)
1436 perror_reply(550, path);
1437 else {
1438 show_chdir_messages(250);
1439 ack("CWD");
1440 }
1441 }
1442
1443 static void
1444 replydirname(name, message)
1445 const char *name, *message;
1446 {
1447 char npath[MAXPATHLEN + 1];
1448 int i;
1449
1450 for (i = 0; *name != '\0' && i < sizeof(npath) - 1; i++, name++) {
1451 npath[i] = *name;
1452 if (*name == '"')
1453 npath[++i] = '"';
1454 }
1455 npath[i] = '\0';
1456 reply(257, "\"%s\" %s", npath, message);
1457 }
1458
1459 void
1460 makedir(name)
1461 char *name;
1462 {
1463
1464 LOGCMD("mkdir", name);
1465 if (mkdir(name, 0777) < 0)
1466 perror_reply(550, name);
1467 else
1468 replydirname(name, "directory created.");
1469 }
1470
1471 void
1472 removedir(name)
1473 char *name;
1474 {
1475
1476 LOGCMD("rmdir", name);
1477 if (rmdir(name) < 0)
1478 perror_reply(550, name);
1479 else
1480 ack("RMD");
1481 }
1482
1483 void
1484 pwd()
1485 {
1486 char path[MAXPATHLEN + 1];
1487
1488 if (getcwd(path, sizeof(path) - 1) == NULL)
1489 reply(550, "%s.", path);
1490 else
1491 replydirname(path, "is the current directory.");
1492 }
1493
1494 char *
1495 renamefrom(name)
1496 char *name;
1497 {
1498 struct stat st;
1499
1500 if (stat(name, &st) < 0) {
1501 perror_reply(550, name);
1502 return ((char *)0);
1503 }
1504 reply(350, "File exists, ready for destination name");
1505 return (name);
1506 }
1507
1508 void
1509 renamecmd(from, to)
1510 char *from, *to;
1511 {
1512
1513 LOGCMD2("rename", from, to);
1514 if (rename(from, to) < 0)
1515 perror_reply(550, "rename");
1516 else
1517 ack("RNTO");
1518 }
1519
1520 static void
1521 dolog(sin)
1522 struct sockaddr_in *sin;
1523 {
1524 struct hostent *hp = gethostbyaddr((char *)&sin->sin_addr,
1525 sizeof(struct in_addr), AF_INET);
1526
1527 if (hp)
1528 (void) strncpy(remotehost, hp->h_name, sizeof(remotehost));
1529 else
1530 (void) strncpy(remotehost, inet_ntoa(sin->sin_addr),
1531 sizeof(remotehost));
1532 #ifdef HASSETPROCTITLE
1533 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
1534 setproctitle(proctitle);
1535 #endif /* HASSETPROCTITLE */
1536
1537 if (logging)
1538 syslog(LOG_INFO, "connection from %s", remotehost);
1539 }
1540
1541 /*
1542 * Record logout in wtmp file
1543 * and exit with supplied status.
1544 */
1545 void
1546 dologout(status)
1547 int status;
1548 {
1549 /*
1550 * Prevent reception of SIGURG from resulting in a resumption
1551 * back to the main program loop.
1552 */
1553 transflag = 0;
1554
1555 if (logged_in) {
1556 (void) seteuid((uid_t)0);
1557 logwtmp(ttyline, "", "");
1558 #ifdef KERBEROS
1559 if (!notickets && krbtkfile_env)
1560 unlink(krbtkfile_env);
1561 #endif
1562 }
1563 /* beware of flushing buffers after a SIGPIPE */
1564 _exit(status);
1565 }
1566
1567 static void
1568 myoob(signo)
1569 int signo;
1570 {
1571 char *cp;
1572
1573 /* only process if transfer occurring */
1574 if (!transflag)
1575 return;
1576 cp = tmpline;
1577 if (getline(cp, 7, stdin) == NULL) {
1578 reply(221, "You could at least say goodbye.");
1579 dologout(0);
1580 }
1581 upper(cp);
1582 if (strcmp(cp, "ABOR\r\n") == 0) {
1583 tmpline[0] = '\0';
1584 reply(426, "Transfer aborted. Data connection closed.");
1585 reply(226, "Abort successful");
1586 longjmp(urgcatch, 1);
1587 }
1588 if (strcmp(cp, "STAT\r\n") == 0) {
1589 if (file_size != (off_t) -1)
1590 reply(213, "Status: %qd of %qd bytes transferred",
1591 byte_count, file_size);
1592 else
1593 reply(213, "Status: %qd bytes transferred", byte_count);
1594 }
1595 }
1596
1597 /*
1598 * Note: a response of 425 is not mentioned as a possible response to
1599 * the PASV command in RFC959. However, it has been blessed as
1600 * a legitimate response by Jon Postel in a telephone conversation
1601 * with Rick Adams on 25 Jan 89.
1602 */
1603 void
1604 passive()
1605 {
1606 int len;
1607 char *p, *a;
1608
1609 pdata = socket(AF_INET, SOCK_STREAM, 0);
1610 if (pdata < 0 || !logged_in) {
1611 perror_reply(425, "Can't open passive connection");
1612 return;
1613 }
1614 pasv_addr = ctrl_addr;
1615 pasv_addr.sin_port = 0;
1616 (void) seteuid((uid_t)0);
1617 if (bind(pdata, (struct sockaddr *)&pasv_addr, sizeof(pasv_addr)) < 0) {
1618 (void) seteuid((uid_t)pw->pw_uid);
1619 goto pasv_error;
1620 }
1621 (void) seteuid((uid_t)pw->pw_uid);
1622 len = sizeof(pasv_addr);
1623 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
1624 goto pasv_error;
1625 if (listen(pdata, 1) < 0)
1626 goto pasv_error;
1627 a = (char *) &pasv_addr.sin_addr;
1628 p = (char *) &pasv_addr.sin_port;
1629
1630 #define UC(b) (((int) b) & 0xff)
1631
1632 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
1633 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
1634 return;
1635
1636 pasv_error:
1637 (void) close(pdata);
1638 pdata = -1;
1639 perror_reply(425, "Can't open passive connection");
1640 return;
1641 }
1642
1643 /*
1644 * Generate unique name for file with basename "local".
1645 * The file named "local" is already known to exist.
1646 * Generates failure reply on error.
1647 *
1648 * XXX this function should under go changes similar to
1649 * the mktemp(3)/mkstemp(3) changes.
1650 */
1651 static char *
1652 gunique(local)
1653 char *local;
1654 {
1655 static char new[MAXPATHLEN];
1656 struct stat st;
1657 int count, len;
1658 char *cp;
1659
1660 cp = strrchr(local, '/');
1661 if (cp)
1662 *cp = '\0';
1663 if (stat(cp ? local : ".", &st) < 0) {
1664 perror_reply(553, cp ? local : ".");
1665 return ((char *) 0);
1666 }
1667 if (cp)
1668 *cp = '/';
1669 (void) strcpy(new, local);
1670 len = strlen(new);
1671 cp = new + len;
1672 *cp++ = '.';
1673 for (count = 1; count < 100; count++) {
1674 (void)snprintf(cp, sizeof(new) - len - 2, "%d", count);
1675 if (stat(new, &st) < 0)
1676 return (new);
1677 }
1678 reply(452, "Unique file name cannot be created.");
1679 return (NULL);
1680 }
1681
1682 /*
1683 * Format and send reply containing system error number.
1684 */
1685 void
1686 perror_reply(code, string)
1687 int code;
1688 char *string;
1689 {
1690
1691 reply(code, "%s: %s.", string, strerror(errno));
1692 }
1693
1694 static char *onefile[] = {
1695 "",
1696 0
1697 };
1698
1699 void
1700 send_file_list(whichf)
1701 char *whichf;
1702 {
1703 struct stat st;
1704 DIR *dirp = NULL;
1705 struct dirent *dir;
1706 FILE *dout = NULL;
1707 char **dirlist, *dirname;
1708 int simple = 0;
1709 int freeglob = 0;
1710 glob_t gl;
1711 #ifdef __GNUC__
1712 (void) &dout;
1713 (void) &dirlist;
1714 (void) &simple;
1715 (void) &freeglob;
1716 #endif
1717
1718 if (strpbrk(whichf, "~{[*?") != NULL) {
1719 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
1720
1721 memset(&gl, 0, sizeof(gl));
1722 freeglob = 1;
1723 if (glob(whichf, flags, 0, &gl)) {
1724 reply(550, "not found");
1725 goto out;
1726 } else if (gl.gl_pathc == 0) {
1727 errno = ENOENT;
1728 perror_reply(550, whichf);
1729 goto out;
1730 }
1731 dirlist = gl.gl_pathv;
1732 } else {
1733 onefile[0] = whichf;
1734 dirlist = onefile;
1735 simple = 1;
1736 }
1737
1738 if (setjmp(urgcatch)) {
1739 transflag = 0;
1740 goto out;
1741 }
1742 while ((dirname = *dirlist++) != NULL) {
1743 int trailingslash = 0;
1744
1745 if (stat(dirname, &st) < 0) {
1746 /*
1747 * If user typed "ls -l", etc, and the client
1748 * used NLST, do what the user meant.
1749 */
1750 if (dirname[0] == '-' && *dirlist == NULL &&
1751 transflag == 0) {
1752 retrieve("/bin/ls %s", dirname);
1753 goto out;
1754 }
1755 perror_reply(550, whichf);
1756 if (dout != NULL) {
1757 (void) fclose(dout);
1758 transflag = 0;
1759 data = -1;
1760 pdata = -1;
1761 }
1762 goto out;
1763 }
1764
1765 if (S_ISREG(st.st_mode)) {
1766 if (dout == NULL) {
1767 dout = dataconn("file list", (off_t)-1, "w");
1768 if (dout == NULL)
1769 goto out;
1770 transflag++;
1771 }
1772 fprintf(dout, "%s%s\n", dirname,
1773 type == TYPE_A ? "\r" : "");
1774 byte_count += strlen(dirname) + 1;
1775 continue;
1776 } else if (!S_ISDIR(st.st_mode))
1777 continue;
1778
1779 if (dirname[strlen(dirname) - 1] == '/')
1780 trailingslash++;
1781
1782 if ((dirp = opendir(dirname)) == NULL)
1783 continue;
1784
1785 while ((dir = readdir(dirp)) != NULL) {
1786 char nbuf[MAXPATHLEN];
1787
1788 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
1789 continue;
1790 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
1791 dir->d_namlen == 2)
1792 continue;
1793
1794 (void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
1795 trailingslash ? "" : "/", dir->d_name);
1796
1797 /*
1798 * We have to do a stat to ensure it's
1799 * not a directory or special file.
1800 */
1801 if (simple || (stat(nbuf, &st) == 0 &&
1802 S_ISREG(st.st_mode))) {
1803 if (dout == NULL) {
1804 dout = dataconn("file list", (off_t)-1,
1805 "w");
1806 if (dout == NULL)
1807 goto out;
1808 transflag++;
1809 }
1810 if (nbuf[0] == '.' && nbuf[1] == '/')
1811 fprintf(dout, "%s%s\n", &nbuf[2],
1812 type == TYPE_A ? "\r" : "");
1813 else
1814 fprintf(dout, "%s%s\n", nbuf,
1815 type == TYPE_A ? "\r" : "");
1816 byte_count += strlen(nbuf) + 1;
1817 }
1818 }
1819 (void) closedir(dirp);
1820 }
1821
1822 if (dout == NULL)
1823 reply(550, "No files found.");
1824 else if (ferror(dout) != 0)
1825 perror_reply(550, "Data connection");
1826 else
1827 reply(226, "Transfer complete.");
1828
1829 transflag = 0;
1830 if (dout != NULL)
1831 (void) fclose(dout);
1832 data = -1;
1833 pdata = -1;
1834 out:
1835 if (freeglob) {
1836 freeglob = 0;
1837 globfree(&gl);
1838 }
1839 }
1840
1841 char *
1842 conffilename(s)
1843 const char *s;
1844 {
1845 static char filename[MAXPATHLEN];
1846
1847 (void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
1848 return filename;
1849 }
1850