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