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