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