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