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