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