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