1) Added s/key support .
[unix-history] / libexec / ftpd / ftpd.c
CommitLineData
15637ed4
RG
1/*
2 * Copyright (c) 1985, 1988, 1990 Regents of the University of California.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#ifndef lint
35char copyright[] =
36"@(#) Copyright (c) 1985, 1988, 1990 Regents of the University of California.\n\
37 All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41static char sccsid[] = "@(#)ftpd.c 5.40 (Berkeley) 7/2/91";
42#endif /* not lint */
43
44/*
45 * FTP server.
46 */
47#include <sys/param.h>
48#include <sys/stat.h>
49#include <sys/ioctl.h>
50#include <sys/socket.h>
51#include <sys/wait.h>
52
53#include <netinet/in.h>
54#include <netinet/in_systm.h>
55#include <netinet/ip.h>
56
57#define FTP_NAMES
58#include <arpa/ftp.h>
59#include <arpa/inet.h>
60#include <arpa/telnet.h>
61
62#include <signal.h>
63#include <dirent.h>
64#include <fcntl.h>
65#include <time.h>
66#include <pwd.h>
67#include <setjmp.h>
68#include <netdb.h>
69#include <errno.h>
70#include <syslog.h>
71#include <varargs.h>
72#include <unistd.h>
73#include <stdio.h>
74#include <ctype.h>
75#include <stdlib.h>
76#include <string.h>
77#include "pathnames.h"
78
79/*
80 * File containing login names
81 * NOT to be used on this machine.
82 * Commonly used to disallow uucp.
83 */
84extern int errno;
85extern char *crypt();
86extern char version[];
87extern char *home; /* pointer to home directory for glob */
88extern FILE *ftpd_popen(), *fopen(), *freopen();
89extern int ftpd_pclose(), fclose();
90extern char *getline();
91extern char cbuf[];
92extern off_t restart_point;
93
94struct sockaddr_in ctrl_addr;
95struct sockaddr_in data_source;
96struct sockaddr_in data_dest;
97struct sockaddr_in his_addr;
98struct sockaddr_in pasv_addr;
99
100int data;
101jmp_buf errcatch, urgcatch;
102int logged_in;
103struct passwd *pw;
104int debug;
105int timeout = 900; /* timeout after 15 minutes of inactivity */
106int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
107int logging;
108int guest;
109int type;
110int form;
111int stru; /* avoid C keyword */
112int mode;
113int usedefault = 1; /* for data transfers */
114int pdata = -1; /* for passive mode */
115int transflag;
116off_t file_size;
117off_t byte_count;
118#if !defined(CMASK) || CMASK == 0
119#undef CMASK
120#define CMASK 027
121#endif
122int defumask = CMASK; /* default umask value */
123char tmpline[7];
124char hostname[MAXHOSTNAMELEN];
125char remotehost[MAXHOSTNAMELEN];
126
127/*
128 * Timeout intervals for retrying connections
129 * to hosts that don't accept PORT cmds. This
130 * is a kludge, but given the problems with TCP...
131 */
132#define SWAITMAX 90 /* wait at most 90 seconds */
133#define SWAITINT 5 /* interval between retries */
134
135int swaitmax = SWAITMAX;
136int swaitint = SWAITINT;
137
138void lostconn(), myoob();
139FILE *getdatasock(), *dataconn();
140
141#ifdef SETPROCTITLE
142char **Argv = NULL; /* pointer to argument vector */
143char *LastArgv = NULL; /* end of argv */
144char proctitle[BUFSIZ]; /* initial part of title */
145#endif /* SETPROCTITLE */
146
05a0983d
GR
147#ifdef SKEY
148int pwok = 0;
149char *skey_challenge();
150char *skey_crypt();
151#endif
15637ed4
RG
152main(argc, argv, envp)
153 int argc;
154 char *argv[];
155 char **envp;
156{
157 int addrlen, on = 1, tos;
158 char *cp;
05a0983d
GR
159#ifdef SKEY
160 char addr_string[20]; /* XXX */
161#endif
15637ed4
RG
162
163 /*
164 * LOG_NDELAY sets up the logging connection immediately,
165 * necessary for anonymous ftp's that chroot and can't do it later.
166 */
167 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_DAEMON);
168 addrlen = sizeof (his_addr);
169 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
170 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
171 exit(1);
172 }
05a0983d
GR
173#ifdef SKEY
174 strcpy(addr_string, inet_ntoa(his_addr.sin_addr));
175 pwok = authfile(addr_string);
176#endif
15637ed4
RG
177 addrlen = sizeof (ctrl_addr);
178 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
179 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
180 exit(1);
181 }
182#ifdef IP_TOS
183 tos = IPTOS_LOWDELAY;
184 if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(int)) < 0)
185 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
186#endif
187 data_source.sin_port = htons(ntohs(ctrl_addr.sin_port) - 1);
188 debug = 0;
189#ifdef SETPROCTITLE
190 /*
191 * Save start and extent of argv for setproctitle.
192 */
193 Argv = argv;
194 while (*envp)
195 envp++;
196 LastArgv = envp[-1] + strlen(envp[-1]);
197#endif /* SETPROCTITLE */
198
199 argc--, argv++;
200 while (argc > 0 && *argv[0] == '-') {
201 for (cp = &argv[0][1]; *cp; cp++) switch (*cp) {
202
203 case 'v':
204 debug = 1;
205 break;
206
207 case 'd':
208 debug = 1;
209 break;
210
211 case 'l':
212 logging = 1;
213 break;
214
215 case 't':
216 timeout = atoi(++cp);
217 if (maxtimeout < timeout)
218 maxtimeout = timeout;
219 goto nextopt;
220
221 case 'T':
222 maxtimeout = atoi(++cp);
223 if (timeout > maxtimeout)
224 timeout = maxtimeout;
225 goto nextopt;
226
227 case 'u':
228 {
229 int val = 0;
230
231 while (*++cp && *cp >= '0' && *cp <= '9')
232 val = val*8 + *cp - '0';
233 if (*cp)
234 fprintf(stderr, "ftpd: Bad value for -u\n");
235 else
236 defumask = val;
237 goto nextopt;
238 }
239
240 default:
241 fprintf(stderr, "ftpd: Unknown flag -%c ignored.\n",
242 *cp);
243 break;
244 }
245nextopt:
246 argc--, argv++;
247 }
248 (void) freopen(_PATH_DEVNULL, "w", stderr);
249 (void) signal(SIGPIPE, lostconn);
250 (void) signal(SIGCHLD, SIG_IGN);
251 if ((int)signal(SIGURG, myoob) < 0)
252 syslog(LOG_ERR, "signal: %m");
253
254 /* Try to handle urgent data inline */
255#ifdef SO_OOBINLINE
256 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
257 syslog(LOG_ERR, "setsockopt: %m");
258#endif
259
260#ifdef F_SETOWN
261 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
262 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
263#endif
264 dolog(&his_addr);
265 /*
266 * Set up default state
267 */
268 data = -1;
269 type = TYPE_A;
270 form = FORM_N;
271 stru = STRU_F;
272 mode = MODE_S;
273 tmpline[0] = '\0';
274 (void) gethostname(hostname, sizeof (hostname));
275 reply(220, "%s FTP server (%s) ready.", hostname, version);
276 (void) setjmp(errcatch);
277 for (;;)
278 (void) yyparse();
279 /* NOTREACHED */
280}
281
282void
283lostconn()
284{
285 if (debug)
286 syslog(LOG_DEBUG, "lost connection");
287 dologout(-1);
288}
289
290static char ttyline[20];
291
292/*
293 * Helper function for sgetpwnam().
294 */
295char *
296sgetsave(s)
297 char *s;
298{
299 char *new = malloc((unsigned) strlen(s) + 1);
300
301 if (new == NULL) {
302 perror_reply(421, "Local resource failure: malloc");
303 dologout(1);
304 /* NOTREACHED */
305 }
306 (void) strcpy(new, s);
307 return (new);
308}
309
310/*
311 * Save the result of a getpwnam. Used for USER command, since
312 * the data returned must not be clobbered by any other command
313 * (e.g., globbing).
314 */
315struct passwd *
316sgetpwnam(name)
317 char *name;
318{
319 static struct passwd save;
320 register struct passwd *p;
321 char *sgetsave();
322
323 if ((p = getpwnam(name)) == NULL)
324 return (p);
325 if (save.pw_name) {
326 free(save.pw_name);
327 free(save.pw_passwd);
328 free(save.pw_gecos);
329 free(save.pw_dir);
330 free(save.pw_shell);
331 }
332 save = *p;
333 save.pw_name = sgetsave(p->pw_name);
334 save.pw_passwd = sgetsave(p->pw_passwd);
335 save.pw_gecos = sgetsave(p->pw_gecos);
336 save.pw_dir = sgetsave(p->pw_dir);
337 save.pw_shell = sgetsave(p->pw_shell);
338 return (&save);
339}
340
341int login_attempts; /* number of failed login attempts */
342int askpasswd; /* had user command, ask for passwd */
343
344/*
345 * USER command.
346 * Sets global passwd pointer pw if named account exists and is acceptable;
347 * sets askpasswd if a PASS command is expected. If logged in previously,
348 * need to reset state. If name is "ftp" or "anonymous", the name is not in
349 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
350 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
351 * requesting login privileges. Disallow anyone who does not have a standard
352 * shell as returned by getusershell(). Disallow anyone mentioned in the file
353 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
354 */
355user(name)
356 char *name;
357{
358 register char *cp;
359 char *shell;
360 char *getusershell();
361
362 if (logged_in) {
363 if (guest) {
364 reply(530, "Can't change user from guest login.");
365 return;
366 }
367 end_login();
368 }
369
370 guest = 0;
371 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
372 if (checkuser("ftp") || checkuser("anonymous"))
373 reply(530, "User %s access denied.", name);
374 else if ((pw = sgetpwnam("ftp")) != NULL) {
375 guest = 1;
376 askpasswd = 1;
377 reply(331, "Guest login ok, send ident as password.");
378 } else
379 reply(530, "User %s unknown.", name);
380 return;
381 }
382 if (pw = sgetpwnam(name)) {
383 if ((shell = pw->pw_shell) == NULL || *shell == 0)
384 shell = _PATH_BSHELL;
385 while ((cp = getusershell()) != NULL)
386 if (strcmp(cp, shell) == 0)
387 break;
388 endusershell();
389 if (cp == NULL || checkuser(name)) {
390 reply(530, "User %s access denied.", name);
391 if (logging)
392 syslog(LOG_NOTICE,
393 "FTP LOGIN REFUSED FROM %s, %s",
394 remotehost, name);
395 pw = (struct passwd *) NULL;
396 return;
397 }
398 }
05a0983d
GR
399#ifdef SKEY
400 reply(331, "%s", skey_challenge(name, pw, pwok));
401#else
15637ed4 402 reply(331, "Password required for %s.", name);
05a0983d 403#endif
15637ed4
RG
404 askpasswd = 1;
405 /*
406 * Delay before reading passwd after first failed
407 * attempt to slow down passwd-guessing programs.
408 */
409 if (login_attempts)
410 sleep((unsigned) login_attempts);
411}
412
413/*
414 * Check if a user is in the file _PATH_FTPUSERS
415 */
416checkuser(name)
417 char *name;
418{
419 register FILE *fd;
420 register char *p;
421 char line[BUFSIZ];
422
423 if ((fd = fopen(_PATH_FTPUSERS, "r")) != NULL) {
424 while (fgets(line, sizeof(line), fd) != NULL)
425 if ((p = index(line, '\n')) != NULL) {
426 *p = '\0';
427 if (line[0] == '#')
428 continue;
429 if (strcmp(line, name) == 0)
430 return (1);
431 }
432 (void) fclose(fd);
433 }
434 return (0);
435}
436
437/*
438 * Terminate login as previous user, if any, resetting state;
439 * used when USER command is given or login fails.
440 */
441end_login()
442{
443
444 (void) seteuid((uid_t)0);
445 if (logged_in)
446 logwtmp(ttyline, "", "");
447 pw = NULL;
448 logged_in = 0;
449 guest = 0;
450}
451
452pass(passwd)
453 char *passwd;
454{
455 char *xpasswd, *salt;
456
457 if (logged_in || askpasswd == 0) {
458 reply(503, "Login with USER first.");
459 return;
460 }
461 askpasswd = 0;
462 if (!guest) { /* "ftp" is only account allowed no password */
463 if (pw == NULL)
464 salt = "xx";
465 else
466 salt = pw->pw_passwd;
05a0983d
GR
467#ifdef SKEY
468 xpasswd = skey_crypt(passwd, salt, pw, pwok);
469#else
15637ed4 470 xpasswd = crypt(passwd, salt);
05a0983d 471#endif
15637ed4
RG
472 /* The strcmp does not catch null passwords! */
473 if (pw == NULL || *pw->pw_passwd == '\0' ||
474 strcmp(xpasswd, pw->pw_passwd)) {
475 reply(530, "Login incorrect.");
476 pw = NULL;
477 if (login_attempts++ >= 5) {
478 syslog(LOG_NOTICE,
479 "repeated login failures from %s",
480 remotehost);
481 exit(0);
482 }
483 return;
484 }
485 }
486 login_attempts = 0; /* this time successful */
487 (void) setegid((gid_t)pw->pw_gid);
488 (void) initgroups(pw->pw_name, pw->pw_gid);
489
490 /* open wtmp before chroot */
491 (void)sprintf(ttyline, "ftp%d", getpid());
492 logwtmp(ttyline, pw->pw_name, remotehost);
493 logged_in = 1;
494
495 if (guest) {
496 /*
497 * We MUST do a chdir() after the chroot. Otherwise
498 * the old current directory will be accessible as "."
499 * outside the new root!
500 */
501 if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
502 reply(550, "Can't set guest privileges.");
503 goto bad;
504 }
505 } else if (chdir(pw->pw_dir) < 0) {
506 if (chdir("/") < 0) {
507 reply(530, "User %s: can't change directory to %s.",
508 pw->pw_name, pw->pw_dir);
509 goto bad;
510 } else
511 lreply(230, "No directory! Logging in with home=/");
512 }
513 if (seteuid((uid_t)pw->pw_uid) < 0) {
514 reply(550, "Can't set uid.");
515 goto bad;
516 }
517 if (guest) {
518 reply(230, "Guest login ok, access restrictions apply.");
519#ifdef SETPROCTITLE
520 sprintf(proctitle, "%s: anonymous/%.*s", remotehost,
521 sizeof(proctitle) - sizeof(remotehost) -
522 sizeof(": anonymous/"), passwd);
523 setproctitle(proctitle);
524#endif /* SETPROCTITLE */
525 if (logging)
526 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
527 remotehost, passwd);
528 } else {
529 reply(230, "User %s logged in.", pw->pw_name);
530#ifdef SETPROCTITLE
531 sprintf(proctitle, "%s: %s", remotehost, pw->pw_name);
532 setproctitle(proctitle);
533#endif /* SETPROCTITLE */
534 if (logging)
535 syslog(LOG_INFO, "FTP LOGIN FROM %s, %s",
536 remotehost, pw->pw_name);
537 }
538 home = pw->pw_dir; /* home dir for globbing */
539 (void) umask(defumask);
540 return;
541bad:
542 /* Forget all about it... */
543 end_login();
544}
545
546retrieve(cmd, name)
547 char *cmd, *name;
548{
549 FILE *fin, *dout;
550 struct stat st;
551 int (*closefunc)();
552
553 if (cmd == 0) {
554 fin = fopen(name, "r"), closefunc = fclose;
555 st.st_size = 0;
556 } else {
557 char line[BUFSIZ];
558
559 (void) sprintf(line, cmd, name), name = line;
560 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
561 st.st_size = -1;
562 st.st_blksize = BUFSIZ;
563 }
564 if (fin == NULL) {
565 if (errno != 0)
566 perror_reply(550, name);
567 return;
568 }
569 if (cmd == 0 &&
570 (fstat(fileno(fin), &st) < 0 || (st.st_mode&S_IFMT) != S_IFREG)) {
571 reply(550, "%s: not a plain file.", name);
572 goto done;
573 }
574 if (restart_point) {
575 if (type == TYPE_A) {
576 register int i, n, c;
577
578 n = restart_point;
579 i = 0;
580 while (i++ < n) {
581 if ((c=getc(fin)) == EOF) {
582 perror_reply(550, name);
583 goto done;
584 }
585 if (c == '\n')
586 i++;
587 }
588 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
589 perror_reply(550, name);
590 goto done;
591 }
592 }
593 dout = dataconn(name, st.st_size, "w");
594 if (dout == NULL)
595 goto done;
596 send_data(fin, dout, st.st_blksize);
597 (void) fclose(dout);
598 data = -1;
599 pdata = -1;
600done:
601 (*closefunc)(fin);
602}
603
604store(name, mode, unique)
605 char *name, *mode;
606 int unique;
607{
608 FILE *fout, *din;
609 struct stat st;
610 int (*closefunc)();
611 char *gunique();
612
613 if (unique && stat(name, &st) == 0 &&
614 (name = gunique(name)) == NULL)
615 return;
616
617 if (restart_point)
618 mode = "r+w";
619 fout = fopen(name, mode);
620 closefunc = fclose;
621 if (fout == NULL) {
622 perror_reply(553, name);
623 return;
624 }
625 if (restart_point) {
626 if (type == TYPE_A) {
627 register int i, n, c;
628
629 n = restart_point;
630 i = 0;
631 while (i++ < n) {
632 if ((c=getc(fout)) == EOF) {
633 perror_reply(550, name);
634 goto done;
635 }
636 if (c == '\n')
637 i++;
638 }
639 /*
640 * We must do this seek to "current" position
641 * because we are changing from reading to
642 * writing.
643 */
644 if (fseek(fout, 0L, L_INCR) < 0) {
645 perror_reply(550, name);
646 goto done;
647 }
648 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
649 perror_reply(550, name);
650 goto done;
651 }
652 }
653 din = dataconn(name, (off_t)-1, "r");
654 if (din == NULL)
655 goto done;
656 if (receive_data(din, fout) == 0) {
657 if (unique)
658 reply(226, "Transfer complete (unique file name:%s).",
659 name);
660 else
661 reply(226, "Transfer complete.");
662 }
663 (void) fclose(din);
664 data = -1;
665 pdata = -1;
666done:
667 (*closefunc)(fout);
668}
669
670FILE *
671getdatasock(mode)
672 char *mode;
673{
674 int s, on = 1, tries;
675
676 if (data >= 0)
677 return (fdopen(data, mode));
678 (void) seteuid((uid_t)0);
679 s = socket(AF_INET, SOCK_STREAM, 0);
680 if (s < 0)
681 goto bad;
682 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
683 (char *) &on, sizeof (on)) < 0)
684 goto bad;
685 /* anchor socket to avoid multi-homing problems */
686 data_source.sin_family = AF_INET;
687 data_source.sin_addr = ctrl_addr.sin_addr;
688 for (tries = 1; ; tries++) {
689 if (bind(s, (struct sockaddr *)&data_source,
690 sizeof (data_source)) >= 0)
691 break;
692 if (errno != EADDRINUSE || tries > 10)
693 goto bad;
694 sleep(tries);
695 }
696 (void) seteuid((uid_t)pw->pw_uid);
697#ifdef IP_TOS
698 on = IPTOS_THROUGHPUT;
699 if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on, sizeof(int)) < 0)
700 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
701#endif
702 return (fdopen(s, mode));
703bad:
704 (void) seteuid((uid_t)pw->pw_uid);
705 (void) close(s);
706 return (NULL);
707}
708
709FILE *
710dataconn(name, size, mode)
711 char *name;
712 off_t size;
713 char *mode;
714{
715 char sizebuf[32];
716 FILE *file;
717 int retry = 0, tos;
718
719 file_size = size;
720 byte_count = 0;
721 if (size != (off_t) -1)
722 (void) sprintf (sizebuf, " (%ld bytes)", size);
723 else
724 (void) strcpy(sizebuf, "");
725 if (pdata >= 0) {
726 struct sockaddr_in from;
727 int s, fromlen = sizeof(from);
728
729 s = accept(pdata, (struct sockaddr *)&from, &fromlen);
730 if (s < 0) {
731 reply(425, "Can't open data connection.");
732 (void) close(pdata);
733 pdata = -1;
734 return(NULL);
735 }
736 (void) close(pdata);
737 pdata = s;
738#ifdef IP_TOS
739 tos = IPTOS_LOWDELAY;
740 (void) setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&tos,
741 sizeof(int));
742#endif
743 reply(150, "Opening %s mode data connection for %s%s.",
744 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
745 return(fdopen(pdata, mode));
746 }
747 if (data >= 0) {
748 reply(125, "Using existing data connection for %s%s.",
749 name, sizebuf);
750 usedefault = 1;
751 return (fdopen(data, mode));
752 }
753 if (usedefault)
754 data_dest = his_addr;
755 usedefault = 1;
756 file = getdatasock(mode);
757 if (file == NULL) {
758 reply(425, "Can't create data socket (%s,%d): %s.",
759 inet_ntoa(data_source.sin_addr),
760 ntohs(data_source.sin_port), strerror(errno));
761 return (NULL);
762 }
763 data = fileno(file);
764 while (connect(data, (struct sockaddr *)&data_dest,
765 sizeof (data_dest)) < 0) {
766 if (errno == EADDRINUSE && retry < swaitmax) {
767 sleep((unsigned) swaitint);
768 retry += swaitint;
769 continue;
770 }
771 perror_reply(425, "Can't build data connection");
772 (void) fclose(file);
773 data = -1;
774 return (NULL);
775 }
776 reply(150, "Opening %s mode data connection for %s%s.",
777 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
778 return (file);
779}
780
781/*
782 * Tranfer the contents of "instr" to
783 * "outstr" peer using the appropriate
784 * encapsulation of the data subject
785 * to Mode, Structure, and Type.
786 *
787 * NB: Form isn't handled.
788 */
789send_data(instr, outstr, blksize)
790 FILE *instr, *outstr;
791 off_t blksize;
792{
793 register int c, cnt;
794 register char *buf;
795 int netfd, filefd;
796
797 transflag++;
798 if (setjmp(urgcatch)) {
799 transflag = 0;
800 return;
801 }
802 switch (type) {
803
804 case TYPE_A:
805 while ((c = getc(instr)) != EOF) {
806 byte_count++;
807 if (c == '\n') {
808 if (ferror(outstr))
809 goto data_err;
810 (void) putc('\r', outstr);
811 }
812 (void) putc(c, outstr);
813 }
814 fflush(outstr);
815 transflag = 0;
816 if (ferror(instr))
817 goto file_err;
818 if (ferror(outstr))
819 goto data_err;
820 reply(226, "Transfer complete.");
821 return;
822
823 case TYPE_I:
824 case TYPE_L:
825 if ((buf = malloc((u_int)blksize)) == NULL) {
826 transflag = 0;
827 perror_reply(451, "Local resource failure: malloc");
828 return;
829 }
830 netfd = fileno(outstr);
831 filefd = fileno(instr);
832 while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
833 write(netfd, buf, cnt) == cnt)
834 byte_count += cnt;
835 transflag = 0;
836 (void)free(buf);
837 if (cnt != 0) {
838 if (cnt < 0)
839 goto file_err;
840 goto data_err;
841 }
842 reply(226, "Transfer complete.");
843 return;
844 default:
845 transflag = 0;
846 reply(550, "Unimplemented TYPE %d in send_data", type);
847 return;
848 }
849
850data_err:
851 transflag = 0;
852 perror_reply(426, "Data connection");
853 return;
854
855file_err:
856 transflag = 0;
857 perror_reply(551, "Error on input file");
858}
859
860/*
861 * Transfer data from peer to
862 * "outstr" using the appropriate
863 * encapulation of the data subject
864 * to Mode, Structure, and Type.
865 *
866 * N.B.: Form isn't handled.
867 */
868receive_data(instr, outstr)
869 FILE *instr, *outstr;
870{
871 register int c;
872 int cnt, bare_lfs = 0;
873 char buf[BUFSIZ];
874
875 transflag++;
876 if (setjmp(urgcatch)) {
877 transflag = 0;
878 return (-1);
879 }
880 switch (type) {
881
882 case TYPE_I:
883 case TYPE_L:
884 while ((cnt = read(fileno(instr), buf, sizeof buf)) > 0) {
885 if (write(fileno(outstr), buf, cnt) != cnt)
886 goto file_err;
887 byte_count += cnt;
888 }
889 if (cnt < 0)
890 goto data_err;
891 transflag = 0;
892 return (0);
893
894 case TYPE_E:
895 reply(553, "TYPE E not implemented.");
896 transflag = 0;
897 return (-1);
898
899 case TYPE_A:
900 while ((c = getc(instr)) != EOF) {
901 byte_count++;
902 if (c == '\n')
903 bare_lfs++;
904 while (c == '\r') {
905 if (ferror(outstr))
906 goto data_err;
907 if ((c = getc(instr)) != '\n') {
908 (void) putc ('\r', outstr);
909 if (c == '\0' || c == EOF)
910 goto contin2;
911 }
912 }
913 (void) putc(c, outstr);
914 contin2: ;
915 }
916 fflush(outstr);
917 if (ferror(instr))
918 goto data_err;
919 if (ferror(outstr))
920 goto file_err;
921 transflag = 0;
922 if (bare_lfs) {
923 lreply(230, "WARNING! %d bare linefeeds received in ASCII mode", bare_lfs);
924 printf(" File may not have transferred correctly.\r\n");
925 }
926 return (0);
927 default:
928 reply(550, "Unimplemented TYPE %d in receive_data", type);
929 transflag = 0;
930 return (-1);
931 }
932
933data_err:
934 transflag = 0;
935 perror_reply(426, "Data Connection");
936 return (-1);
937
938file_err:
939 transflag = 0;
940 perror_reply(452, "Error writing file");
941 return (-1);
942}
943
944statfilecmd(filename)
945 char *filename;
946{
947 char line[BUFSIZ];
948 FILE *fin;
949 int c;
950
951 (void) sprintf(line, "/bin/ls -lgA %s", filename);
952 fin = ftpd_popen(line, "r");
953 lreply(211, "status of %s:", filename);
954 while ((c = getc(fin)) != EOF) {
955 if (c == '\n') {
956 if (ferror(stdout)){
957 perror_reply(421, "control connection");
958 (void) ftpd_pclose(fin);
959 dologout(1);
960 /* NOTREACHED */
961 }
962 if (ferror(fin)) {
963 perror_reply(551, filename);
964 (void) ftpd_pclose(fin);
965 return;
966 }
967 (void) putc('\r', stdout);
968 }
969 (void) putc(c, stdout);
970 }
971 (void) ftpd_pclose(fin);
972 reply(211, "End of Status");
973}
974
975statcmd()
976{
977 struct sockaddr_in *sin;
978 u_char *a, *p;
979
980 lreply(211, "%s FTP server status:", hostname, version);
981 printf(" %s\r\n", version);
982 printf(" Connected to %s", remotehost);
983 if (!isdigit(remotehost[0]))
984 printf(" (%s)", inet_ntoa(his_addr.sin_addr));
985 printf("\r\n");
986 if (logged_in) {
987 if (guest)
988 printf(" Logged in anonymously\r\n");
989 else
990 printf(" Logged in as %s\r\n", pw->pw_name);
991 } else if (askpasswd)
992 printf(" Waiting for password\r\n");
993 else
994 printf(" Waiting for user name\r\n");
995 printf(" TYPE: %s", typenames[type]);
996 if (type == TYPE_A || type == TYPE_E)
997 printf(", FORM: %s", formnames[form]);
998 if (type == TYPE_L)
999#if NBBY == 8
1000 printf(" %d", NBBY);
1001#else
1002 printf(" %d", bytesize); /* need definition! */
1003#endif
1004 printf("; STRUcture: %s; transfer MODE: %s\r\n",
1005 strunames[stru], modenames[mode]);
1006 if (data != -1)
1007 printf(" Data connection open\r\n");
1008 else if (pdata != -1) {
1009 printf(" in Passive mode");
1010 sin = &pasv_addr;
1011 goto printaddr;
1012 } else if (usedefault == 0) {
1013 printf(" PORT");
1014 sin = &data_dest;
1015printaddr:
1016 a = (u_char *) &sin->sin_addr;
1017 p = (u_char *) &sin->sin_port;
1018#define UC(b) (((int) b) & 0xff)
1019 printf(" (%d,%d,%d,%d,%d,%d)\r\n", UC(a[0]),
1020 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
1021#undef UC
1022 } else
1023 printf(" No data connection\r\n");
1024 reply(211, "End of status");
1025}
1026
1027fatal(s)
1028 char *s;
1029{
1030 reply(451, "Error in server: %s\n", s);
1031 reply(221, "Closing connection due to server error.");
1032 dologout(0);
1033 /* NOTREACHED */
1034}
1035
1036/* VARARGS2 */
1037reply(n, fmt, p0, p1, p2, p3, p4, p5)
1038 int n;
1039 char *fmt;
1040{
1041 printf("%d ", n);
1042 printf(fmt, p0, p1, p2, p3, p4, p5);
1043 printf("\r\n");
1044 (void)fflush(stdout);
1045 if (debug) {
1046 syslog(LOG_DEBUG, "<--- %d ", n);
1047 syslog(LOG_DEBUG, fmt, p0, p1, p2, p3, p4, p5);
1048}
1049}
1050
1051/* VARARGS2 */
1052lreply(n, fmt, p0, p1, p2, p3, p4, p5)
1053 int n;
1054 char *fmt;
1055{
1056 printf("%d- ", n);
1057 printf(fmt, p0, p1, p2, p3, p4, p5);
1058 printf("\r\n");
1059 (void)fflush(stdout);
1060 if (debug) {
1061 syslog(LOG_DEBUG, "<--- %d- ", n);
1062 syslog(LOG_DEBUG, fmt, p0, p1, p2, p3, p4, p5);
1063 }
1064}
1065
1066ack(s)
1067 char *s;
1068{
1069 reply(250, "%s command successful.", s);
1070}
1071
1072nack(s)
1073 char *s;
1074{
1075 reply(502, "%s command not implemented.", s);
1076}
1077
1078/* ARGSUSED */
1079yyerror(s)
1080 char *s;
1081{
1082 char *cp;
1083
1084 if (cp = index(cbuf,'\n'))
1085 *cp = '\0';
1086 reply(500, "'%s': command not understood.", cbuf);
1087}
1088
1089delete(name)
1090 char *name;
1091{
1092 struct stat st;
1093
1094 if (stat(name, &st) < 0) {
1095 perror_reply(550, name);
1096 return;
1097 }
1098 if ((st.st_mode&S_IFMT) == S_IFDIR) {
1099 if (rmdir(name) < 0) {
1100 perror_reply(550, name);
1101 return;
1102 }
1103 goto done;
1104 }
1105 if (unlink(name) < 0) {
1106 perror_reply(550, name);
1107 return;
1108 }
1109done:
1110 ack("DELE");
1111}
1112
1113cwd(path)
1114 char *path;
1115{
1116 if (chdir(path) < 0)
1117 perror_reply(550, path);
1118 else
1119 ack("CWD");
1120}
1121
1122makedir(name)
1123 char *name;
1124{
1125 if (mkdir(name, 0777) < 0)
1126 perror_reply(550, name);
1127 else
1128 reply(257, "MKD command successful.");
1129}
1130
1131removedir(name)
1132 char *name;
1133{
1134 if (rmdir(name) < 0)
1135 perror_reply(550, name);
1136 else
1137 ack("RMD");
1138}
1139
1140pwd()
1141{
1142 char path[MAXPATHLEN + 1];
1143 extern char *getwd();
1144
1145 if (getwd(path) == (char *)NULL)
1146 reply(550, "%s.", path);
1147 else
1148 reply(257, "\"%s\" is current directory.", path);
1149}
1150
1151char *
1152renamefrom(name)
1153 char *name;
1154{
1155 struct stat st;
1156
1157 if (stat(name, &st) < 0) {
1158 perror_reply(550, name);
1159 return ((char *)0);
1160 }
1161 reply(350, "File exists, ready for destination name");
1162 return (name);
1163}
1164
1165renamecmd(from, to)
1166 char *from, *to;
1167{
1168 if (rename(from, to) < 0)
1169 perror_reply(550, "rename");
1170 else
1171 ack("RNTO");
1172}
1173
1174dolog(sin)
1175 struct sockaddr_in *sin;
1176{
1177 struct hostent *hp = gethostbyaddr((char *)&sin->sin_addr,
1178 sizeof (struct in_addr), AF_INET);
1179 time_t t, time();
1180 extern char *ctime();
1181
1182 if (hp)
1183 (void) strncpy(remotehost, hp->h_name, sizeof (remotehost));
1184 else
1185 (void) strncpy(remotehost, inet_ntoa(sin->sin_addr),
1186 sizeof (remotehost));
1187#ifdef SETPROCTITLE
1188 sprintf(proctitle, "%s: connected", remotehost);
1189 setproctitle(proctitle);
1190#endif /* SETPROCTITLE */
1191
1192 if (logging) {
1193 t = time((time_t *) 0);
1194 syslog(LOG_INFO, "connection from %s at %s",
1195 remotehost, ctime(&t));
1196 }
1197}
1198
1199/*
1200 * Record logout in wtmp file
1201 * and exit with supplied status.
1202 */
1203dologout(status)
1204 int status;
1205{
1206 if (logged_in) {
1207 (void) seteuid((uid_t)0);
1208 logwtmp(ttyline, "", "");
1209 }
1210 /* beware of flushing buffers after a SIGPIPE */
1211 _exit(status);
1212}
1213
1214void
1215myoob()
1216{
1217 char *cp;
1218
1219 /* only process if transfer occurring */
1220 if (!transflag)
1221 return;
1222 cp = tmpline;
1223 if (getline(cp, 7, stdin) == NULL) {
1224 reply(221, "You could at least say goodbye.");
1225 dologout(0);
1226 }
1227 upper(cp);
1228 if (strcmp(cp, "ABOR\r\n") == 0) {
1229 tmpline[0] = '\0';
1230 reply(426, "Transfer aborted. Data connection closed.");
1231 reply(226, "Abort successful");
1232 longjmp(urgcatch, 1);
1233 }
1234 if (strcmp(cp, "STAT\r\n") == 0) {
1235 if (file_size != (off_t) -1)
1236 reply(213, "Status: %lu of %lu bytes transferred",
1237 byte_count, file_size);
1238 else
1239 reply(213, "Status: %lu bytes transferred", byte_count);
1240 }
1241}
1242
1243/*
1244 * Note: a response of 425 is not mentioned as a possible response to
1245 * the PASV command in RFC959. However, it has been blessed as
1246 * a legitimate response by Jon Postel in a telephone conversation
1247 * with Rick Adams on 25 Jan 89.
1248 */
1249passive()
1250{
1251 int len;
1252 register char *p, *a;
1253
1254 pdata = socket(AF_INET, SOCK_STREAM, 0);
1255 if (pdata < 0) {
1256 perror_reply(425, "Can't open passive connection");
1257 return;
1258 }
1259 pasv_addr = ctrl_addr;
1260 pasv_addr.sin_port = 0;
1261 (void) seteuid((uid_t)0);
1262 if (bind(pdata, (struct sockaddr *)&pasv_addr, sizeof(pasv_addr)) < 0) {
1263 (void) seteuid((uid_t)pw->pw_uid);
1264 goto pasv_error;
1265 }
1266 (void) seteuid((uid_t)pw->pw_uid);
1267 len = sizeof(pasv_addr);
1268 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
1269 goto pasv_error;
1270 if (listen(pdata, 1) < 0)
1271 goto pasv_error;
1272 a = (char *) &pasv_addr.sin_addr;
1273 p = (char *) &pasv_addr.sin_port;
1274
1275#define UC(b) (((int) b) & 0xff)
1276
1277 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
1278 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
1279 return;
1280
1281pasv_error:
1282 (void) close(pdata);
1283 pdata = -1;
1284 perror_reply(425, "Can't open passive connection");
1285 return;
1286}
1287
1288/*
1289 * Generate unique name for file with basename "local".
1290 * The file named "local" is already known to exist.
1291 * Generates failure reply on error.
1292 */
1293char *
1294gunique(local)
1295 char *local;
1296{
1297 static char new[MAXPATHLEN];
1298 struct stat st;
1299 char *cp = rindex(local, '/');
1300 int count = 0;
1301
1302 if (cp)
1303 *cp = '\0';
1304 if (stat(cp ? local : ".", &st) < 0) {
1305 perror_reply(553, cp ? local : ".");
1306 return((char *) 0);
1307 }
1308 if (cp)
1309 *cp = '/';
1310 (void) strcpy(new, local);
1311 cp = new + strlen(new);
1312 *cp++ = '.';
1313 for (count = 1; count < 100; count++) {
1314 (void) sprintf(cp, "%d", count);
1315 if (stat(new, &st) < 0)
1316 return(new);
1317 }
1318 reply(452, "Unique file name cannot be created.");
1319 return((char *) 0);
1320}
1321
1322/*
1323 * Format and send reply containing system error number.
1324 */
1325perror_reply(code, string)
1326 int code;
1327 char *string;
1328{
1329 reply(code, "%s: %s.", string, strerror(errno));
1330}
1331
1332static char *onefile[] = {
1333 "",
1334 0
1335};
1336
1337send_file_list(whichfiles)
1338 char *whichfiles;
1339{
1340 struct stat st;
1341 DIR *dirp = NULL;
1342 struct dirent *dir;
1343 FILE *dout = NULL;
1344 register char **dirlist, *dirname;
1345 int simple = 0;
1346 char *strpbrk();
1347
1348 if (strpbrk(whichfiles, "~{[*?") != NULL) {
1349 extern char **ftpglob(), *globerr;
1350
1351 globerr = NULL;
1352 dirlist = ftpglob(whichfiles);
1353 if (globerr != NULL) {
1354 reply(550, globerr);
1355 return;
1356 } else if (dirlist == NULL) {
1357 errno = ENOENT;
1358 perror_reply(550, whichfiles);
1359 return;
1360 }
1361 } else {
1362 onefile[0] = whichfiles;
1363 dirlist = onefile;
1364 simple = 1;
1365 }
1366
1367 if (setjmp(urgcatch)) {
1368 transflag = 0;
1369 return;
1370 }
1371 while (dirname = *dirlist++) {
1372 if (stat(dirname, &st) < 0) {
1373 /*
1374 * If user typed "ls -l", etc, and the client
1375 * used NLST, do what the user meant.
1376 */
1377 if (dirname[0] == '-' && *dirlist == NULL &&
1378 transflag == 0) {
1379 retrieve("/bin/ls %s", dirname);
1380 return;
1381 }
1382 perror_reply(550, whichfiles);
1383 if (dout != NULL) {
1384 (void) fclose(dout);
1385 transflag = 0;
1386 data = -1;
1387 pdata = -1;
1388 }
1389 return;
1390 }
1391
1392 if ((st.st_mode&S_IFMT) == S_IFREG) {
1393 if (dout == NULL) {
1394 dout = dataconn("file list", (off_t)-1, "w");
1395 if (dout == NULL)
1396 return;
1397 transflag++;
1398 }
1399 fprintf(dout, "%s%s\n", dirname,
1400 type == TYPE_A ? "\r" : "");
1401 byte_count += strlen(dirname) + 1;
1402 continue;
1403 } else if ((st.st_mode&S_IFMT) != S_IFDIR)
1404 continue;
1405
1406 if ((dirp = opendir(dirname)) == NULL)
1407 continue;
1408
1409 while ((dir = readdir(dirp)) != NULL) {
1410 char nbuf[MAXPATHLEN];
1411
1412 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
1413 continue;
1414 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
1415 dir->d_namlen == 2)
1416 continue;
1417
1418 sprintf(nbuf, "%s/%s", dirname, dir->d_name);
1419
1420 /*
1421 * We have to do a stat to insure it's
1422 * not a directory or special file.
1423 */
1424 if (simple || (stat(nbuf, &st) == 0 &&
1425 (st.st_mode&S_IFMT) == S_IFREG)) {
1426 if (dout == NULL) {
1427 dout = dataconn("file list", (off_t)-1,
1428 "w");
1429 if (dout == NULL)
1430 return;
1431 transflag++;
1432 }
1433 if (nbuf[0] == '.' && nbuf[1] == '/')
1434 fprintf(dout, "%s%s\n", &nbuf[2],
1435 type == TYPE_A ? "\r" : "");
1436 else
1437 fprintf(dout, "%s%s\n", nbuf,
1438 type == TYPE_A ? "\r" : "");
1439 byte_count += strlen(nbuf) + 1;
1440 }
1441 }
1442 (void) closedir(dirp);
1443 }
1444
1445 if (dout == NULL)
1446 reply(550, "No files found.");
1447 else if (ferror(dout) != 0)
1448 perror_reply(550, "Data connection");
1449 else
1450 reply(226, "Transfer complete.");
1451
1452 transflag = 0;
1453 if (dout != NULL)
1454 (void) fclose(dout);
1455 data = -1;
1456 pdata = -1;
1457}
1458
1459#ifdef SETPROCTITLE
1460/*
1461 * clobber argv so ps will show what we're doing.
1462 * (stolen from sendmail)
1463 * warning, since this is usually started from inetd.conf, it
1464 * often doesn't have much of an environment or arglist to overwrite.
1465 */
1466
1467/*VARARGS1*/
1468setproctitle(fmt, a, b, c)
1469char *fmt;
1470{
1471 register char *p, *bp, ch;
1472 register int i;
1473 char buf[BUFSIZ];
1474
1475 (void) sprintf(buf, fmt, a, b, c);
1476
1477 /* make ps print our process name */
1478 p = Argv[0];
1479 *p++ = '-';
1480
1481 i = strlen(buf);
1482 if (i > LastArgv - p - 2) {
1483 i = LastArgv - p - 2;
1484 buf[i] = '\0';
1485 }
1486 bp = buf;
1487 while (ch = *bp++)
1488 if (ch != '\n' && ch != '\r')
1489 *p++ = ch;
1490 while (p < LastArgv)
1491 *p++ = ' ';
1492}
1493#endif /* SETPROCTITLE */