1 /* opieftpd.c: Main program for an FTP daemon.
3 %%% portions-copyright-cmetz-96
4 Portions of this software are Copyright 1996-1999 by Craig Metz, All Rights
5 Reserved. The Inner Net License Version 2 applies to these portions of
7 You should have received a copy of the license with this software. If
8 you didn't get a copy, you may request one from <license@inner.net>.
10 Portions of this software are Copyright 1995 by Randall Atkinson and Dan
11 McDonald, All Rights Reserved. All Rights under this copyright are assigned
12 to the U.S. Naval Research Laboratory (NRL). The NRL Copyright Notice and
13 License Agreement applies to this software.
17 Modified by cmetz for OPIE 2.4. Add id parameter to opielogwtmp. Use
18 opiestrncpy(). Fix incorrect use of setproctitle().
19 Modified by cmetz for OPIE 2.32. Remove include of dirent.h here; it's
20 done already (and conditionally) in opie_cfg.h.
21 Modified by cmetz for OPIE 2.31. Merged in some 4.4BSD-Lite changes.
22 Merged in a security fix to BSD-derived ftpds.
23 Modified by cmetz for OPIE 2.3. Fixed the filename at the top.
24 Moved LS_COMMAND here.
25 Modified by cmetz for OPIE 2.2. Use FUNCTION definition et al.
26 Removed useless strings (I don't think that removing the
27 ucb copyright one is a problem -- please let me know if
28 I'm wrong). Changed default CMASK to 077. Removed random
29 comments. Use ANSI stdargs for reply/lreply if we can,
30 added stdargs version of reply/lreply. Don't declare the
31 tos variable unless IP_TOS defined. Include stdargs headers
32 early. More headers ifdefed. Made everything static.
33 Got rid of gethostname() call and use of hostname. Pared
34 down status response for places where header files frequently
35 cause trouble. Made logging of user logins (ala -l)
36 non-optional. Moved reply()/lrepy(). Fixed some prototypes.
37 Modified at NRL for OPIE 2.1. Added declaration of envp. Discard
38 result of opiechallenge (allows access control to work).
39 Added patches for AIX. Symbol changes for autoconf.
40 Modified at NRL for OPIE 2.01. Changed password lookup handling
41 to avoid problems with drain-bamaged shadow password packages.
42 Properly handle internal state for anonymous FTP. Unlock
43 user accounts properly if login fails because of /etc/shells.
44 Make sure to close syslog by function to avoid problems with
45 drain bamaged syslog implementations.
46 Modified at NRL for OPIE 2.0.
47 Originally from BSD Net/2.
49 There is some really, really ugly code in here.
51 $FreeBSD: head/contrib/opie/opieftpd.c 92914 2002-03-21 23:42:52Z markm $
54 * Copyright (c) 1985, 1988, 1990 Regents of the University of California.
55 * All rights reserved.
57 * Redistribution and use in source and binary forms, with or without
58 * modification, are permitted provided that the following conditions
60 * 1. Redistributions of source code must retain the above copyright
61 * notice, this list of conditions and the following disclaimer.
62 * 2. Redistributions in binary form must reproduce the above copyright
63 * notice, this list of conditions and the following disclaimer in the
64 * documentation and/or other materials provided with the distribution.
65 * 3. All advertising materials mentioning features or use of this software
66 * must display the following acknowledgement:
67 * This product includes software developed by the University of
68 * California, Berkeley and its contributors.
69 * 4. Neither the name of the University nor the names of its contributors
70 * may be used to endorse or promote products derived from this software
71 * without specific prior written permission.
73 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
74 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
75 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
76 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
77 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
78 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
79 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
80 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
81 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
82 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
90 #endif /* HAVE_ANSISTDARG */
97 #include <sys/param.h>
98 #endif /* HAVE_SYS_PARAM_H */
100 /* #include <sys/ioctl.h> */
101 #include <sys/socket.h>
102 #include <sys/wait.h>
104 #include <sys/fcntl.h>
107 #endif /* SYS_FCNTL_H */
108 #include <sys/types.h>
110 #include <netinet/in.h>
111 #include <netinet/in_systm.h>
112 #include <netinet/ip.h>
115 #include <arpa/ftp.h>
116 #include <arpa/inet.h>
117 #include <arpa/telnet.h>
123 #endif /* HAVE_TIME_H */
126 #endif /* HAVE_PWD_H */
133 #endif /* HAVE_UNISTD_H */
144 #endif /* HAVE_SHADOW_H */
148 #endif /* HAVE_CRYPT_H */
150 #if HAVE_SYS_UTSNAME_H
151 #include <sys/utsname.h>
152 #endif /* HAVE_SYS_UTSNAME_H */
156 #include <sys/priv.h>
160 #ifndef IPTOS_THROUGHPUT
162 #endif /* !IPTOS_THROUGHPUT */
163 #ifndef IPTOS_LOWDELAY
165 #endif /* !IPTOS_LOWDELAY */
169 extern char *home
; /* pointer to home directory for glob */
170 extern FILE *ftpd_popen
__P((char *, char *));
171 extern int ftpd_pclose
__P((FILE *));
173 extern off_t restart_point
;
175 static struct sockaddr_in ctrl_addr
;
176 static struct sockaddr_in data_source
;
177 struct sockaddr_in data_dest
;
178 struct sockaddr_in his_addr
;
179 static struct sockaddr_in pasv_addr
;
183 static jmp_buf urgcatch
;
187 int timeout
= 900; /* timeout after 15 minutes of inactivity */
188 int maxtimeout
= 7200; /* don't allow idle time to be set beyond 2 hours */
192 #endif /* DOANONYMOUS */
195 static int stru
; /* avoid C keyword */
197 int usedefault
= 1; /* for data transfers */
198 int pdata
= -1; /* for passive mode */
199 static int transflag
;
200 static off_t file_size
;
201 static off_t byte_count
;
203 #if (!defined(CMASK) || CMASK == 0)
208 static int defumask
= CMASK
; /* default umask value */
210 char remotehost
[MAXHOSTNAMELEN
];
213 * Timeout intervals for retrying connections
214 * to hosts that don't accept PORT cmds. This
215 * is a kludge, but given the problems with TCP...
217 #define SWAITMAX 90 /* wait at most 90 seconds */
218 #define SWAITINT 5 /* interval between retries */
220 static int swaitmax
= SWAITMAX
;
221 static int swaitint
= SWAITINT
;
224 static char **Argv
= NULL
; /* pointer to argument vector */
225 static char *LastArgv
= NULL
; /* end of argv */
226 static char proctitle
[BUFSIZ
]; /* initial part of title */
229 static int af_pwok
= 0, pwok
= 0;
230 static struct opie opiestate
;
232 VOIDRET perror_reply
__P((int, char *));
233 VOIDRET dologout
__P((int));
234 char *getline
__P((char *, int, FILE *));
235 VOIDRET upper
__P((char *));
237 static VOIDRET lostconn
__P((int));
238 static VOIDRET myoob
__P((int));
239 static FILE *getdatasock
__P((char *));
240 static FILE *dataconn
__P((char *, off_t
, char *));
241 static int checkuser
__P((char *));
242 static VOIDRET end_login
__P((void));
243 static VOIDRET send_data
__P((FILE *, FILE *, off_t
));
244 static int receive_data
__P((FILE *, FILE *));
245 static char *gunique
__P((char *));
246 static char *sgetsave
__P((char *));
248 int opielogwtmp
__P((char *, char *, char *, char *));
250 int fclose
__P((FILE *));
252 #ifdef HAVE_ANSISTDARG
253 VOIDRET reply
FUNCTION((stdarg is ANSI only
), int n AND
char *fmt AND
...)
259 vsprintf(buffer
, fmt
, ap
);
262 printf("%d %s\r\n", n
, buffer
);
265 syslog(LOG_DEBUG
, "<--- %d %s", n
, buffer
);
267 #else /* HAVE_ANSISTDARG */
268 VOIDRET reply
FUNCTION((n
, fmt
, p0
, p1
, p2
, p3
, p4
, p5
), int n AND
char *fmt AND
int p0 AND
int p1 AND
int p2 AND
int p3 AND
int p4 AND
int p5
)
271 printf(fmt
, p0
, p1
, p2
, p3
, p4
, p5
);
275 syslog(LOG_DEBUG
, "<--- %d ", n
);
276 syslog(LOG_DEBUG
, fmt
, p0
, p1
, p2
, p3
, p4
, p5
);
279 #endif /* HAVE_ANSISTDARG */
281 #ifdef HAVE_ANSISTDARG
282 VOIDRET lreply
FUNCTION((stdarg is ANSI only
), int n AND
char *fmt AND
...)
288 vsprintf(buffer
, fmt
, ap
);
291 printf("%d- %s\r\n", n
, buffer
);
294 syslog(LOG_DEBUG
, "<--- %d- %s", n
, buffer
);
296 #else /* HAVE_ANSISTDARG */
297 VOIDRET lreply
FUNCTION((n
, fmt
, p0
, p1
, p2
, p3
, p4
, p5
), int n AND
char *fmt AND
int p0 AND
int p1 AND
int p2 AND
int p3 AND
int p4 AND
int p5
)
300 printf(fmt
, p0
, p1
, p2
, p3
, p4
, p5
);
304 syslog(LOG_DEBUG
, "<--- %d- ", n
);
305 syslog(LOG_DEBUG
, fmt
, p0
, p1
, p2
, p3
, p4
, p5
);
308 #endif /* HAVE_ANSISTDARG */
310 VOIDRET enable_signalling FUNCTION_NOARGS
312 signal(SIGPIPE
, lostconn
);
313 if ((int)signal(SIGURG
, myoob
) < 0)
314 syslog(LOG_ERR
, "signal: %m");
317 VOIDRET disable_signalling FUNCTION_NOARGS
319 signal(SIGPIPE
, SIG_IGN
);
320 if ((int)signal(SIGURG
, SIG_IGN
) < 0)
321 syslog(LOG_ERR
, "signal: %m");
324 static VOIDRET lostconn
FUNCTION((input
), int input
)
327 syslog(LOG_DEBUG
, "lost connection");
331 static char ttyline
[20];
334 * Helper function for sgetpwnam().
336 static char *sgetsave
FUNCTION((s
), char *s
)
338 char *new = malloc((unsigned) strlen(s
) + 1);
341 perror_reply(421, "Local resource failure: malloc");
350 * Save the result of a getpwnam. Used for USER command, since
351 * the data returned must not be clobbered by any other command
354 static struct passwd
*sgetpwnam
FUNCTION((name
), char *name
)
356 static struct passwd save
;
357 register struct passwd
*p
;
361 #endif /* HAVE_SHADOW */
363 if ((p
= getpwnam(name
)) == NULL
)
367 if ((spwd
= getspnam(name
)) == NULL
)
372 p
->pw_passwd
= spwd
->sp_pwdp
;
373 #endif /* HAVE_SHADOW */
379 free(save
.pw_passwd
);
385 save
.pw_name
= sgetsave(p
->pw_name
);
386 save
.pw_passwd
= sgetsave(p
->pw_passwd
);
387 save
.pw_gecos
= sgetsave(p
->pw_gecos
);
388 save
.pw_dir
= sgetsave(p
->pw_dir
);
389 save
.pw_shell
= sgetsave(p
->pw_shell
);
393 int login_attempts
; /* number of failed login attempts */
394 int askpasswd
; /* had user command, ask for passwd */
398 * Sets global passwd pointer pw if named account exists and is acceptable;
399 * sets askpasswd if a PASS command is expected. If logged in previously,
400 * need to reset state. If name is "ftp" or "anonymous", the name is not in
401 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
402 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
403 * requesting login privileges. Disallow anyone who does not have a standard
404 * shell as returned by getusershell(). Disallow anyone mentioned in the file
405 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
407 int user
FUNCTION((name
), char *name
)
415 reply(530, "Can't change user from guest login.");
418 #endif /* DOANONMOUS */
424 if (!strcmp(name
, "ftp") || !strcmp(name
, "anonymous"))
425 if (!checkuser("ftp") && !checkuser("anonymous"))
426 if ((pw
= sgetpwnam("ftp")) != NULL
) {
429 reply(331, "Guest login ok, send your e-mail address as your password.");
430 syslog(LOG_INFO
, "Anonymous FTP connection made from host %s.", remotehost
);
433 #endif /* DOANONYMOUS */
434 if (pw
= sgetpwnam(name
)) {
435 if ((shell
= pw
->pw_shell
) == NULL
|| *shell
== 0)
436 shell
= _PATH_BSHELL
;
437 while ((cp
= getusershell()) != NULL
)
438 if (!strcmp(cp
, shell
))
441 if (cp
== NULL
|| checkuser(name
) || ((pw
->pw_passwd
[0] == '*') || (pw
->pw_passwd
[0] == '#'))) {
444 syslog(LOG_DEBUG
, "Couldn't find %s in the list of valid shells.", pw
->pw_shell
);
446 syslog(LOG_DEBUG
, "checkuser failed - user in /etc/ftpusers?");
447 if (((pw
->pw_passwd
[0] == '*') || (pw
->pw_passwd
[0] == '#')))
448 syslog(LOG_DEBUG
, "Login disabled: pw_passwd == %s", pw
->pw_passwd
);
450 pw
= (struct passwd
*) NULL
;
455 char prompt
[OPIE_CHALLENGE_MAX
+ 1];
457 opiechallenge(&opiestate
, name
, prompt
);
459 if (askpasswd
== -1) {
460 syslog(LOG_WARNING
, "Invalid FTP user name %s attempted from %s.", name
, remotehost
);
463 pwok
= af_pwok
&& opiealways(pw
->pw_dir
);
466 reply(331, "Response to %s %s for %s.", prompt
,
467 #else /* NEW_PROMPTS */
468 reply(331, "OTP response %s %s for %s.", prompt
,
469 #endif /* NEW_PROMPTS */
470 pwok
? "requested" : "required", name
);
472 /* Delay before reading passwd after first failed attempt to slow down
473 passwd-guessing programs. */
475 sleep((unsigned) login_attempts
);
481 * Check if a user is in the file _PATH_FTPUSERS
483 static int checkuser
FUNCTION((name
), char *name
)
489 if ((fd
= fopen(_PATH_FTPUSERS
, "r")) != NULL
) {
490 while (fgets(line
, sizeof(line
), fd
) != NULL
)
491 if ((p
= strchr(line
, '\n')) != NULL
) {
495 if (!strcmp(line
, name
)) {
506 * Terminate login as previous user, if any, resetting state;
507 * used when USER command is given or login fails.
509 static VOIDRET end_login FUNCTION_NOARGS
511 disable_signalling();
512 if (seteuid((uid_t
) 0))
513 syslog(LOG_ERR
, "Can't set euid");
515 opielogwtmp(ttyline
, "", "", "ftp");
520 #endif /* DOANONYMOUS */
524 VOIDRET pass
FUNCTION((passwd
), char *passwd
)
526 int legit
= askpasswd
+ 1, i
;
528 if (logged_in
|| askpasswd
== 0) {
529 reply(503, "Login with USER first.");
535 if (!guest
) { /* "ftp" is only account allowed no password */
536 #endif /* DOANONYMOUS */
537 i
= opieverify(&opiestate
, passwd
);
538 if (legit
&& i
&& pwok
)
539 i
= strcmp(crypt(passwd
, pw
->pw_passwd
), pw
->pw_passwd
);
541 reply(530, "Login incorrect.");
543 if (login_attempts
++ >= 5) {
545 "Repeated login failures for user %s from %s",
546 pw
->pw_name
, remotehost
);
553 if ((passwd
[0] <= ' ') || checkuser(passwd
)) {
554 reply(530, "No identity, no service.");
555 syslog(LOG_DEBUG
, "Bogus address: %s", passwd
);
558 #endif /* DOANONYMOUS */
559 login_attempts
= 0; /* this time successful */
560 if (setegid((gid_t
) pw
->pw_gid
) < 0) {
561 reply(550, "Can't set gid.");
562 syslog(LOG_DEBUG
, "gid = %d, errno = %s(%d)", pw
->pw_gid
, strerror(errno
), errno
);
565 initgroups(pw
->pw_name
, pw
->pw_gid
);
567 /* open wtmp before chroot */
568 sprintf(ttyline
, "ftp%d", getpid());
569 opielogwtmp(ttyline
, pw
->pw_name
, remotehost
, "ftp");
574 /* We MUST do a chdir() after the chroot. Otherwise the old current
575 directory will be accessible as "." outside the new root! */
576 if (chroot(pw
->pw_dir
) < 0 || chdir("/") < 0) {
577 reply(550, "Can't set guest privileges.");
581 #endif /* DOANONYMOUS */
582 if (chdir(pw
->pw_dir
) < 0) {
583 if (chdir("/") < 0) {
584 reply(530, "User %s: can't change directory to %s.",
585 pw
->pw_name
, pw
->pw_dir
);
588 lreply(230, "No directory! Logging in with home=/");
590 /* This patch was contributed by an OPIE user. We don't know what it
591 does, exactly. It may or may not work. */
597 setgroups(NULL
, NULL
);
598 if (setpriv(PRIV_SET
|PRIV_INHERITED
|PRIV_EFFECTIVE
|PRIV_BEQUEATH
,
599 &priv
, sizeof(priv_t
)) < 0 ||
600 setgidx(ID_REAL
|ID_EFFECTIVE
, (gid_t
)pw
->pw_gid
) < 0 ||
601 setuidx(ID_REAL
|ID_EFFECTIVE
, (uid_t
)pw
->pw_uid
) < 0 ||
602 seteuid((uid_t
)pw
->pw_uid
) < 0) {
603 reply(550, "Can't set uid (_AIX3).");
608 if (seteuid((uid_t
) pw
->pw_uid
) < 0) {
609 reply(550, "Can't set uid.");
614 * Display a login message, if it exists.
615 * N.B. reply(230,) must follow the message.
620 if ((fd
= fopen(_PATH_FTPLOGINMESG
, "r")) != NULL
) {
623 while (fgets(line
, sizeof(line
), fd
) != NULL
) {
624 if ((cp
= strchr(line
, '\n')) != NULL
)
626 lreply(230, "%s", line
);
628 (void) fflush(stdout
);
634 reply(230, "Guest login ok, access restrictions apply.");
636 setproctitle("%s: anonymous/%.*s", remotehost
,
637 sizeof(proctitle
) - sizeof(remotehost
) - sizeof(": anonymous/"),
640 syslog(LOG_NOTICE
, "ANONYMOUS FTP login from %s with ID %s",
643 #endif /* DOANONYMOUS */
645 reply(230, "User %s logged in.", pw
->pw_name
);
648 setproctitle("%s: %s", remotehost
, pw
->pw_name
);
650 syslog(LOG_INFO
, "FTP login from %s with user name %s", remotehost
, pw
->pw_name
);
652 home
= pw
->pw_dir
; /* home dir for globbing */
657 /* Forget all about it... */
661 VOIDRET retrieve
FUNCTION((cmd
, name
), char *cmd AND
char *name
)
668 fin
= fopen(name
, "r"), closefunc
= fclose
;
673 snprintf(line
, sizeof(line
), cmd
, name
);
675 fin
= ftpd_popen(line
, "r"), closefunc
= ftpd_pclose
;
678 st
.st_blksize
= BUFSIZ
;
679 #endif /* HAVE_ST_BLKSIZE */
683 perror_reply(550, name
);
687 (fstat(fileno(fin
), &st
) < 0 || (st
.st_mode
& S_IFMT
) != S_IFREG
)) {
688 reply(550, "%s: not a plain file.", name
);
692 if (type
== TYPE_A
) {
693 register int i
, n
, c
;
698 if ((c
= getc(fin
)) == EOF
) {
699 perror_reply(550, name
);
706 if (lseek(fileno(fin
), restart_point
, SEEK_SET
/* L_SET */ ) < 0) {
707 perror_reply(550, name
);
711 dout
= dataconn(name
, st
.st_size
, "w");
715 send_data(fin
, dout
, st
.st_blksize
);
716 #else /* HAVE_ST_BLKSIZE */
717 send_data(fin
, dout
, BUFSIZ
);
718 #endif /* HAVE_ST_BLKSIZE */
726 VOIDRET store
FUNCTION((name
, mode
, unique
), char *name AND
char *mode AND
int unique
)
732 if (unique
&& stat(name
, &st
) == 0 &&
733 (name
= gunique(name
)) == NULL
)
738 fout
= fopen(name
, mode
);
741 perror_reply(553, name
);
745 if (type
== TYPE_A
) {
746 register int i
, n
, c
;
751 if ((c
= getc(fout
)) == EOF
) {
752 perror_reply(550, name
);
758 /* We must do this seek to "current" position because we are changing
759 from reading to writing. */
760 if (fseek(fout
, 0L, SEEK_CUR
/* L_INCR */ ) < 0) {
761 perror_reply(550, name
);
765 if (lseek(fileno(fout
), restart_point
, SEEK_SET
/* L_SET */ ) < 0) {
766 perror_reply(550, name
);
770 din
= dataconn(name
, (off_t
) - 1, "r");
773 if (receive_data(din
, fout
) == 0) {
775 reply(226, "Transfer complete (unique file name:%s).",
778 reply(226, "Transfer complete.");
787 static FILE *getdatasock
FUNCTION((mode
), char *mode
)
789 int s
, on
= 1, tries
;
792 return (fdopen(data
, mode
));
793 disable_signalling();
794 if (seteuid((uid_t
) 0))
795 syslog(LOG_ERR
, "Can't set euid");
796 s
= socket(AF_INET
, SOCK_STREAM
, 0);
799 if (setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
,
800 (char *) &on
, sizeof(on
)) < 0)
802 /* anchor socket to avoid multi-homing problems */
803 data_source
.sin_family
= AF_INET
;
804 data_source
.sin_addr
= ctrl_addr
.sin_addr
;
805 for (tries
= 1;; tries
++) {
806 if (bind(s
, (struct sockaddr
*) & data_source
,
807 sizeof(data_source
)) >= 0)
809 if (errno
!= EADDRINUSE
|| tries
> 10)
813 if (seteuid((uid_t
) pw
->pw_uid
))
814 syslog(LOG_ERR
, "Can't set euid");
817 on
= IPTOS_THROUGHPUT
;
818 if (setsockopt(s
, IPPROTO_IP
, IP_TOS
, (char *) &on
, sizeof(int)) < 0)
819 syslog(LOG_WARNING
, "setsockopt (IP_TOS): %m");
821 return (fdopen(s
, mode
));
826 if (seteuid((uid_t
) pw
->pw_uid
))
827 syslog(LOG_ERR
, "Can't set euid");
836 static FILE *dataconn
FUNCTION((name
, size
, mode
), char *name AND off_t size AND
char *mode
)
847 if (size
!= (off_t
) - 1)
848 snprintf(sizebuf
, sizeof(sizebuf
), " (%ld bytes)", size
);
852 struct sockaddr_in from
;
853 int s
, fromlen
= sizeof(from
);
855 s
= accept(pdata
, (struct sockaddr
*) & from
, &fromlen
);
857 reply(425, "Can't open data connection.");
865 tos
= IPTOS_LOWDELAY
;
866 setsockopt(s
, IPPROTO_IP
, IP_TOS
, (char *) &tos
,
870 reply(150, "Opening %s mode data connection for %s%s.",
871 type
== TYPE_A
? "ASCII" : "BINARY", name
, sizebuf
);
872 return (fdopen(pdata
, mode
));
875 reply(125, "Using existing data connection for %s%s.",
878 return (fdopen(data
, mode
));
881 data_dest
= his_addr
;
883 file
= getdatasock(mode
);
885 reply(425, "Can't create data socket (%s,%d): %s.",
886 inet_ntoa(data_source
.sin_addr
),
887 ntohs(data_source
.sin_port
), strerror(errno
));
891 while (connect(data
, (struct sockaddr
*) & data_dest
,
892 sizeof(data_dest
)) < 0) {
893 if (errno
== EADDRINUSE
&& retry
< swaitmax
) {
894 sleep((unsigned) swaitint
);
898 perror_reply(425, "Can't build data connection");
903 reply(150, "Opening %s mode data connection for %s%s.",
904 type
== TYPE_A
? "ASCII" : "BINARY", name
, sizebuf
);
909 * Tranfer the contents of "instr" to
910 * "outstr" peer using the appropriate
911 * encapsulation of the data subject
912 * to Mode, Structure, and Type.
914 * NB: Form isn't handled.
916 static VOIDRET send_data
FUNCTION((instr
, outstr
, blksize
), FILE *instr AND
FILE *outstr AND off_t blksize
)
923 if (setjmp(urgcatch
)) {
930 while ((c
= getc(instr
)) != EOF
) {
945 reply(226, "Transfer complete.");
950 if ((buf
= malloc((u_int
) blksize
)) == NULL
) {
952 perror_reply(451, "Local resource failure: malloc");
955 netfd
= fileno(outstr
);
956 filefd
= fileno(instr
);
957 while ((cnt
= read(filefd
, buf
, (u_int
) blksize
)) > 0 &&
958 write(netfd
, buf
, cnt
) == cnt
)
967 reply(226, "Transfer complete.");
971 reply(550, "Unimplemented TYPE %d in send_data", type
);
977 perror_reply(426, "Data connection");
982 perror_reply(551, "Error on input file");
986 * Transfer data from peer to
987 * "outstr" using the appropriate
988 * encapulation of the data subject
989 * to Mode, Structure, and Type.
991 * N.B.: Form isn't handled.
993 static int receive_data
FUNCTION((instr
, outstr
), FILE *instr AND
FILE *outstr
)
996 int cnt
, bare_lfs
= 0;
1000 if (setjmp(urgcatch
)) {
1008 while ((cnt
= read(fileno(instr
), buf
, sizeof buf
)) > 0) {
1009 if (write(fileno(outstr
), buf
, cnt
) != cnt
)
1019 reply(553, "TYPE E not implemented.");
1024 while ((c
= getc(instr
)) != EOF
) {
1031 if ((c
= getc(instr
)) != '\n') {
1033 if (c
== '\0' || c
== EOF
)
1047 lreply(230, "WARNING! %d bare linefeeds received in ASCII mode", bare_lfs
);
1048 printf(" File may not have transferred correctly.\r\n");
1052 reply(550, "Unimplemented TYPE %d in receive_data", type
);
1059 perror_reply(426, "Data Connection");
1064 perror_reply(452, "Error writing file");
1068 VOIDRET statfilecmd
FUNCTION((filename
), char *filename
)
1075 snprintf(line
, sizeof(line
), "%s %s", "/bin/ls -lgA", filename
);
1076 #else /* HAVE_LS_G_FLAG */
1077 snprintf(line
, sizeof(line
), "%s %s", "/bin/ls -lA", filename
);
1078 #endif /* HAVE_LS_G_FLAG */
1079 fin
= ftpd_popen(line
, "r");
1080 lreply(211, "status of %s:", filename
);
1081 while ((c
= getc(fin
)) != EOF
) {
1083 if (ferror(stdout
)) {
1084 perror_reply(421, "control connection");
1090 perror_reply(551, filename
);
1099 reply(211, "End of Status");
1102 VOIDRET statcmd FUNCTION_NOARGS
1104 /* COMMENTED OUT STUFF BECAUSE THINGS BROKE ON SUNOS. */
1105 struct sockaddr_in
*sin
;
1108 lreply(211, "FTP server status:");
1110 printf(" Connected to %s", remotehost
);
1111 if (!isdigit(remotehost
[0]))
1112 printf(" (%s)", inet_ntoa(his_addr
.sin_addr
));
1117 printf(" Logged in anonymously\r\n");
1119 #endif /* DOANONYMOUS */
1120 printf(" Logged in as %s\r\n", pw
->pw_name
);
1123 printf(" Waiting for password\r\n");
1125 printf(" Waiting for user name\r\n");
1127 printf(" Data connection open\r\n");
1130 printf(" in Passive mode");
1134 if (usedefault
== 0) {
1138 a
= (u_char
*) & sin
->sin_addr
;
1139 p
= (u_char
*) & sin
->sin_port
;
1140 #define UC(b) (((int) b) & 0xff)
1141 printf(" (%d,%d,%d,%d,%d,%d)\r\n", UC(a
[0]),
1142 UC(a
[1]), UC(a
[2]), UC(a
[3]), UC(p
[0]), UC(p
[1]));
1145 printf(" No data connection\r\n");
1146 reply(211, "End of status");
1149 VOIDRET opiefatal
FUNCTION((s
), char *s
)
1151 reply(451, "Error in server: %s\n", s
);
1152 reply(221, "Closing connection due to server error.");
1157 static VOIDRET ack
FUNCTION((s
), char *s
)
1159 reply(250, "%s command successful.", s
);
1162 VOIDRET nack
FUNCTION((s
), char *s
)
1164 reply(502, "%s command not implemented.", s
);
1167 VOIDRET yyerror
FUNCTION((s
), char *s
)
1171 if (cp
= strchr(cbuf
, '\n'))
1173 reply(500, "'%s': command not understood.", cbuf
);
1176 VOIDRET
delete FUNCTION((name
), char *name
)
1180 if (stat(name
, &st
) < 0) {
1181 perror_reply(550, name
);
1184 if ((st
.st_mode
& S_IFMT
) == S_IFDIR
) {
1185 if (rmdir(name
) < 0) {
1186 perror_reply(550, name
);
1191 if (unlink(name
) < 0) {
1192 perror_reply(550, name
);
1199 VOIDRET cwd
FUNCTION((path
), char *path
)
1201 if (chdir(path
) < 0)
1202 perror_reply(550, path
);
1207 VOIDRET makedir
FUNCTION((name
), char *name
)
1209 if (mkdir(name
, 0777) < 0)
1210 perror_reply(550, name
);
1212 reply(257, "MKD command successful.");
1215 VOIDRET removedir
FUNCTION((name
), char *name
)
1217 if (rmdir(name
) < 0)
1218 perror_reply(550, name
);
1223 VOIDRET pwd FUNCTION_NOARGS
1225 char path
[MAXPATHLEN
+ 1];
1227 if (getcwd(path
, MAXPATHLEN
) == (char *) NULL
)
1228 reply(550, "%s.", path
);
1230 reply(257, "\"%s\" is current directory.", path
);
1233 char *renamefrom
FUNCTION((name
), char *name
)
1237 if (stat(name
, &st
) < 0) {
1238 perror_reply(550, name
);
1239 return ((char *) 0);
1241 reply(350, "File exists, ready for destination name");
1245 VOIDRET renamecmd
FUNCTION((from
, to
), char *from AND
char *to
)
1247 if (rename(from
, to
) < 0)
1248 perror_reply(550, "rename");
1253 static VOIDRET dolog
FUNCTION((sin
), struct sockaddr_in
*sin
)
1255 struct hostent
*hp
= gethostbyaddr((char *) &sin
->sin_addr
,
1256 sizeof(struct in_addr
), AF_INET
);
1260 opiestrncpy(remotehost
, hp
->h_name
, sizeof(remotehost
));
1262 opiestrncpy(remotehost
, inet_ntoa(sin
->sin_addr
), sizeof(remotehost
));
1264 setproctitle("%s: connected", remotehost
);
1265 #endif /* DOTITLE */
1267 t
= time((time_t *) 0);
1268 syslog(LOG_INFO
, "connection from %s at %s",
1269 remotehost
, ctime(&t
));
1273 * Record logout in wtmp file
1274 * and exit with supplied status.
1276 VOIDRET dologout
FUNCTION((status
), int status
)
1278 disable_signalling();
1280 if (seteuid((uid_t
) 0))
1281 syslog(LOG_ERR
, "Can't set euid");
1282 opielogwtmp(ttyline
, "", "", "ftp");
1284 /* beware of flushing buffers after a SIGPIPE */
1288 static VOIDRET myoob
FUNCTION((input
), int input
)
1292 /* only process if transfer occurring */
1296 if (getline(cp
, 7, stdin
) == NULL
) {
1297 reply(221, "You could at least say goodbye.");
1301 if (strcmp(cp
, "ABOR\r\n") == 0) {
1303 reply(426, "Transfer aborted. Data connection closed.");
1304 reply(226, "Abort successful");
1305 longjmp(urgcatch
, 1);
1307 if (strcmp(cp
, "STAT\r\n") == 0) {
1308 if (file_size
!= (off_t
) - 1)
1309 reply(213, "Status: %lu of %lu bytes transferred",
1310 byte_count
, file_size
);
1312 reply(213, "Status: %lu bytes transferred", byte_count
);
1317 * Note: a response of 425 is not mentioned as a possible response to
1318 * the PASV command in RFC959. However, it has been blessed as
1319 * a legitimate response by Jon Postel in a telephone conversation
1320 * with Rick Adams on 25 Jan 89.
1322 VOIDRET passive FUNCTION_NOARGS
1325 register char *p
, *a
;
1327 pdata
= socket(AF_INET
, SOCK_STREAM
, 0);
1329 perror_reply(425, "Can't open passive connection");
1332 pasv_addr
= ctrl_addr
;
1333 pasv_addr
.sin_port
= 0;
1334 if (seteuid((uid_t
) 0))
1335 syslog(LOG_ERR
, "Can't set euid");
1336 if (bind(pdata
, (struct sockaddr
*) & pasv_addr
, sizeof(pasv_addr
)) < 0) {
1337 seteuid((uid_t
) pw
->pw_uid
);
1340 if (seteuid((uid_t
) pw
->pw_uid
))
1341 syslog(LOG_ERR
, "Can't set euid");
1342 len
= sizeof(pasv_addr
);
1343 if (getsockname(pdata
, (struct sockaddr
*) & pasv_addr
, &len
) < 0)
1345 if (listen(pdata
, 1) < 0)
1347 a
= (char *) &pasv_addr
.sin_addr
;
1348 p
= (char *) &pasv_addr
.sin_port
;
1350 #define UC(b) (((int) b) & 0xff)
1352 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a
[0]),
1353 UC(a
[1]), UC(a
[2]), UC(a
[3]), UC(p
[0]), UC(p
[1]));
1359 perror_reply(425, "Can't open passive connection");
1364 * Generate unique name for file with basename "local".
1365 * The file named "local" is already known to exist.
1366 * Generates failure reply on error.
1368 static char *gunique
FUNCTION((local
), char *local
)
1370 static char new[MAXPATHLEN
+1];
1372 char *cp
= strrchr(local
, '/');
1377 if (stat(cp
? local
: ".", &st
) < 0) {
1378 perror_reply(553, cp
? local
: ".");
1379 return ((char *) 0);
1384 cp
= new + strlen(new);
1386 for (count
= 1; count
< 100; count
++) {
1387 snprintf(cp
, sizeof(new) - (cp
- new), "%d", count
);
1388 if (stat(new, &st
) < 0)
1391 reply(452, "Unique file name cannot be created.");
1392 return ((char *) 0);
1396 * Format and send reply containing system error number.
1398 VOIDRET perror_reply
FUNCTION((code
, string
), int code AND
char *string
)
1400 reply(code
, "%s: %s.", string
, strerror(errno
));
1403 static char *onefile
[] =
1409 VOIDRET send_file_list
FUNCTION((whichfiles
), char *whichfiles
)
1415 register char **dirlist
, *dirname
;
1418 if (strpbrk(whichfiles
, "~{[*?") != NULL
) {
1419 extern char **ftpglob(), *globerr
;
1422 dirlist
= ftpglob(whichfiles
);
1423 if (globerr
!= NULL
) {
1424 reply(550, globerr
);
1427 if (dirlist
== NULL
) {
1429 perror_reply(550, whichfiles
);
1433 onefile
[0] = whichfiles
;
1438 if (setjmp(urgcatch
)) {
1442 while (dirname
= *dirlist
++) {
1443 if (stat(dirname
, &st
) < 0) {
1444 /* If user typed "ls -l", etc, and the client used NLST, do what the
1446 if (dirname
[0] == '-' && *dirlist
== NULL
&&
1448 retrieve("/bin/ls %s", dirname
);
1451 perror_reply(550, whichfiles
);
1460 if ((st
.st_mode
& S_IFMT
) == S_IFREG
) {
1462 dout
= dataconn("file list", (off_t
) - 1, "w");
1467 fprintf(dout
, "%s%s\n", dirname
,
1468 type
== TYPE_A
? "\r" : "");
1469 byte_count
+= strlen(dirname
) + 1;
1472 if ((st
.st_mode
& S_IFMT
) != S_IFDIR
)
1475 if ((dirp
= opendir(dirname
)) == NULL
)
1478 while ((dir
= readdir(dirp
)) != NULL
) {
1479 char nbuf
[MAXPATHLEN
+1];
1481 if (dir
->d_name
[0] == '.' && (strlen(dir
->d_name
) == 1))
1483 if (dir
->d_name
[0] == '.' && dir
->d_name
[1] == '.' &&
1484 (strlen(dir
->d_name
) == 2))
1487 snprintf(nbuf
, sizeof(nbuf
), "%s/%s", dirname
, dir
->d_name
);
1489 /* We have to do a stat to insure it's not a directory or special file. */
1490 if (simple
|| (stat(nbuf
, &st
) == 0 &&
1491 (st
.st_mode
& S_IFMT
) == S_IFREG
)) {
1493 dout
= dataconn("file list", (off_t
) - 1, "w");
1498 if (nbuf
[0] == '.' && nbuf
[1] == '/')
1499 fprintf(dout
, "%s%s\n", &nbuf
[2],
1500 type
== TYPE_A
? "\r" : "");
1502 fprintf(dout
, "%s%s\n", nbuf
,
1503 type
== TYPE_A
? "\r" : "");
1504 byte_count
+= strlen(nbuf
) + 1;
1511 reply(550, "No files found.");
1513 if (ferror(dout
) != 0)
1514 perror_reply(550, "Data connection");
1516 reply(226, "Transfer complete.");
1527 * clobber argv so ps will show what we're doing.
1528 * (stolen from sendmail)
1529 * warning, since this is usually started from inetd.conf, it
1530 * often doesn't have much of an environment or arglist to overwrite.
1532 VOIDRET setproctitle
FUNCTION((fmt
, a
, b
, c
), char *fmt AND
int a AND
int b AND
int c
)
1534 register char *p
, *bp
, ch
;
1538 snprintf(buf
, sizeof(buf
), fmt
, a
, b
, c
);
1540 /* make ps print our process name */
1545 if (i
> LastArgv
- p
- 2) {
1546 i
= LastArgv
- p
- 2;
1551 if (ch
!= '\n' && ch
!= '\r')
1553 while (p
< LastArgv
)
1556 #endif /* DOTITLE */
1558 VOIDRET catchexit FUNCTION_NOARGS
1563 int main
FUNCTION((argc
, argv
, envp
), int argc AND
char *argv
[] AND
char *envp
[])
1565 int addrlen
, on
= 1;
1574 for (i
= sysconf(_SC_OPEN_MAX
); i
> 2; i
--)
1578 /* LOG_NDELAY sets up the logging connection immediately, necessary for
1579 anonymous ftp's that chroot and can't do it later. */
1580 openlog("ftpd", LOG_PID
| LOG_NDELAY
, LOG_DAEMON
);
1582 addrlen
= sizeof(his_addr
);
1583 if (getpeername(0, (struct sockaddr
*) & his_addr
, &addrlen
) < 0) {
1584 syslog(LOG_ERR
, "getpeername (%s): %m", argv
[0]);
1587 addrlen
= sizeof(ctrl_addr
);
1588 if (getsockname(0, (struct sockaddr
*) & ctrl_addr
, &addrlen
) < 0) {
1589 syslog(LOG_ERR
, "getsockname (%s): %m", argv
[0]);
1593 tos
= IPTOS_LOWDELAY
;
1594 if (setsockopt(0, IPPROTO_IP
, IP_TOS
, (char *) &tos
, sizeof(int)) < 0)
1595 syslog(LOG_WARNING
, "setsockopt (IP_TOS): %m");
1597 data_source
.sin_port
= htons(ntohs(ctrl_addr
.sin_port
) - 1);
1600 /* Save start and extent of argv for setproctitle. */
1604 LastArgv
= envp
[-1] + strlen(envp
[-1]);
1605 #endif /* DOTITLE */
1608 while (argc
> 0 && *argv
[0] == '-') {
1609 for (cp
= &argv
[0][1]; *cp
; cp
++)
1624 timeout
= atoi(++cp
);
1625 if (maxtimeout
< timeout
)
1626 maxtimeout
= timeout
;
1630 maxtimeout
= atoi(++cp
);
1631 if (timeout
> maxtimeout
)
1632 timeout
= maxtimeout
;
1639 while (*++cp
&& *cp
>= '0' && *cp
<= '9')
1640 val
= val
* 8 + *cp
- '0';
1642 fprintf(stderr
, "ftpd: Bad value for -u\n");
1649 fprintf(stderr
, "ftpd: Unknown flag -%c ignored.\n",
1656 freopen(_PATH_DEVNULL
, "w", stderr
);
1657 signal(SIGCHLD
, SIG_IGN
);
1658 enable_signalling();
1660 /* Try to handle urgent data inline */
1662 if (setsockopt(0, SOL_SOCKET
, SO_OOBINLINE
, (char *) &on
, sizeof(on
)) < 0)
1663 syslog(LOG_ERR
, "setsockopt: %m");
1667 if (fcntl(fileno(stdin
), F_SETOWN
, getpid()) == -1)
1668 syslog(LOG_ERR
, "fcntl F_SETOWN: %m");
1671 /* Set up default state */
1678 af_pwok
= opieaccessfile(remotehost
);
1684 /* If logins are disabled, print out the message. */
1685 if ((fd
= fopen(_PATH_NOLOGIN
,"r")) != NULL
) {
1686 while (fgets(line
, sizeof(line
), fd
) != NULL
) {
1687 if ((cp
= strchr(line
, '\n')) != NULL
)
1689 lreply(530, "%s", line
);
1691 (void) fflush(stdout
);
1693 reply(530, "System not available.");
1696 if ((fd
= fopen(_PATH_FTPWELCOME
, "r")) != NULL
) {
1697 while (fgets(line
, sizeof(line
), fd
) != NULL
) {
1698 if ((cp
= strchr(line
, '\n')) != NULL
)
1700 lreply(220, "%s", line
);
1702 (void) fflush(stdout
);
1704 /* reply(220,) must follow */
1708 reply(220, "FTP server ready.");